diff --git a/node_modules/mapbox-gl/src/shaders/symbol_text_and_icon.vertex.glsl b/node_modules/mapbox-gl/src/shaders/symbol_text_and_icon.vertex.glsl new file mode 100644 index 0000000000000000000000000000000000000000..647310fc9c9f81d50731307d9e5546044f2a4de6 --- /dev/null +++ b/node_modules/mapbox-gl/src/shaders/symbol_text_and_icon.vertex.glsl @@ -0,0 +1,116 @@ +const float PI = 3.141592653589793; + +attribute vec4 a_pos_offset; +attribute vec4 a_data; +attribute vec3 a_projected_pos; +attribute float a_fade_opacity; + +// contents of a_size vary based on the type of property value +// used for {text,icon}-size. +// For constants, a_size is disabled. +// For source functions, we bind only one value per vertex: the value of {text,icon}-size evaluated for the current feature. +// For composite functions: +// [ text-size(lowerZoomStop, feature), +// text-size(upperZoomStop, feature) ] +uniform bool u_is_size_zoom_constant; +uniform bool u_is_size_feature_constant; +uniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function +uniform highp float u_size; // used when size is both zoom and feature constant +uniform mat4 u_matrix; +uniform mat4 u_label_plane_matrix; +uniform mat4 u_coord_matrix; +uniform bool u_is_text; +uniform bool u_pitch_with_map; +uniform highp float u_pitch; +uniform bool u_rotate_symbol; +uniform highp float u_aspect_ratio; +uniform highp float u_camera_to_center_distance; +uniform float u_fade_change; +uniform vec2 u_texsize; +uniform vec2 u_texsize_icon; + +varying vec4 v_data0; +varying vec4 v_data1; + +#pragma mapbox: define highp vec4 fill_color +#pragma mapbox: define highp vec4 halo_color +#pragma mapbox: define lowp float opacity +#pragma mapbox: define lowp float halo_width +#pragma mapbox: define lowp float halo_blur + +void main() { + #pragma mapbox: initialize highp vec4 fill_color + #pragma mapbox: initialize highp vec4 halo_color + #pragma mapbox: initialize lowp float opacity + #pragma mapbox: initialize lowp float halo_width + #pragma mapbox: initialize lowp float halo_blur + + vec2 a_pos = a_pos_offset.xy; + vec2 a_offset = a_pos_offset.zw; + + vec2 a_tex = a_data.xy; + vec2 a_size = a_data.zw; + + float a_size_min = floor(a_size[0] * 0.5); + float is_sdf = a_size[0] - 2.0 * a_size_min; + + highp float segment_angle = -a_projected_pos[2]; + float size; + + if (!u_is_size_zoom_constant && !u_is_size_feature_constant) { + size = mix(a_size_min, a_size[1], u_size_t) / 128.0; + } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) { + size = a_size_min / 128.0; + } else { + size = u_size; + } + + vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1); + highp float camera_to_anchor_distance = projectedPoint.w; + // If the label is pitched with the map, layout is done in pitched space, + // which makes labels in the distance smaller relative to viewport space. + // We counteract part of that effect by multiplying by the perspective ratio. + // If the label isn't pitched with the map, we do layout in viewport space, + // which makes labels in the distance larger relative to the features around + // them. We counteract part of that effect by dividing by the perspective ratio. + highp float distance_ratio = u_pitch_with_map ? + camera_to_anchor_distance / u_camera_to_center_distance : + u_camera_to_center_distance / camera_to_anchor_distance; + highp float perspective_ratio = clamp( + 0.5 + 0.5 * distance_ratio, + 0.0, // Prevents oversized near-field symbols in pitched/overzoomed tiles + 4.0); + + size *= perspective_ratio; + + float fontScale = size / 24.0; + + highp float symbol_rotation = 0.0; + if (u_rotate_symbol) { + // Point labels with 'rotation-alignment: map' are horizontal with respect to tile units + // To figure out that angle in projected space, we draw a short horizontal line in tile + // space, project it, and measure its angle in projected space. + vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1); + + vec2 a = projectedPoint.xy / projectedPoint.w; + vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w; + + symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x); + } + + highp float angle_sin = sin(segment_angle + symbol_rotation); + highp float angle_cos = cos(segment_angle + symbol_rotation); + mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos); + + vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0); + gl_Position = u_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 32.0 * fontScale), 0.0, 1.0); + float gamma_scale = gl_Position.w; + + vec2 fade_opacity = unpack_opacity(a_fade_opacity); + float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change; + float interpolated_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change)); + + v_data0.xy = a_tex / u_texsize; + v_data0.zw = a_tex / u_texsize_icon; + v_data1 = vec4(gamma_scale, size, interpolated_fade_opacity, is_sdf); +} diff --git a/node_modules/mapbox-gl/src/source/canvas_source.js b/node_modules/mapbox-gl/src/source/canvas_source.js new file mode 100644 index 0000000000000000000000000000000000000000..54b65ce2454c3d4ec8bf9b498fa0cd499441bf1b --- /dev/null +++ b/node_modules/mapbox-gl/src/source/canvas_source.js @@ -0,0 +1,238 @@ +// @flow + +import ImageSource from './image_source'; + +import window from '../util/window'; +import rasterBoundsAttributes from '../data/raster_bounds_attributes'; +import SegmentVector from '../data/segment'; +import Texture from '../render/texture'; +import {ErrorEvent} from '../util/evented'; +import ValidationError from '../style-spec/error/validation_error'; + +import type Map from '../ui/map'; +import type Dispatcher from '../util/dispatcher'; +import type {Evented} from '../util/evented'; + +export type CanvasSourceSpecification = {| + "type": "canvas", + "coordinates": [[number, number], [number, number], [number, number], [number, number]], + "animate"?: boolean, + "canvas": string | HTMLCanvasElement +|}; + +/** + * Options to add a canvas source type to the map. + * + * @typedef {Object} CanvasSourceOptions + * @property {string} type Source type. Must be `"canvas"`. + * @property {string|HTMLCanvasElement} canvas Canvas source from which to read pixels. Can be a string representing the ID of the canvas element, or the `HTMLCanvasElement` itself. + * @property {Array>} coordinates Four geographical coordinates denoting where to place the corners of the canvas, specified in `[longitude, latitude]` pairs. + * @property {boolean} [animate=true] Whether the canvas source is animated. If the canvas is static (i.e. pixels do not need to be re-read on every frame), `animate` should be set to `false` to improve performance. + */ + +/** + * A data source containing the contents of an HTML canvas. See {@link CanvasSourceOptions} for detailed documentation of options. + * + * @example + * // add to map + * map.addSource('some id', { + * type: 'canvas', + * canvas: 'idOfMyHTMLCanvas', + * animate: true, + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update + * var mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * map.removeSource('some id'); // remove + */ +class CanvasSource extends ImageSource { + options: CanvasSourceSpecification; + animate: boolean; + canvas: HTMLCanvasElement; + width: number; + height: number; + play: () => void; + pause: () => void; + _playing: boolean; + + /** + * @private + */ + constructor(id: string, options: CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) { + super(id, options, dispatcher, eventedParent); + + // We build in some validation here, since canvas sources aren't included in the style spec: + if (!options.coordinates) { + this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'missing required property "coordinates"'))); + } else if (!Array.isArray(options.coordinates) || options.coordinates.length !== 4 || + options.coordinates.some(c => !Array.isArray(c) || c.length !== 2 || c.some(l => typeof l !== 'number'))) { + this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, '"coordinates" property must be an array of 4 longitude/latitude array pairs'))); + } + + if (options.animate && typeof options.animate !== 'boolean') { + this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'optional "animate" property must be a boolean value'))); + } + + if (!options.canvas) { + this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'missing required property "canvas"'))); + } else if (typeof options.canvas !== 'string' && !(options.canvas instanceof window.HTMLCanvasElement)) { + this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, '"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))); + } + + this.options = options; + this.animate = options.animate !== undefined ? options.animate : true; + } + + /** + * Enables animation. The image will be copied from the canvas to the map on each frame. + * @method play + * @instance + * @memberof CanvasSource + */ + + /** + * Disables animation. The map will display a static copy of the canvas image. + * @method pause + * @instance + * @memberof CanvasSource + */ + + load() { + this._loaded = true; + if (!this.canvas) { + this.canvas = (this.options.canvas instanceof window.HTMLCanvasElement) ? + this.options.canvas : + window.document.getElementById(this.options.canvas); + } + this.width = this.canvas.width; + this.height = this.canvas.height; + + if (this._hasInvalidDimensions()) { + this.fire(new ErrorEvent(new Error('Canvas dimensions cannot be less than or equal to zero.'))); + return; + } + + this.play = function() { + this._playing = true; + this.map.triggerRepaint(); + }; + + this.pause = function() { + if (this._playing) { + this.prepare(); + this._playing = false; + } + }; + + this._finishLoading(); + } + + /** + * Returns the HTML `canvas` element. + * + * @returns {HTMLCanvasElement} The HTML `canvas` element. + */ + getCanvas() { + return this.canvas; + } + + onAdd(map: Map) { + this.map = map; + this.load(); + if (this.canvas) { + if (this.animate) this.play(); + } + } + + onRemove() { + this.pause(); + } + + /** + * Sets the canvas's coordinates and re-renders the map. + * + * @method setCoordinates + * @instance + * @memberof CanvasSource + * @param {Array>} coordinates Four geographical coordinates, + * represented as arrays of longitude and latitude numbers, which define the corners of the canvas. + * The coordinates start at the top left corner of the canvas and proceed in clockwise order. + * They do not have to represent a rectangle. + * @returns {CanvasSource} this + */ + // setCoordinates inherited from ImageSource + + prepare() { + let resize = false; + if (this.canvas.width !== this.width) { + this.width = this.canvas.width; + resize = true; + } + if (this.canvas.height !== this.height) { + this.height = this.canvas.height; + resize = true; + } + + if (this._hasInvalidDimensions()) return; + + if (Object.keys(this.tiles).length === 0) return; // not enough data for current position + + const context = this.map.painter.context; + const gl = context.gl; + + if (!this.boundsBuffer) { + this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members); + } + + if (!this.boundsSegments) { + this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2); + } + + if (!this.texture) { + this.texture = new Texture(context, this.canvas, gl.RGBA, {premultiply: true}); + } else if (resize || this._playing) { + this.texture.update(this.canvas, {premultiply: true}); + } + + for (const w in this.tiles) { + const tile = this.tiles[w]; + if (tile.state !== 'loaded') { + tile.state = 'loaded'; + tile.texture = this.texture; + } + } + } + + serialize(): Object { + return { + type: 'canvas', + coordinates: this.coordinates + }; + } + + hasTransition() { + return this._playing; + } + + _hasInvalidDimensions() { + for (const x of [this.canvas.width, this.canvas.height]) { + if (isNaN(x) || x <= 0) return true; + } + return false; + } +} + +export default CanvasSource; diff --git a/node_modules/mapbox-gl/src/source/geojson_source.js b/node_modules/mapbox-gl/src/source/geojson_source.js new file mode 100644 index 0000000000000000000000000000000000000000..b822900513dfd873fcdf416c7de36bba7659c3f1 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/geojson_source.js @@ -0,0 +1,370 @@ +// @flow + +import {Event, ErrorEvent, Evented} from '../util/evented'; + +import {extend} from '../util/util'; +import EXTENT from '../data/extent'; +import {ResourceType} from '../util/ajax'; +import browser from '../util/browser'; + +import type {Source} from './source'; +import type Map from '../ui/map'; +import type Dispatcher from '../util/dispatcher'; +import type Tile from './tile'; +import type Actor from '../util/actor'; +import type {Callback} from '../types/callback'; +import type {GeoJSON, GeoJSONFeature} from '@mapbox/geojson-types'; +import type {GeoJSONSourceSpecification, PromoteIdSpecification} from '../style-spec/types'; + +/** + * A source containing GeoJSON. + * (See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-geojson) for detailed documentation of options.) + * + * @example + * map.addSource('some id', { + * type: 'geojson', + * data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson' + * }); + * + * @example + * map.addSource('some id', { + * type: 'geojson', + * data: { + * "type": "FeatureCollection", + * "features": [{ + * "type": "Feature", + * "properties": {}, + * "geometry": { + * "type": "Point", + * "coordinates": [ + * -76.53063297271729, + * 39.18174077994108 + * ] + * } + * }] + * } + * }); + * + * @example + * map.getSource('some id').setData({ + * "type": "FeatureCollection", + * "features": [{ + * "type": "Feature", + * "properties": { "name": "Null Island" }, + * "geometry": { + * "type": "Point", + * "coordinates": [ 0, 0 ] + * } + * }] + * }); + * @see [Draw GeoJSON points](https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/) + * @see [Add a GeoJSON line](https://www.mapbox.com/mapbox-gl-js/example/geojson-line/) + * @see [Create a heatmap from points](https://www.mapbox.com/mapbox-gl-js/example/heatmap/) + * @see [Create and style clusters](https://www.mapbox.com/mapbox-gl-js/example/cluster/) + */ +class GeoJSONSource extends Evented implements Source { + type: 'geojson'; + id: string; + minzoom: number; + maxzoom: number; + tileSize: number; + attribution: string; + promoteId: ?PromoteIdSpecification; + + isTileClipped: boolean; + reparseOverscaled: boolean; + _data: GeoJSON | string; + _options: any; + workerOptions: any; + map: Map; + actor: Actor; + _loaded: boolean; + _collectResourceTiming: boolean; + _resourceTiming: Array; + _removed: boolean; + + /** + * @private + */ + constructor(id: string, options: GeoJSONSourceSpecification & {workerOptions?: any, collectResourceTiming: boolean}, dispatcher: Dispatcher, eventedParent: Evented) { + super(); + + this.id = id; + + // `type` is a property rather than a constant to make it easy for 3rd + // parties to use GeoJSONSource to build their own source types. + this.type = 'geojson'; + + this.minzoom = 0; + this.maxzoom = 18; + this.tileSize = 512; + this.isTileClipped = true; + this.reparseOverscaled = true; + this._removed = false; + this._loaded = false; + + this.actor = dispatcher.getActor(); + this.setEventedParent(eventedParent); + + this._data = (options.data: any); + this._options = extend({}, options); + + this._collectResourceTiming = options.collectResourceTiming; + this._resourceTiming = []; + + if (options.maxzoom !== undefined) this.maxzoom = options.maxzoom; + if (options.type) this.type = options.type; + if (options.attribution) this.attribution = options.attribution; + this.promoteId = options.promoteId; + + const scale = EXTENT / this.tileSize; + + // sent to the worker, along with `url: ...` or `data: literal geojson`, + // so that it can load/parse/index the geojson data + // extending with `options.workerOptions` helps to make it easy for + // third-party sources to hack/reuse GeoJSONSource. + this.workerOptions = extend({ + source: this.id, + cluster: options.cluster || false, + geojsonVtOptions: { + buffer: (options.buffer !== undefined ? options.buffer : 128) * scale, + tolerance: (options.tolerance !== undefined ? options.tolerance : 0.375) * scale, + extent: EXTENT, + maxZoom: this.maxzoom, + lineMetrics: options.lineMetrics || false, + generateId: options.generateId || false + }, + superclusterOptions: { + maxZoom: options.clusterMaxZoom !== undefined ? + Math.min(options.clusterMaxZoom, this.maxzoom - 1) : + (this.maxzoom - 1), + minPoints: Math.max(2, options.clusterMinPoints || 2), + extent: EXTENT, + radius: (options.clusterRadius || 50) * scale, + log: false, + generateId: options.generateId || false + }, + clusterProperties: options.clusterProperties, + filter: options.filter + }, options.workerOptions); + } + + load() { + this.fire(new Event('dataloading', {dataType: 'source'})); + this._updateWorkerData((err) => { + if (err) { + this.fire(new ErrorEvent(err)); + return; + } + + const data: Object = {dataType: 'source', sourceDataType: 'metadata'}; + if (this._collectResourceTiming && this._resourceTiming && (this._resourceTiming.length > 0)) { + data.resourceTiming = this._resourceTiming; + this._resourceTiming = []; + } + + // although GeoJSON sources contain no metadata, we fire this event to let the SourceCache + // know its ok to start requesting tiles. + this.fire(new Event('data', data)); + }); + } + + onAdd(map: Map) { + this.map = map; + this.load(); + } + + /** + * Sets the GeoJSON data and re-renders the map. + * + * @param {Object|string} data A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files. + * @returns {GeoJSONSource} this + */ + setData(data: GeoJSON | string) { + this._data = data; + this.fire(new Event('dataloading', {dataType: 'source'})); + this._updateWorkerData((err) => { + if (err) { + this.fire(new ErrorEvent(err)); + return; + } + + const data: Object = {dataType: 'source', sourceDataType: 'content'}; + if (this._collectResourceTiming && this._resourceTiming && (this._resourceTiming.length > 0)) { + data.resourceTiming = this._resourceTiming; + this._resourceTiming = []; + } + this.fire(new Event('data', data)); + }); + + return this; + } + + /** + * For clustered sources, fetches the zoom at which the given cluster expands. + * + * @param clusterId The value of the cluster's `cluster_id` property. + * @param callback A callback to be called when the zoom value is retrieved (`(error, zoom) => { ... }`). + * @returns {GeoJSONSource} this + */ + getClusterExpansionZoom(clusterId: number, callback: Callback) { + this.actor.send('geojson.getClusterExpansionZoom', {clusterId, source: this.id}, callback); + return this; + } + + /** + * For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features). + * + * @param clusterId The value of the cluster's `cluster_id` property. + * @param callback A callback to be called when the features are retrieved (`(error, features) => { ... }`). + * @returns {GeoJSONSource} this + */ + getClusterChildren(clusterId: number, callback: Callback>) { + this.actor.send('geojson.getClusterChildren', {clusterId, source: this.id}, callback); + return this; + } + + /** + * For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features). + * + * @param clusterId The value of the cluster's `cluster_id` property. + * @param limit The maximum number of features to return. + * @param offset The number of features to skip (e.g. for pagination). + * @param callback A callback to be called when the features are retrieved (`(error, features) => { ... }`). + * @returns {GeoJSONSource} this + * @example + * // Retrieve cluster leaves on click + * map.on('click', 'clusters', function(e) { + * var features = map.queryRenderedFeatures(e.point, { + * layers: ['clusters'] + * }); + * + * var clusterId = features[0].properties.cluster_id; + * var pointCount = features[0].properties.point_count; + * var clusterSource = map.getSource('clusters'); + * + * clusterSource.getClusterLeaves(clusterId, pointCount, 0, function(error, features) { + * // Print cluster leaves in the console + * console.log('Cluster leaves:', error, features); + * }) + * }); + */ + getClusterLeaves(clusterId: number, limit: number, offset: number, callback: Callback>) { + this.actor.send('geojson.getClusterLeaves', { + source: this.id, + clusterId, + limit, + offset + }, callback); + return this; + } + + /* + * Responsible for invoking WorkerSource's geojson.loadData target, which + * handles loading the geojson data and preparing to serve it up as tiles, + * using geojson-vt or supercluster as appropriate. + */ + _updateWorkerData(callback: Callback) { + this._loaded = false; + const options = extend({}, this.workerOptions); + const data = this._data; + if (typeof data === 'string') { + options.request = this.map._requestManager.transformRequest(browser.resolveURL(data), ResourceType.Source); + options.request.collectResourceTiming = this._collectResourceTiming; + } else { + options.data = JSON.stringify(data); + } + + // target {this.type}.loadData rather than literally geojson.loadData, + // so that other geojson-like source types can easily reuse this + // implementation + this.actor.send(`${this.type}.loadData`, options, (err, result) => { + if (this._removed || (result && result.abandoned)) { + return; + } + + this._loaded = true; + + if (result && result.resourceTiming && result.resourceTiming[this.id]) + this._resourceTiming = result.resourceTiming[this.id].slice(0); + // Any `loadData` calls that piled up while we were processing + // this one will get coalesced into a single call when this + // 'coalesce' message is processed. + // We would self-send from the worker if we had access to its + // message queue. Waiting instead for the 'coalesce' to round-trip + // through the foreground just means we're throttling the worker + // to run at a little less than full-throttle. + this.actor.send(`${this.type}.coalesce`, {source: options.source}, null); + callback(err); + }); + } + + loaded(): boolean { + return this._loaded; + } + + loadTile(tile: Tile, callback: Callback) { + const message = !tile.actor ? 'loadTile' : 'reloadTile'; + tile.actor = this.actor; + const params = { + type: this.type, + uid: tile.uid, + tileID: tile.tileID, + zoom: tile.tileID.overscaledZ, + maxZoom: this.maxzoom, + tileSize: this.tileSize, + source: this.id, + pixelRatio: browser.devicePixelRatio, + showCollisionBoxes: this.map.showCollisionBoxes, + promoteId: this.promoteId + }; + + tile.request = this.actor.send(message, params, (err, data) => { + delete tile.request; + tile.unloadVectorData(); + + if (tile.aborted) { + return callback(null); + } + + if (err) { + return callback(err); + } + + tile.loadVectorData(data, this.map.painter, message === 'reloadTile'); + + return callback(null); + }); + } + + abortTile(tile: Tile) { + if (tile.request) { + tile.request.cancel(); + delete tile.request; + } + tile.aborted = true; + } + + unloadTile(tile: Tile) { + tile.unloadVectorData(); + this.actor.send('removeTile', {uid: tile.uid, type: this.type, source: this.id}); + } + + onRemove() { + this._removed = true; + this.actor.send('removeSource', {type: this.type, source: this.id}); + } + + serialize() { + return extend({}, this._options, { + type: this.type, + data: this._data + }); + } + + hasTransition() { + return false; + } +} + +export default GeoJSONSource; diff --git a/node_modules/mapbox-gl/src/source/geojson_worker_source.js b/node_modules/mapbox-gl/src/source/geojson_worker_source.js new file mode 100644 index 0000000000000000000000000000000000000000..a395a6fbbed6636125948113e73c84793afcbb28 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/geojson_worker_source.js @@ -0,0 +1,366 @@ +// @flow + +import {getJSON} from '../util/ajax'; + +import {RequestPerformance} from '../util/performance'; +import rewind from '@mapbox/geojson-rewind'; +import GeoJSONWrapper from './geojson_wrapper'; +import vtpbf from 'vt-pbf'; +import Supercluster from 'supercluster'; +import geojsonvt from 'geojson-vt'; +import assert from 'assert'; +import VectorTileWorkerSource from './vector_tile_worker_source'; +import {createExpression} from '../style-spec/expression'; + +import type { + WorkerTileParameters, + WorkerTileCallback, +} from '../source/worker_source'; + +import type Actor from '../util/actor'; +import type StyleLayerIndex from '../style/style_layer_index'; + +import type {LoadVectorDataCallback} from './vector_tile_worker_source'; +import type {RequestParameters, ResponseCallback} from '../util/ajax'; +import type {Callback} from '../types/callback'; +import type {GeoJSONFeature} from '@mapbox/geojson-types'; + +export type LoadGeoJSONParameters = { + request?: RequestParameters, + data?: string, + source: string, + cluster: boolean, + superclusterOptions?: Object, + geojsonVtOptions?: Object, + clusterProperties?: Object, + filter?: Array +}; + +export type LoadGeoJSON = (params: LoadGeoJSONParameters, callback: ResponseCallback) => void; + +export interface GeoJSONIndex { + getTile(z: number, x: number, y: number): Object; + + // supercluster methods + getClusterExpansionZoom(clusterId: number): number; + getChildren(clusterId: number): Array; + getLeaves(clusterId: number, limit: number, offset: number): Array; +} + +function loadGeoJSONTile(params: WorkerTileParameters, callback: LoadVectorDataCallback) { + const canonical = params.tileID.canonical; + + if (!this._geoJSONIndex) { + return callback(null, null); // we couldn't load the file + } + + const geoJSONTile = this._geoJSONIndex.getTile(canonical.z, canonical.x, canonical.y); + if (!geoJSONTile) { + return callback(null, null); // nothing in the given tile + } + + const geojsonWrapper = new GeoJSONWrapper(geoJSONTile.features); + + // Encode the geojson-vt tile into binary vector tile form. This + // is a convenience that allows `FeatureIndex` to operate the same way + // across `VectorTileSource` and `GeoJSONSource` data. + let pbf = vtpbf(geojsonWrapper); + if (pbf.byteOffset !== 0 || pbf.byteLength !== pbf.buffer.byteLength) { + // Compatibility with node Buffer (https://github.com/mapbox/pbf/issues/35) + pbf = new Uint8Array(pbf); + } + + callback(null, { + vectorTile: geojsonWrapper, + rawData: pbf.buffer + }); +} + +export type SourceState = + | 'Idle' // Source empty or data loaded + | 'Coalescing' // Data finished loading, but discard 'loadData' messages until receiving 'coalesced' + | 'NeedsLoadData'; // 'loadData' received while coalescing, trigger one more 'loadData' on receiving 'coalesced' + +/** + * The {@link WorkerSource} implementation that supports {@link GeoJSONSource}. + * This class is designed to be easily reused to support custom source types + * for data formats that can be parsed/converted into an in-memory GeoJSON + * representation. To do so, create it with + * `new GeoJSONWorkerSource(actor, layerIndex, customLoadGeoJSONFunction)`. + * For a full example, see [mapbox-gl-topojson](https://github.com/developmentseed/mapbox-gl-topojson). + * + * @private + */ +class GeoJSONWorkerSource extends VectorTileWorkerSource { + loadGeoJSON: LoadGeoJSON; + _state: SourceState; + _pendingCallback: Callback<{ + resourceTiming?: {[_: string]: Array}, + abandoned?: boolean }>; + _pendingLoadDataParams: LoadGeoJSONParameters; + _geoJSONIndex: GeoJSONIndex + + /** + * @param [loadGeoJSON] Optional method for custom loading/parsing of + * GeoJSON based on parameters passed from the main-thread Source. + * See {@link GeoJSONWorkerSource#loadGeoJSON}. + * @private + */ + constructor(actor: Actor, layerIndex: StyleLayerIndex, availableImages: Array, loadGeoJSON: ?LoadGeoJSON) { + super(actor, layerIndex, availableImages, loadGeoJSONTile); + if (loadGeoJSON) { + this.loadGeoJSON = loadGeoJSON; + } + } + + /** + * Fetches (if appropriate), parses, and index geojson data into tiles. This + * preparatory method must be called before {@link GeoJSONWorkerSource#loadTile} + * can correctly serve up tiles. + * + * Defers to {@link GeoJSONWorkerSource#loadGeoJSON} for the fetching/parsing, + * expecting `callback(error, data)` to be called with either an error or a + * parsed GeoJSON object. + * + * When `loadData` requests come in faster than they can be processed, + * they are coalesced into a single request using the latest data. + * See {@link GeoJSONWorkerSource#coalesce} + * + * @param params + * @param callback + * @private + */ + loadData(params: LoadGeoJSONParameters, callback: Callback<{ + resourceTiming?: {[_: string]: Array}, + abandoned?: boolean }>) { + if (this._pendingCallback) { + // Tell the foreground the previous call has been abandoned + this._pendingCallback(null, {abandoned: true}); + } + this._pendingCallback = callback; + this._pendingLoadDataParams = params; + + if (this._state && + this._state !== 'Idle') { + this._state = 'NeedsLoadData'; + } else { + this._state = 'Coalescing'; + this._loadData(); + } + } + + /** + * Internal implementation: called directly by `loadData` + * or by `coalesce` using stored parameters. + */ + _loadData() { + if (!this._pendingCallback || !this._pendingLoadDataParams) { + assert(false); + return; + } + const callback = this._pendingCallback; + const params = this._pendingLoadDataParams; + delete this._pendingCallback; + delete this._pendingLoadDataParams; + + const perf = (params && params.request && params.request.collectResourceTiming) ? + new RequestPerformance(params.request) : false; + + this.loadGeoJSON(params, (err: ?Error, data: ?Object) => { + if (err || !data) { + return callback(err); + } else if (typeof data !== 'object') { + return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`)); + } else { + rewind(data, true); + + try { + if (params.filter) { + const compiled = createExpression(params.filter, {type: 'boolean', 'property-type': 'data-driven', overridable: false, transition: false}); + if (compiled.result === 'error') + throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', ')); + + const features = data.features.filter(feature => compiled.value.evaluate({zoom: 0}, feature)); + data = {type: 'FeatureCollection', features}; + } + + this._geoJSONIndex = params.cluster ? + new Supercluster(getSuperclusterOptions(params)).load(data.features) : + geojsonvt(data, params.geojsonVtOptions); + } catch (err) { + return callback(err); + } + + this.loaded = {}; + + const result = {}; + if (perf) { + const resourceTimingData = perf.finish(); + // it's necessary to eval the result of getEntriesByName() here via parse/stringify + // late evaluation in the main thread causes TypeError: illegal invocation + if (resourceTimingData) { + result.resourceTiming = {}; + result.resourceTiming[params.source] = JSON.parse(JSON.stringify(resourceTimingData)); + } + } + callback(null, result); + } + }); + } + + /** + * While processing `loadData`, we coalesce all further + * `loadData` messages into a single call to _loadData + * that will happen once we've finished processing the + * first message. {@link GeoJSONSource#_updateWorkerData} + * is responsible for sending us the `coalesce` message + * at the time it receives a response from `loadData` + * + * State: Idle + * ↑ | + * 'coalesce' 'loadData' + * | (triggers load) + * | ↓ + * State: Coalescing + * ↑ | + * (triggers load) | + * 'coalesce' 'loadData' + * | ↓ + * State: NeedsLoadData + */ + coalesce() { + if (this._state === 'Coalescing') { + this._state = 'Idle'; + } else if (this._state === 'NeedsLoadData') { + this._state = 'Coalescing'; + this._loadData(); + } + } + + /** + * Implements {@link WorkerSource#reloadTile}. + * + * If the tile is loaded, uses the implementation in VectorTileWorkerSource. + * Otherwise, such as after a setData() call, we load the tile fresh. + * + * @param params + * @param params.uid The UID for this tile. + * @private + */ + reloadTile(params: WorkerTileParameters, callback: WorkerTileCallback) { + const loaded = this.loaded, + uid = params.uid; + + if (loaded && loaded[uid]) { + return super.reloadTile(params, callback); + } else { + return this.loadTile(params, callback); + } + } + + /** + * Fetch and parse GeoJSON according to the given params. Calls `callback` + * with `(err, data)`, where `data` is a parsed GeoJSON object. + * + * GeoJSON is loaded and parsed from `params.url` if it exists, or else + * expected as a literal (string or object) `params.data`. + * + * @param params + * @param [params.url] A URL to the remote GeoJSON data. + * @param [params.data] Literal GeoJSON data. Must be provided if `params.url` is not. + * @private + */ + loadGeoJSON(params: LoadGeoJSONParameters, callback: ResponseCallback) { + // Because of same origin issues, urls must either include an explicit + // origin or absolute path. + // ie: /foo/bar.json or http://example.com/bar.json + // but not ../foo/bar.json + if (params.request) { + getJSON(params.request, callback); + } else if (typeof params.data === 'string') { + try { + return callback(null, JSON.parse(params.data)); + } catch (e) { + return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`)); + } + } else { + return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`)); + } + } + + removeSource(params: {source: string}, callback: Callback) { + if (this._pendingCallback) { + // Don't leak callbacks + this._pendingCallback(null, {abandoned: true}); + } + callback(); + } + + getClusterExpansionZoom(params: {clusterId: number}, callback: Callback) { + try { + callback(null, this._geoJSONIndex.getClusterExpansionZoom(params.clusterId)); + } catch (e) { + callback(e); + } + } + + getClusterChildren(params: {clusterId: number}, callback: Callback>) { + try { + callback(null, this._geoJSONIndex.getChildren(params.clusterId)); + } catch (e) { + callback(e); + } + } + + getClusterLeaves(params: {clusterId: number, limit: number, offset: number}, callback: Callback>) { + try { + callback(null, this._geoJSONIndex.getLeaves(params.clusterId, params.limit, params.offset)); + } catch (e) { + callback(e); + } + } +} + +function getSuperclusterOptions({superclusterOptions, clusterProperties}) { + if (!clusterProperties || !superclusterOptions) return superclusterOptions; + + const mapExpressions = {}; + const reduceExpressions = {}; + const globals = {accumulated: null, zoom: 0}; + const feature = {properties: null}; + const propertyNames = Object.keys(clusterProperties); + + for (const key of propertyNames) { + const [operator, mapExpression] = clusterProperties[key]; + + const mapExpressionParsed = createExpression(mapExpression); + const reduceExpressionParsed = createExpression( + typeof operator === 'string' ? [operator, ['accumulated'], ['get', key]] : operator); + + assert(mapExpressionParsed.result === 'success'); + assert(reduceExpressionParsed.result === 'success'); + + mapExpressions[key] = mapExpressionParsed.value; + reduceExpressions[key] = reduceExpressionParsed.value; + } + + superclusterOptions.map = (pointProperties) => { + feature.properties = pointProperties; + const properties = {}; + for (const key of propertyNames) { + properties[key] = mapExpressions[key].evaluate(globals, feature); + } + return properties; + }; + superclusterOptions.reduce = (accumulated, clusterProperties) => { + feature.properties = clusterProperties; + for (const key of propertyNames) { + globals.accumulated = accumulated[key]; + accumulated[key] = reduceExpressions[key].evaluate(globals, feature); + } + }; + + return superclusterOptions; +} + +export default GeoJSONWorkerSource; diff --git a/node_modules/mapbox-gl/src/source/geojson_wrapper.js b/node_modules/mapbox-gl/src/source/geojson_wrapper.js new file mode 100644 index 0000000000000000000000000000000000000000..35a23afd2c3123ba42ca87085ae5da450b077731 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/geojson_wrapper.js @@ -0,0 +1,94 @@ +// @flow + +import Point from '@mapbox/point-geometry'; + +import mvt from '@mapbox/vector-tile'; +const toGeoJSON = mvt.VectorTileFeature.prototype.toGeoJSON; +import EXTENT from '../data/extent'; + +// The feature type used by geojson-vt and supercluster. Should be extracted to +// global type and used in module definitions for those two modules. +type Feature = { + type: 1, + id: mixed, + tags: {[_: string]: string | number | boolean}, + geometry: Array<[number, number]>, +} | { + type: 2 | 3, + id: mixed, + tags: {[_: string]: string | number | boolean}, + geometry: Array>, +} + +class FeatureWrapper implements VectorTileFeature { + _feature: Feature; + + extent: number; + type: 1 | 2 | 3; + id: number; + properties: {[_: string]: string | number | boolean}; + + constructor(feature: Feature) { + this._feature = feature; + + this.extent = EXTENT; + this.type = feature.type; + this.properties = feature.tags; + + // If the feature has a top-level `id` property, copy it over, but only + // if it can be coerced to an integer, because this wrapper is used for + // serializing geojson feature data into vector tile PBF data, and the + // vector tile spec only supports integer values for feature ids -- + // allowing non-integer values here results in a non-compliant PBF + // that causes an exception when it is parsed with vector-tile-js + if ('id' in feature && !isNaN(feature.id)) { + this.id = parseInt(feature.id, 10); + } + } + + loadGeometry() { + if (this._feature.type === 1) { + const geometry = []; + for (const point of this._feature.geometry) { + geometry.push([new Point(point[0], point[1])]); + } + return geometry; + } else { + const geometry = []; + for (const ring of this._feature.geometry) { + const newRing = []; + for (const point of ring) { + newRing.push(new Point(point[0], point[1])); + } + geometry.push(newRing); + } + return geometry; + } + } + + toGeoJSON(x: number, y: number, z: number) { + return toGeoJSON.call(this, x, y, z); + } +} + +class GeoJSONWrapper implements VectorTile, VectorTileLayer { + layers: {[_: string]: VectorTileLayer}; + name: string; + extent: number; + length: number; + _features: Array; + + constructor(features: Array) { + this.layers = {'_geojsonTileLayer': this}; + this.name = '_geojsonTileLayer'; + this.extent = EXTENT; + this.length = features.length; + this._features = features; + } + + feature(i: number): VectorTileFeature { + return new FeatureWrapper(this._features[i]); + } +} + +export default GeoJSONWrapper; diff --git a/node_modules/mapbox-gl/src/source/image_source.js b/node_modules/mapbox-gl/src/source/image_source.js new file mode 100644 index 0000000000000000000000000000000000000000..6b548c374bb2a2390aa0b6382763093d3b2d55ec --- /dev/null +++ b/node_modules/mapbox-gl/src/source/image_source.js @@ -0,0 +1,307 @@ +// @flow + +import {CanonicalTileID} from './tile_id'; +import {Event, ErrorEvent, Evented} from '../util/evented'; +import {getImage, ResourceType} from '../util/ajax'; +import EXTENT from '../data/extent'; +import {RasterBoundsArray} from '../data/array_types'; +import rasterBoundsAttributes from '../data/raster_bounds_attributes'; +import SegmentVector from '../data/segment'; +import Texture from '../render/texture'; +import MercatorCoordinate from '../geo/mercator_coordinate'; + +import type {Source} from './source'; +import type {CanvasSourceSpecification} from './canvas_source'; +import type Map from '../ui/map'; +import type Dispatcher from '../util/dispatcher'; +import type Tile from './tile'; +import type {Callback} from '../types/callback'; +import type VertexBuffer from '../gl/vertex_buffer'; +import type { + ImageSourceSpecification, + VideoSourceSpecification +} from '../style-spec/types'; + +type Coordinates = [[number, number], [number, number], [number, number], [number, number]]; + +/** + * A data source containing an image. + * (See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-image) for detailed documentation of options.) + * + * @example + * // add to map + * map.addSource('some id', { + * type: 'image', + * url: 'https://www.mapbox.com/images/foo.png', + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update coordinates + * var mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * // update url and coordinates simultaneously + * mySource.updateImage({ + * url: 'https://www.mapbox.com/images/bar.png', + * coordinates: [ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ] + * }) + * + * map.removeSource('some id'); // remove + * @see [Add an image](https://www.mapbox.com/mapbox-gl-js/example/image-on-a-map/) + */ +class ImageSource extends Evented implements Source { + type: string; + id: string; + minzoom: number; + maxzoom: number; + tileSize: number; + url: string; + + coordinates: Coordinates; + tiles: {[_: string]: Tile}; + options: any; + dispatcher: Dispatcher; + map: Map; + texture: Texture | null; + image: HTMLImageElement | ImageBitmap; + tileID: CanonicalTileID; + _boundsArray: RasterBoundsArray; + boundsBuffer: VertexBuffer; + boundsSegments: SegmentVector; + _loaded: boolean; + + /** + * @private + */ + constructor(id: string, options: ImageSourceSpecification | VideoSourceSpecification | CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) { + super(); + this.id = id; + this.dispatcher = dispatcher; + this.coordinates = options.coordinates; + + this.type = 'image'; + this.minzoom = 0; + this.maxzoom = 22; + this.tileSize = 512; + this.tiles = {}; + this._loaded = false; + + this.setEventedParent(eventedParent); + + this.options = options; + } + + load(newCoordinates?: Coordinates, successCallback?: () => void) { + this._loaded = false; + this.fire(new Event('dataloading', {dataType: 'source'})); + + this.url = this.options.url; + + getImage(this.map._requestManager.transformRequest(this.url, ResourceType.Image), (err, image) => { + this._loaded = true; + if (err) { + this.fire(new ErrorEvent(err)); + } else if (image) { + this.image = image; + if (newCoordinates) { + this.coordinates = newCoordinates; + } + if (successCallback) { + successCallback(); + } + this._finishLoading(); + } + }); + } + + loaded(): boolean { + return this._loaded; + } + + /** + * Updates the image URL and, optionally, the coordinates. To avoid having the image flash after changing, + * set the `raster-fade-duration` paint property on the raster layer to 0. + * + * @param {Object} options Options object. + * @param {string} [options.url] Required image URL. + * @param {Array>} [options.coordinates] Four geographical coordinates, + * represented as arrays of longitude and latitude numbers, which define the corners of the image. + * The coordinates start at the top left corner of the image and proceed in clockwise order. + * They do not have to represent a rectangle. + * @returns {ImageSource} this + */ + updateImage(options: {url: string, coordinates?: Coordinates}) { + if (!this.image || !options.url) { + return this; + } + this.options.url = options.url; + this.load(options.coordinates, () => { this.texture = null; }); + return this; + } + + _finishLoading() { + if (this.map) { + this.setCoordinates(this.coordinates); + this.fire(new Event('data', {dataType: 'source', sourceDataType: 'metadata'})); + } + } + + onAdd(map: Map) { + this.map = map; + this.load(); + } + + /** + * Sets the image's coordinates and re-renders the map. + * + * @param {Array>} coordinates Four geographical coordinates, + * represented as arrays of longitude and latitude numbers, which define the corners of the image. + * The coordinates start at the top left corner of the image and proceed in clockwise order. + * They do not have to represent a rectangle. + * @returns {ImageSource} this + */ + setCoordinates(coordinates: Coordinates) { + this.coordinates = coordinates; + + // Calculate which mercator tile is suitable for rendering the video in + // and create a buffer with the corner coordinates. These coordinates + // may be outside the tile, because raster tiles aren't clipped when rendering. + + // transform the geo coordinates into (zoom 0) tile space coordinates + const cornerCoords = coordinates.map(MercatorCoordinate.fromLngLat); + + // Compute the coordinates of the tile we'll use to hold this image's + // render data + this.tileID = getCoordinatesCenterTileID(cornerCoords); + + // Constrain min/max zoom to our tile's zoom level in order to force + // SourceCache to request this tile (no matter what the map's zoom + // level) + this.minzoom = this.maxzoom = this.tileID.z; + + // Transform the corner coordinates into the coordinate space of our + // tile. + const tileCoords = cornerCoords.map((coord) => this.tileID.getTilePoint(coord)._round()); + + this._boundsArray = new RasterBoundsArray(); + this._boundsArray.emplaceBack(tileCoords[0].x, tileCoords[0].y, 0, 0); + this._boundsArray.emplaceBack(tileCoords[1].x, tileCoords[1].y, EXTENT, 0); + this._boundsArray.emplaceBack(tileCoords[3].x, tileCoords[3].y, 0, EXTENT); + this._boundsArray.emplaceBack(tileCoords[2].x, tileCoords[2].y, EXTENT, EXTENT); + + if (this.boundsBuffer) { + this.boundsBuffer.destroy(); + delete this.boundsBuffer; + } + + this.fire(new Event('data', {dataType:'source', sourceDataType: 'content'})); + return this; + } + + prepare() { + if (Object.keys(this.tiles).length === 0 || !this.image) { + return; + } + + const context = this.map.painter.context; + const gl = context.gl; + + if (!this.boundsBuffer) { + this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members); + } + + if (!this.boundsSegments) { + this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2); + } + + if (!this.texture) { + this.texture = new Texture(context, this.image, gl.RGBA); + this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + } + + for (const w in this.tiles) { + const tile = this.tiles[w]; + if (tile.state !== 'loaded') { + tile.state = 'loaded'; + tile.texture = this.texture; + } + } + } + + loadTile(tile: Tile, callback: Callback) { + // We have a single tile -- whoose coordinates are this.tileID -- that + // covers the image we want to render. If that's the one being + // requested, set it up with the image; otherwise, mark the tile as + // `errored` to indicate that we have no data for it. + // If the world wraps, we may have multiple "wrapped" copies of the + // single tile. + if (this.tileID && this.tileID.equals(tile.tileID.canonical)) { + this.tiles[String(tile.tileID.wrap)] = tile; + tile.buckets = {}; + callback(null); + } else { + tile.state = 'errored'; + callback(null); + } + } + + serialize(): Object { + return { + type: 'image', + url: this.options.url, + coordinates: this.coordinates + }; + } + + hasTransition() { + return false; + } +} + +/** + * Given a list of coordinates, get their center as a coordinate. + * + * @returns centerpoint + * @private + */ +export function getCoordinatesCenterTileID(coords: Array) { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + + for (const coord of coords) { + minX = Math.min(minX, coord.x); + minY = Math.min(minY, coord.y); + maxX = Math.max(maxX, coord.x); + maxY = Math.max(maxY, coord.y); + } + + const dx = maxX - minX; + const dy = maxY - minY; + const dMax = Math.max(dx, dy); + const zoom = Math.max(0, Math.floor(-Math.log(dMax) / Math.LN2)); + const tilesAtZoom = Math.pow(2, zoom); + + return new CanonicalTileID( + zoom, + Math.floor((minX + maxX) / 2 * tilesAtZoom), + Math.floor((minY + maxY) / 2 * tilesAtZoom)); +} + +export default ImageSource; diff --git a/node_modules/mapbox-gl/src/source/load_tilejson.js b/node_modules/mapbox-gl/src/source/load_tilejson.js new file mode 100644 index 0000000000000000000000000000000000000000..2f96df7f794b0a9b881b4187d011098726c1a94f --- /dev/null +++ b/node_modules/mapbox-gl/src/source/load_tilejson.js @@ -0,0 +1,39 @@ +// @flow + +import {pick, extend} from '../util/util'; + +import {getJSON, ResourceType} from '../util/ajax'; +import browser from '../util/browser'; + +import type {RequestManager} from '../util/mapbox'; +import type {Callback} from '../types/callback'; +import type {TileJSON} from '../types/tilejson'; +import type {Cancelable} from '../types/cancelable'; + +export default function(options: any, requestManager: RequestManager, callback: Callback): Cancelable { + const loaded = function(err: ?Error, tileJSON: ?Object) { + if (err) { + return callback(err); + } else if (tileJSON) { + const result: any = pick( + // explicit source options take precedence over TileJSON + extend(tileJSON, options), + ['tiles', 'minzoom', 'maxzoom', 'attribution', 'mapbox_logo', 'bounds', 'scheme', 'tileSize', 'encoding'] + ); + + if (tileJSON.vector_layers) { + result.vectorLayers = tileJSON.vector_layers; + result.vectorLayerIds = result.vectorLayers.map((layer) => { return layer.id; }); + } + + result.tiles = requestManager.canonicalizeTileset(result, options.url); + callback(null, result); + } + }; + + if (options.url) { + return getJSON(requestManager.transformRequest(requestManager.normalizeSourceURL(options.url), ResourceType.Source), loaded); + } else { + return browser.frame(() => loaded(null, options)); + } +} diff --git a/node_modules/mapbox-gl/src/source/pixels_to_tile_units.js b/node_modules/mapbox-gl/src/source/pixels_to_tile_units.js new file mode 100644 index 0000000000000000000000000000000000000000..7874396f30c791b182b9393da6f8a6f71d261d22 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/pixels_to_tile_units.js @@ -0,0 +1,21 @@ +// @flow + +import EXTENT from '../data/extent'; + +import type {OverscaledTileID} from './tile_id'; + +/** + * Converts a pixel value at a the given zoom level to tile units. + * + * The shaders mostly calculate everything in tile units so style + * properties need to be converted from pixels to tile units using this. + * + * For example, a translation by 30 pixels at zoom 6.5 will be a + * translation by pixelsToTileUnits(30, 6.5) tile units. + * + * @returns value in tile units + * @private + */ +export default function(tile: {tileID: OverscaledTileID, tileSize: number}, pixelValue: number, z: number): number { + return pixelValue * (EXTENT / (tile.tileSize * Math.pow(2, z - tile.tileID.overscaledZ))); +} diff --git a/node_modules/mapbox-gl/src/source/query_features.js b/node_modules/mapbox-gl/src/source/query_features.js new file mode 100644 index 0000000000000000000000000000000000000000..c7017b577be8d901224e4f8e368afd5ca82ba9c6 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/query_features.js @@ -0,0 +1,208 @@ +// @flow + +import type SourceCache from './source_cache'; +import type StyleLayer from '../style/style_layer'; +import type CollisionIndex from '../symbol/collision_index'; +import type Transform from '../geo/transform'; +import type {RetainedQueryData} from '../symbol/placement'; +import type {FilterSpecification} from '../style-spec/types'; +import assert from 'assert'; +import {mat4} from 'gl-matrix'; + +/* + * Returns a matrix that can be used to convert from tile coordinates to viewport pixel coordinates. + */ +function getPixelPosMatrix(transform, tileID) { + const t = mat4.identity([]); + mat4.translate(t, t, [1, 1, 0]); + mat4.scale(t, t, [transform.width * 0.5, transform.height * 0.5, 1]); + return mat4.multiply(t, t, transform.calculatePosMatrix(tileID.toUnwrapped())); +} + +function queryIncludes3DLayer(layers?: Array, styleLayers: {[_: string]: StyleLayer}, sourceID: string) { + if (layers) { + for (const layerID of layers) { + const layer = styleLayers[layerID]; + if (layer && layer.source === sourceID && layer.type === 'fill-extrusion') { + return true; + } + } + } else { + for (const key in styleLayers) { + const layer = styleLayers[key]; + if (layer.source === sourceID && layer.type === 'fill-extrusion') { + return true; + } + } + } + return false; +} + +export function queryRenderedFeatures(sourceCache: SourceCache, + styleLayers: {[_: string]: StyleLayer}, + serializedLayers: {[_: string]: Object}, + queryGeometry: Array, + params: { filter: FilterSpecification, layers: Array, availableImages: Array }, + transform: Transform) { + + const has3DLayer = queryIncludes3DLayer(params && params.layers, styleLayers, sourceCache.id); + const maxPitchScaleFactor = transform.maxPitchScaleFactor(); + const tilesIn = sourceCache.tilesIn(queryGeometry, maxPitchScaleFactor, has3DLayer); + + tilesIn.sort(sortTilesIn); + const renderedFeatureLayers = []; + for (const tileIn of tilesIn) { + renderedFeatureLayers.push({ + wrappedTileID: tileIn.tileID.wrapped().key, + queryResults: tileIn.tile.queryRenderedFeatures( + styleLayers, + serializedLayers, + sourceCache._state, + tileIn.queryGeometry, + tileIn.cameraQueryGeometry, + tileIn.scale, + params, + transform, + maxPitchScaleFactor, + getPixelPosMatrix(sourceCache.transform, tileIn.tileID)) + }); + } + + const result = mergeRenderedFeatureLayers(renderedFeatureLayers); + + // Merge state from SourceCache into the results + for (const layerID in result) { + result[layerID].forEach((featureWrapper) => { + const feature = featureWrapper.feature; + const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id); + feature.source = feature.layer.source; + if (feature.layer['source-layer']) { + feature.sourceLayer = feature.layer['source-layer']; + } + feature.state = state; + }); + } + return result; +} + +export function queryRenderedSymbols(styleLayers: {[_: string]: StyleLayer}, + serializedLayers: {[_: string]: StyleLayer}, + sourceCaches: {[_: string]: SourceCache}, + queryGeometry: Array, + params: { filter: FilterSpecification, layers: Array, availableImages: Array }, + collisionIndex: CollisionIndex, + retainedQueryData: {[_: number]: RetainedQueryData}) { + const result = {}; + const renderedSymbols = collisionIndex.queryRenderedSymbols(queryGeometry); + const bucketQueryData = []; + for (const bucketInstanceId of Object.keys(renderedSymbols).map(Number)) { + bucketQueryData.push(retainedQueryData[bucketInstanceId]); + } + bucketQueryData.sort(sortTilesIn); + + for (const queryData of bucketQueryData) { + const bucketSymbols = queryData.featureIndex.lookupSymbolFeatures( + renderedSymbols[queryData.bucketInstanceId], + serializedLayers, + queryData.bucketIndex, + queryData.sourceLayerIndex, + params.filter, + params.layers, + params.availableImages, + styleLayers); + + for (const layerID in bucketSymbols) { + const resultFeatures = result[layerID] = result[layerID] || []; + const layerSymbols = bucketSymbols[layerID]; + layerSymbols.sort((a, b) => { + // Match topDownFeatureComparator from FeatureIndex, but using + // most recent sorting of features from bucket.sortFeatures + const featureSortOrder = queryData.featureSortOrder; + if (featureSortOrder) { + // queryRenderedSymbols documentation says we'll return features in + // "top-to-bottom" rendering order (aka last-to-first). + // Actually there can be multiple symbol instances per feature, so + // we sort each feature based on the first matching symbol instance. + const sortedA = featureSortOrder.indexOf(a.featureIndex); + const sortedB = featureSortOrder.indexOf(b.featureIndex); + assert(sortedA >= 0); + assert(sortedB >= 0); + return sortedB - sortedA; + } else { + // Bucket hasn't been re-sorted based on angle, so use the + // reverse of the order the features appeared in the data. + return b.featureIndex - a.featureIndex; + } + }); + for (const symbolFeature of layerSymbols) { + resultFeatures.push(symbolFeature); + } + } + } + + // Merge state from SourceCache into the results + for (const layerName in result) { + result[layerName].forEach((featureWrapper) => { + const feature = featureWrapper.feature; + const layer = styleLayers[layerName]; + const sourceCache = sourceCaches[layer.source]; + const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id); + feature.source = feature.layer.source; + if (feature.layer['source-layer']) { + feature.sourceLayer = feature.layer['source-layer']; + } + feature.state = state; + }); + } + return result; +} + +export function querySourceFeatures(sourceCache: SourceCache, params: any) { + const tiles = sourceCache.getRenderableIds().map((id) => { + return sourceCache.getTileByID(id); + }); + + const result = []; + + const dataTiles = {}; + for (let i = 0; i < tiles.length; i++) { + const tile = tiles[i]; + const dataID = tile.tileID.canonical.key; + if (!dataTiles[dataID]) { + dataTiles[dataID] = true; + tile.querySourceFeatures(result, params); + } + } + + return result; +} + +function sortTilesIn(a, b) { + const idA = a.tileID; + const idB = b.tileID; + return (idA.overscaledZ - idB.overscaledZ) || (idA.canonical.y - idB.canonical.y) || (idA.wrap - idB.wrap) || (idA.canonical.x - idB.canonical.x); +} + +function mergeRenderedFeatureLayers(tiles) { + // Merge results from all tiles, but if two tiles share the same + // wrapped ID, don't duplicate features between the two tiles + const result = {}; + const wrappedIDLayerMap = {}; + for (const tile of tiles) { + const queryResults = tile.queryResults; + const wrappedID = tile.wrappedTileID; + const wrappedIDLayers = wrappedIDLayerMap[wrappedID] = wrappedIDLayerMap[wrappedID] || {}; + for (const layerID in queryResults) { + const tileFeatures = queryResults[layerID]; + const wrappedIDFeatures = wrappedIDLayers[layerID] = wrappedIDLayers[layerID] || {}; + const resultFeatures = result[layerID] = result[layerID] || []; + for (const tileFeature of tileFeatures) { + if (!wrappedIDFeatures[tileFeature.featureIndex]) { + wrappedIDFeatures[tileFeature.featureIndex] = true; + resultFeatures.push(tileFeature); + } + } + } + } + return result; +} diff --git a/node_modules/mapbox-gl/src/source/raster_dem_tile_source.js b/node_modules/mapbox-gl/src/source/raster_dem_tile_source.js new file mode 100644 index 0000000000000000000000000000000000000000..bd36edfdda71162136322e6106db5e638806c948 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/raster_dem_tile_source.js @@ -0,0 +1,138 @@ +// @flow + +import {getImage, ResourceType} from '../util/ajax'; +import {extend} from '../util/util'; +import {Evented} from '../util/evented'; +import browser from '../util/browser'; +import window from '../util/window'; +import offscreenCanvasSupported from '../util/offscreen_canvas_supported'; +import {OverscaledTileID} from './tile_id'; +import RasterTileSource from './raster_tile_source'; +// ensure DEMData is registered for worker transfer on main thread: +import '../data/dem_data'; + +import type {Source} from './source'; +import type Dispatcher from '../util/dispatcher'; +import type Tile from './tile'; +import type {Callback} from '../types/callback'; +import type {RasterDEMSourceSpecification} from '../style-spec/types'; + +class RasterDEMTileSource extends RasterTileSource implements Source { + encoding: "mapbox" | "terrarium"; + + constructor(id: string, options: RasterDEMSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) { + super(id, options, dispatcher, eventedParent); + this.type = 'raster-dem'; + this.maxzoom = 22; + this._options = extend({type: 'raster-dem'}, options); + this.encoding = options.encoding || "mapbox"; + } + + serialize() { + return { + type: 'raster-dem', + url: this.url, + tileSize: this.tileSize, + tiles: this.tiles, + bounds: this.bounds, + encoding: this.encoding + }; + } + + loadTile(tile: Tile, callback: Callback) { + const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), this.tileSize); + tile.request = getImage(this.map._requestManager.transformRequest(url, ResourceType.Tile), imageLoaded.bind(this)); + + tile.neighboringTiles = this._getNeighboringTiles(tile.tileID); + function imageLoaded(err, img) { + delete tile.request; + if (tile.aborted) { + tile.state = 'unloaded'; + callback(null); + } else if (err) { + tile.state = 'errored'; + callback(err); + } else if (img) { + if (this.map._refreshExpiredTiles) tile.setExpiryData(img); + delete (img: any).cacheControl; + delete (img: any).expires; + const transfer = window.ImageBitmap && img instanceof window.ImageBitmap && offscreenCanvasSupported(); + const rawImageData = transfer ? img : browser.getImageData(img, 1); + const params = { + uid: tile.uid, + coord: tile.tileID, + source: this.id, + rawImageData, + encoding: this.encoding + }; + + if (!tile.actor || tile.state === 'expired') { + tile.actor = this.dispatcher.getActor(); + tile.actor.send('loadDEMTile', params, done.bind(this)); + } + } + } + + function done(err, dem) { + if (err) { + tile.state = 'errored'; + callback(err); + } + + if (dem) { + tile.dem = dem; + tile.needsHillshadePrepare = true; + tile.state = 'loaded'; + callback(null); + } + } + } + + _getNeighboringTiles(tileID: OverscaledTileID) { + const canonical = tileID.canonical; + const dim = Math.pow(2, canonical.z); + + const px = (canonical.x - 1 + dim) % dim; + const pxw = canonical.x === 0 ? tileID.wrap - 1 : tileID.wrap; + const nx = (canonical.x + 1 + dim) % dim; + const nxw = canonical.x + 1 === dim ? tileID.wrap + 1 : tileID.wrap; + + const neighboringTiles = {}; + // add adjacent tiles + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y).key] = {backfilled: false}; + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y).key] = {backfilled: false}; + + // Add upper neighboringTiles + if (canonical.y > 0) { + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y - 1).key] = {backfilled: false}; + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y - 1).key] = {backfilled: false}; + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y - 1).key] = {backfilled: false}; + } + // Add lower neighboringTiles + if (canonical.y + 1 < dim) { + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y + 1).key] = {backfilled: false}; + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y + 1).key] = {backfilled: false}; + neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y + 1).key] = {backfilled: false}; + } + + return neighboringTiles; + } + + unloadTile(tile: Tile) { + if (tile.demTexture) this.map.painter.saveTileTexture(tile.demTexture); + if (tile.fbo) { + tile.fbo.destroy(); + delete tile.fbo; + } + if (tile.dem) delete tile.dem; + delete tile.neighboringTiles; + + tile.state = 'unloaded'; + if (tile.actor) { + tile.actor.send('removeDEMTile', {uid: tile.uid, source: this.id}); + } + } + +} + +export default RasterDEMTileSource; diff --git a/node_modules/mapbox-gl/src/source/raster_dem_tile_worker_source.js b/node_modules/mapbox-gl/src/source/raster_dem_tile_worker_source.js new file mode 100644 index 0000000000000000000000000000000000000000..416462ea16912bf88d245a6bd9a380926e56562d --- /dev/null +++ b/node_modules/mapbox-gl/src/source/raster_dem_tile_worker_source.js @@ -0,0 +1,62 @@ +// @flow + +import DEMData from '../data/dem_data'; +import {RGBAImage} from '../util/image'; +import window from '../util/window'; + +import type Actor from '../util/actor'; +import type { + WorkerDEMTileParameters, + WorkerDEMTileCallback, + TileParameters +} from './worker_source'; +const {ImageBitmap} = window; + +class RasterDEMTileWorkerSource { + actor: Actor; + loaded: {[_: string]: DEMData}; + offscreenCanvas: OffscreenCanvas; + offscreenCanvasContext: CanvasRenderingContext2D; + + constructor() { + this.loaded = {}; + } + + loadTile(params: WorkerDEMTileParameters, callback: WorkerDEMTileCallback) { + const {uid, encoding, rawImageData} = params; + // Main thread will transfer ImageBitmap if offscreen decode with OffscreenCanvas is supported, else it will transfer an already decoded image. + const imagePixels = (ImageBitmap && rawImageData instanceof ImageBitmap) ? this.getImageData(rawImageData) : rawImageData; + const dem = new DEMData(uid, imagePixels, encoding); + this.loaded = this.loaded || {}; + this.loaded[uid] = dem; + callback(null, dem); + } + + getImageData(imgBitmap: ImageBitmap): RGBAImage { + // Lazily initialize OffscreenCanvas + if (!this.offscreenCanvas || !this.offscreenCanvasContext) { + // Dem tiles are typically 256x256 + this.offscreenCanvas = new OffscreenCanvas(imgBitmap.width, imgBitmap.height); + this.offscreenCanvasContext = this.offscreenCanvas.getContext('2d'); + } + + this.offscreenCanvas.width = imgBitmap.width; + this.offscreenCanvas.height = imgBitmap.height; + + this.offscreenCanvasContext.drawImage(imgBitmap, 0, 0, imgBitmap.width, imgBitmap.height); + // Insert an additional 1px padding around the image to allow backfilling for neighboring data. + const imgData = this.offscreenCanvasContext.getImageData(-1, -1, imgBitmap.width + 2, imgBitmap.height + 2); + this.offscreenCanvasContext.clearRect(0, 0, this.offscreenCanvas.width, this.offscreenCanvas.height); + return new RGBAImage({width: imgData.width, height: imgData.height}, imgData.data); + } + + removeTile(params: TileParameters) { + const loaded = this.loaded, + uid = params.uid; + if (loaded && loaded[uid]) { + delete loaded[uid]; + } + } +} + +export default RasterDEMTileWorkerSource; diff --git a/node_modules/mapbox-gl/src/source/raster_tile_source.js b/node_modules/mapbox-gl/src/source/raster_tile_source.js new file mode 100644 index 0000000000000000000000000000000000000000..4aa5b71045c6bb7344663e3bb33abcf5fa625b7b --- /dev/null +++ b/node_modules/mapbox-gl/src/source/raster_tile_source.js @@ -0,0 +1,169 @@ +// @flow + +import {extend, pick} from '../util/util'; + +import {getImage, ResourceType} from '../util/ajax'; +import {Event, ErrorEvent, Evented} from '../util/evented'; +import loadTileJSON from './load_tilejson'; +import {postTurnstileEvent, postMapLoadEvent} from '../util/mapbox'; +import TileBounds from './tile_bounds'; +import Texture from '../render/texture'; + +import {cacheEntryPossiblyAdded} from '../util/tile_request_cache'; + +import type {Source} from './source'; +import type {OverscaledTileID} from './tile_id'; +import type Map from '../ui/map'; +import type Dispatcher from '../util/dispatcher'; +import type Tile from './tile'; +import type {Callback} from '../types/callback'; +import type {Cancelable} from '../types/cancelable'; +import type { + RasterSourceSpecification, + RasterDEMSourceSpecification +} from '../style-spec/types'; + +class RasterTileSource extends Evented implements Source { + type: 'raster' | 'raster-dem'; + id: string; + minzoom: number; + maxzoom: number; + url: string; + scheme: string; + tileSize: number; + + bounds: ?[number, number, number, number]; + tileBounds: TileBounds; + roundZoom: boolean; + dispatcher: Dispatcher; + map: Map; + tiles: Array; + + _loaded: boolean; + _options: RasterSourceSpecification | RasterDEMSourceSpecification; + _tileJSONRequest: ?Cancelable; + + constructor(id: string, options: RasterSourceSpecification | RasterDEMSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) { + super(); + this.id = id; + this.dispatcher = dispatcher; + this.setEventedParent(eventedParent); + + this.type = 'raster'; + this.minzoom = 0; + this.maxzoom = 22; + this.roundZoom = true; + this.scheme = 'xyz'; + this.tileSize = 512; + this._loaded = false; + + this._options = extend({type: 'raster'}, options); + extend(this, pick(options, ['url', 'scheme', 'tileSize'])); + } + + load() { + this._loaded = false; + this.fire(new Event('dataloading', {dataType: 'source'})); + this._tileJSONRequest = loadTileJSON(this._options, this.map._requestManager, (err, tileJSON) => { + this._tileJSONRequest = null; + this._loaded = true; + if (err) { + this.fire(new ErrorEvent(err)); + } else if (tileJSON) { + extend(this, tileJSON); + if (tileJSON.bounds) this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom); + + postTurnstileEvent(tileJSON.tiles); + postMapLoadEvent(tileJSON.tiles, this.map._getMapId(), this.map._requestManager._skuToken); + + // `content` is included here to prevent a race condition where `Style#_updateSources` is called + // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives + // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088 + this.fire(new Event('data', {dataType: 'source', sourceDataType: 'metadata'})); + this.fire(new Event('data', {dataType: 'source', sourceDataType: 'content'})); + } + }); + } + + loaded(): boolean { + return this._loaded; + } + + onAdd(map: Map) { + this.map = map; + this.load(); + } + + onRemove() { + if (this._tileJSONRequest) { + this._tileJSONRequest.cancel(); + this._tileJSONRequest = null; + } + } + + serialize() { + return extend({}, this._options); + } + + hasTile(tileID: OverscaledTileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + loadTile(tile: Tile, callback: Callback) { + const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), this.tileSize); + tile.request = getImage(this.map._requestManager.transformRequest(url, ResourceType.Tile), (err, img) => { + delete tile.request; + + if (tile.aborted) { + tile.state = 'unloaded'; + callback(null); + } else if (err) { + tile.state = 'errored'; + callback(err); + } else if (img) { + if (this.map._refreshExpiredTiles) tile.setExpiryData(img); + delete (img: any).cacheControl; + delete (img: any).expires; + + const context = this.map.painter.context; + const gl = context.gl; + tile.texture = this.map.painter.getTileTexture(img.width); + if (tile.texture) { + tile.texture.update(img, {useMipmap: true}); + } else { + tile.texture = new Texture(context, img, gl.RGBA, {useMipmap: true}); + tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST); + + if (context.extTextureFilterAnisotropic) { + gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, context.extTextureFilterAnisotropicMax); + } + } + + tile.state = 'loaded'; + + cacheEntryPossiblyAdded(this.dispatcher); + + callback(null); + } + }); + } + + abortTile(tile: Tile, callback: Callback) { + if (tile.request) { + tile.request.cancel(); + delete tile.request; + } + callback(); + } + + unloadTile(tile: Tile, callback: Callback) { + if (tile.texture) this.map.painter.saveTileTexture(tile.texture); + callback(); + } + + hasTransition() { + return false; + } +} + +export default RasterTileSource; diff --git a/node_modules/mapbox-gl/src/source/rtl_text_plugin.js b/node_modules/mapbox-gl/src/source/rtl_text_plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..1d1e6888b0e5bf2f3ea04e0a1e8069d54847b437 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/rtl_text_plugin.js @@ -0,0 +1,143 @@ +// @flow + +import {Event, Evented} from '../util/evented'; +import {getArrayBuffer} from '../util/ajax'; +import browser from '../util/browser'; +import assert from 'assert'; +import {isWorker} from '../util/util'; + +const status = { + unavailable: 'unavailable', // Not loaded + deferred: 'deferred', // The plugin URL has been specified, but loading has been deferred + loading: 'loading', // request in-flight + loaded: 'loaded', + error: 'error' +}; + +export type PluginState = { + pluginStatus: $Values; + pluginURL: ?string +}; + +type ErrorCallback = (error: ?Error) => void; +type PluginStateSyncCallback = (state: PluginState) => void; +let _completionCallback = null; + +//Variables defining the current state of the plugin +let pluginStatus = status.unavailable; +let pluginURL = null; + +export const triggerPluginCompletionEvent = function(error: ?Error) { + // NetworkError's are not correctly reflected by the plugin status which prevents reloading plugin + if (error && typeof error === 'string' && error.indexOf('NetworkError') > -1) { + pluginStatus = status.error; + } + + if (_completionCallback) { + _completionCallback(error); + } +}; + +function sendPluginStateToWorker() { + evented.fire(new Event('pluginStateChange', {pluginStatus, pluginURL})); +} + +export const evented = new Evented(); + +export const getRTLTextPluginStatus = function () { + return pluginStatus; +}; + +export const registerForPluginStateChange = function(callback: PluginStateSyncCallback) { + // Do an initial sync of the state + callback({pluginStatus, pluginURL}); + // Listen for all future state changes + evented.on('pluginStateChange', callback); + return callback; +}; + +export const clearRTLTextPlugin = function() { + pluginStatus = status.unavailable; + pluginURL = null; +}; + +export const setRTLTextPlugin = function(url: string, callback: ?ErrorCallback, deferred: boolean = false) { + if (pluginStatus === status.deferred || pluginStatus === status.loading || pluginStatus === status.loaded) { + throw new Error('setRTLTextPlugin cannot be called multiple times.'); + } + pluginURL = browser.resolveURL(url); + pluginStatus = status.deferred; + _completionCallback = callback; + sendPluginStateToWorker(); + + //Start downloading the plugin immediately if not intending to lazy-load + if (!deferred) { + downloadRTLTextPlugin(); + } +}; + +export const downloadRTLTextPlugin = function() { + if (pluginStatus !== status.deferred || !pluginURL) { + throw new Error('rtl-text-plugin cannot be downloaded unless a pluginURL is specified'); + } + pluginStatus = status.loading; + sendPluginStateToWorker(); + if (pluginURL) { + getArrayBuffer({url: pluginURL}, (error) => { + if (error) { + triggerPluginCompletionEvent(error); + } else { + pluginStatus = status.loaded; + sendPluginStateToWorker(); + } + }); + } +}; + +export const plugin: { + applyArabicShaping: ?Function, + processBidirectionalText: ?(string, Array) => Array, + processStyledBidirectionalText: ?(string, Array, Array) => Array<[string, Array]>, + isLoaded: () => boolean, + isLoading: () => boolean, + setState: (state: PluginState) => void, + isParsed: () => boolean, + getPluginURL: () => ?string +} = { + applyArabicShaping: null, + processBidirectionalText: null, + processStyledBidirectionalText: null, + isLoaded() { + return pluginStatus === status.loaded || // Main Thread: loaded if the completion callback returned successfully + plugin.applyArabicShaping != null; // Web-worker: loaded if the plugin functions have been compiled + }, + isLoading() { // Main Thread Only: query the loading status, this function does not return the correct value in the worker context. + return pluginStatus === status.loading; + }, + setState(state: PluginState) { // Worker thread only: this tells the worker threads that the plugin is available on the Main thread + assert(isWorker(), 'Cannot set the state of the rtl-text-plugin when not in the web-worker context'); + + pluginStatus = state.pluginStatus; + pluginURL = state.pluginURL; + }, + isParsed(): boolean { + assert(isWorker(), 'rtl-text-plugin is only parsed on the worker-threads'); + + return plugin.applyArabicShaping != null && + plugin.processBidirectionalText != null && + plugin.processStyledBidirectionalText != null; + }, + getPluginURL(): ?string { + assert(isWorker(), 'rtl-text-plugin url can only be queried from the worker threads'); + return pluginURL; + } +}; + +export const lazyLoadRTLTextPlugin = function() { + if (!plugin.isLoading() && + !plugin.isLoaded() && + getRTLTextPluginStatus() === 'deferred' + ) { + downloadRTLTextPlugin(); + } +}; diff --git a/node_modules/mapbox-gl/src/source/source.js b/node_modules/mapbox-gl/src/source/source.js new file mode 100644 index 0000000000000000000000000000000000000000..92f2279ee428155026e2a05e34017ace43ea2c9e --- /dev/null +++ b/node_modules/mapbox-gl/src/source/source.js @@ -0,0 +1,137 @@ +// @flow + +import {bindAll} from '../util/util'; + +import type Dispatcher from '../util/dispatcher'; +import type {Event, Evented} from '../util/evented'; +import type Map from '../ui/map'; +import type Tile from './tile'; +import type {OverscaledTileID} from './tile_id'; +import type {Callback} from '../types/callback'; +import {CanonicalTileID} from './tile_id'; + +/** + * The `Source` interface must be implemented by each source type, including "core" types (`vector`, `raster`, + * `video`, etc.) and all custom, third-party types. + * + * @private + * + * @param {string} id The id for the source. Must not be used by any existing source. + * @param {Object} options Source options, specific to the source type (except for `options.type`, which is always + * required). + * @param {string} options.type The source type, matching the value of `name` used in {@link Style#addSourceType}. + * @param {Dispatcher} dispatcher A {@link Dispatcher} instance, which can be used to send messages to the workers. + * + * @fires data with `{dataType: 'source', sourceDataType: 'metadata'}` to indicate that any necessary metadata + * has been loaded so that it's okay to call `loadTile`; and with `{dataType: 'source', sourceDataType: 'content'}` + * to indicate that the source data has changed, so that any current caches should be flushed. + * @property {string} id The id for the source. Must match the id passed to the constructor. + * @property {number} minzoom + * @property {number} maxzoom + * @property {boolean} isTileClipped `false` if tiles can be drawn outside their boundaries, `true` if they cannot. + * @property {boolean} reparseOverscaled `true` if tiles should be sent back to the worker for each overzoomed zoom + * level, `false` if not. + * @property {boolean} roundZoom `true` if zoom levels are rounded to the nearest integer in the source data, `false` + * if they are floor-ed to the nearest integer. + */ +export interface Source { + +type: string; + id: string; + minzoom: number, + maxzoom: number, + tileSize: number, + attribution?: string, + + roundZoom?: boolean, + isTileClipped?: boolean, + mapbox_logo?: boolean, + tileID?: CanonicalTileID; + reparseOverscaled?: boolean, + vectorLayerIds?: Array, + + hasTransition(): boolean; + loaded(): boolean; + + fire(event: Event): mixed; + + +onAdd?: (map: Map) => void; + +onRemove?: (map: Map) => void; + + loadTile(tile: Tile, callback: Callback): void; + +hasTile?: (tileID: OverscaledTileID) => boolean; + +abortTile?: (tile: Tile, callback: Callback) => void; + +unloadTile?: (tile: Tile, callback: Callback) => void; + + /** + * @returns A plain (stringifiable) JS object representing the current state of the source. + * Creating a source using the returned object as the `options` should result in a Source that is + * equivalent to this one. + * @private + */ + serialize(): Object; + + +prepare?: () => void; +} + +type SourceStatics = { + /* + * An optional URL to a script which, when run by a Worker, registers a {@link WorkerSource} + * implementation for this Source type by calling `self.registerWorkerSource(workerSource: WorkerSource)`. + */ + workerSourceURL?: URL; +}; + +export type SourceClass = Class & SourceStatics; + +import vector from '../source/vector_tile_source'; +import raster from '../source/raster_tile_source'; +import rasterDem from '../source/raster_dem_tile_source'; +import geojson from '../source/geojson_source'; +import video from '../source/video_source'; +import image from '../source/image_source'; +import canvas from '../source/canvas_source'; + +import type {SourceSpecification} from '../style-spec/types'; + +const sourceTypes = { + vector, + raster, + 'raster-dem': rasterDem, + geojson, + video, + image, + canvas +}; + +/* + * Creates a tiled data source instance given an options object. + * + * @param id + * @param {Object} source A source definition object compliant with + * [`mapbox-gl-style-spec`](https://www.mapbox.com/mapbox-gl-style-spec/#sources) or, for a third-party source type, + * with that type's requirements. + * @param {Dispatcher} dispatcher + * @returns {Source} + */ +export const create = function(id: string, specification: SourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) { + const source = new sourceTypes[specification.type](id, (specification: any), dispatcher, eventedParent); + + if (source.id !== id) { + throw new Error(`Expected Source id to be ${id} instead of ${source.id}`); + } + + bindAll(['load', 'abort', 'unload', 'serialize', 'prepare'], source); + return source; +}; + +export const getType = function (name: string) { + return sourceTypes[name]; +}; + +export const setType = function (name: string, type: Class) { + sourceTypes[name] = type; +}; + +export interface Actor { + send(type: string, data: Object, callback: Callback): void; +} diff --git a/node_modules/mapbox-gl/src/source/source_cache.js b/node_modules/mapbox-gl/src/source/source_cache.js new file mode 100644 index 0000000000000000000000000000000000000000..525df8ad006d20ea82e8f189caa516164f80ee39 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/source_cache.js @@ -0,0 +1,953 @@ +// @flow + +import {create as createSource} from './source'; + +import Tile from './tile'; +import {Event, ErrorEvent, Evented} from '../util/evented'; +import TileCache from './tile_cache'; +import MercatorCoordinate from '../geo/mercator_coordinate'; +import {keysDifference, values} from '../util/util'; +import EXTENT from '../data/extent'; +import Context from '../gl/context'; +import Point from '@mapbox/point-geometry'; +import browser from '../util/browser'; +import {OverscaledTileID} from './tile_id'; +import assert from 'assert'; +import SourceFeatureState from './source_state'; + +import type {Source} from './source'; +import type Map from '../ui/map'; +import type Style from '../style/style'; +import type Dispatcher from '../util/dispatcher'; +import type Transform from '../geo/transform'; +import type {TileState} from './tile'; +import type {Callback} from '../types/callback'; +import type {SourceSpecification} from '../style-spec/types'; + +/** + * `SourceCache` is responsible for + * + * - creating an instance of `Source` + * - forwarding events from `Source` + * - caching tiles loaded from an instance of `Source` + * - loading the tiles needed to render a given viewport + * - unloading the cached tiles not needed to render a given viewport + * + * @private + */ +class SourceCache extends Evented { + id: string; + dispatcher: Dispatcher; + map: Map; + style: Style; + + _source: Source; + _sourceLoaded: boolean; + _sourceErrored: boolean; + _tiles: {[_: string]: Tile}; + _prevLng: number | void; + _cache: TileCache; + _timers: {[_: any]: TimeoutID}; + _cacheTimers: {[_: any]: TimeoutID}; + _maxTileCacheSize: ?number; + _paused: boolean; + _shouldReloadOnResume: boolean; + _coveredTiles: {[_: string]: boolean}; + transform: Transform; + _isIdRenderable: (id: string, symbolLayer?: boolean) => boolean; + used: boolean; + _state: SourceFeatureState; + _loadedParentTiles: {[_: string]: ?Tile}; + + static maxUnderzooming: number; + static maxOverzooming: number; + + constructor(id: string, options: SourceSpecification, dispatcher: Dispatcher) { + super(); + this.id = id; + this.dispatcher = dispatcher; + + this.on('data', (e) => { + // this._sourceLoaded signifies that the TileJSON is loaded if applicable. + // if the source type does not come with a TileJSON, the flag signifies the + // source data has loaded (i.e geojson has been tiled on the worker and is ready) + if (e.dataType === 'source' && e.sourceDataType === 'metadata') this._sourceLoaded = true; + + // for sources with mutable data, this event fires when the underlying data + // to a source is changed. (i.e. GeoJSONSource#setData and ImageSource#serCoordinates) + if (this._sourceLoaded && !this._paused && e.dataType === "source" && e.sourceDataType === 'content') { + this.reload(); + if (this.transform) { + this.update(this.transform); + } + } + }); + + this.on('error', () => { + this._sourceErrored = true; + }); + + this._source = createSource(id, options, dispatcher, this); + + this._tiles = {}; + this._cache = new TileCache(0, this._unloadTile.bind(this)); + this._timers = {}; + this._cacheTimers = {}; + this._maxTileCacheSize = null; + this._loadedParentTiles = {}; + + this._coveredTiles = {}; + this._state = new SourceFeatureState(); + } + + onAdd(map: Map) { + this.map = map; + this._maxTileCacheSize = map ? map._maxTileCacheSize : null; + if (this._source && this._source.onAdd) { + this._source.onAdd(map); + } + } + + onRemove(map: Map) { + if (this._source && this._source.onRemove) { + this._source.onRemove(map); + } + } + + /** + * Return true if no tile data is pending, tiles will not change unless + * an additional API call is received. + * @private + */ + loaded(): boolean { + if (this._sourceErrored) { return true; } + if (!this._sourceLoaded) { return false; } + if (!this._source.loaded()) { return false; } + for (const t in this._tiles) { + const tile = this._tiles[t]; + if (tile.state !== 'loaded' && tile.state !== 'errored') + return false; + } + return true; + } + + getSource(): Source { + return this._source; + } + + pause() { + this._paused = true; + } + + resume() { + if (!this._paused) return; + const shouldReload = this._shouldReloadOnResume; + this._paused = false; + this._shouldReloadOnResume = false; + if (shouldReload) this.reload(); + if (this.transform) this.update(this.transform); + } + + _loadTile(tile: Tile, callback: Callback) { + return this._source.loadTile(tile, callback); + } + + _unloadTile(tile: Tile) { + if (this._source.unloadTile) + return this._source.unloadTile(tile, () => {}); + } + + _abortTile(tile: Tile) { + if (this._source.abortTile) + return this._source.abortTile(tile, () => {}); + } + + serialize() { + return this._source.serialize(); + } + + prepare(context: Context) { + if (this._source.prepare) { + this._source.prepare(); + } + + this._state.coalesceChanges(this._tiles, this.map ? this.map.painter : null); + for (const i in this._tiles) { + const tile = this._tiles[i]; + tile.upload(context); + tile.prepare(this.map.style.imageManager); + } + } + + /** + * Return all tile ids ordered with z-order, and cast to numbers + * @private + */ + getIds(): Array { + return (values(this._tiles): any).map((tile: Tile) => tile.tileID).sort(compareTileId).map(id => id.key); + } + + getRenderableIds(symbolLayer?: boolean): Array { + const renderables: Array = []; + for (const id in this._tiles) { + if (this._isIdRenderable(id, symbolLayer)) renderables.push(this._tiles[id]); + } + if (symbolLayer) { + return renderables.sort((a_: Tile, b_: Tile) => { + const a = a_.tileID; + const b = b_.tileID; + const rotatedA = (new Point(a.canonical.x, a.canonical.y))._rotate(this.transform.angle); + const rotatedB = (new Point(b.canonical.x, b.canonical.y))._rotate(this.transform.angle); + return a.overscaledZ - b.overscaledZ || rotatedB.y - rotatedA.y || rotatedB.x - rotatedA.x; + }).map(tile => tile.tileID.key); + } + return renderables.map(tile => tile.tileID).sort(compareTileId).map(id => id.key); + } + + hasRenderableParent(tileID: OverscaledTileID) { + const parentTile = this.findLoadedParent(tileID, 0); + if (parentTile) { + return this._isIdRenderable(parentTile.tileID.key); + } + return false; + } + + _isIdRenderable(id: string, symbolLayer?: boolean) { + return this._tiles[id] && this._tiles[id].hasData() && + !this._coveredTiles[id] && (symbolLayer || !this._tiles[id].holdingForFade()); + } + + reload() { + if (this._paused) { + this._shouldReloadOnResume = true; + return; + } + + this._cache.reset(); + + for (const i in this._tiles) { + if (this._tiles[i].state !== "errored") this._reloadTile(i, 'reloading'); + } + } + + _reloadTile(id: string, state: TileState) { + const tile = this._tiles[id]; + + // this potentially does not address all underlying + // issues https://github.com/mapbox/mapbox-gl-js/issues/4252 + // - hard to tell without repro steps + if (!tile) return; + + // The difference between "loading" tiles and "reloading" or "expired" + // tiles is that "reloading"/"expired" tiles are "renderable". + // Therefore, a "loading" tile cannot become a "reloading" tile without + // first becoming a "loaded" tile. + if (tile.state !== 'loading') { + tile.state = state; + } + + this._loadTile(tile, this._tileLoaded.bind(this, tile, id, state)); + } + + _tileLoaded(tile: Tile, id: string, previousState: TileState, err: ?Error) { + if (err) { + tile.state = 'errored'; + if ((err: any).status !== 404) this._source.fire(new ErrorEvent(err, {tile})); + // continue to try loading parent/children tiles if a tile doesn't exist (404) + else this.update(this.transform); + return; + } + + tile.timeAdded = browser.now(); + if (previousState === 'expired') tile.refreshedUponExpiration = true; + this._setTileReloadTimer(id, tile); + if (this.getSource().type === 'raster-dem' && tile.dem) this._backfillDEM(tile); + this._state.initializeTileState(tile, this.map ? this.map.painter : null); + + this._source.fire(new Event('data', {dataType: 'source', tile, coord: tile.tileID})); + } + + /** + * For raster terrain source, backfill DEM to eliminate visible tile boundaries + * @private + */ + _backfillDEM(tile: Tile) { + const renderables = this.getRenderableIds(); + for (let i = 0; i < renderables.length; i++) { + const borderId = renderables[i]; + if (tile.neighboringTiles && tile.neighboringTiles[borderId]) { + const borderTile = this.getTileByID(borderId); + fillBorder(tile, borderTile); + fillBorder(borderTile, tile); + } + } + + function fillBorder(tile, borderTile) { + tile.needsHillshadePrepare = true; + let dx = borderTile.tileID.canonical.x - tile.tileID.canonical.x; + const dy = borderTile.tileID.canonical.y - tile.tileID.canonical.y; + const dim = Math.pow(2, tile.tileID.canonical.z); + const borderId = borderTile.tileID.key; + if (dx === 0 && dy === 0) return; + + if (Math.abs(dy) > 1) { + return; + } + if (Math.abs(dx) > 1) { + // Adjust the delta coordinate for world wraparound. + if (Math.abs(dx + dim) === 1) { + dx += dim; + } else if (Math.abs(dx - dim) === 1) { + dx -= dim; + } + } + if (!borderTile.dem || !tile.dem) return; + tile.dem.backfillBorder(borderTile.dem, dx, dy); + if (tile.neighboringTiles && tile.neighboringTiles[borderId]) + tile.neighboringTiles[borderId].backfilled = true; + } + } + /** + * Get a specific tile by TileID + * @private + */ + getTile(tileID: OverscaledTileID): Tile { + return this.getTileByID(tileID.key); + } + + /** + * Get a specific tile by id + * @private + */ + getTileByID(id: string): Tile { + return this._tiles[id]; + } + + /** + * For a given set of tiles, retain children that are loaded and have a zoom + * between `zoom` (exclusive) and `maxCoveringZoom` (inclusive) + * @private + */ + _retainLoadedChildren( + idealTiles: {[_: any]: OverscaledTileID}, + zoom: number, + maxCoveringZoom: number, + retain: {[_: any]: OverscaledTileID} + ) { + for (const id in this._tiles) { + let tile = this._tiles[id]; + + // only consider renderable tiles up to maxCoveringZoom + if (retain[id] || + !tile.hasData() || + tile.tileID.overscaledZ <= zoom || + tile.tileID.overscaledZ > maxCoveringZoom + ) continue; + + // loop through parents and retain the topmost loaded one if found + let topmostLoadedID = tile.tileID; + while (tile && tile.tileID.overscaledZ > zoom + 1) { + const parentID = tile.tileID.scaledTo(tile.tileID.overscaledZ - 1); + + tile = this._tiles[parentID.key]; + + if (tile && tile.hasData()) { + topmostLoadedID = parentID; + } + } + + // loop through ancestors of the topmost loaded child to see if there's one that needed it + let tileID = topmostLoadedID; + while (tileID.overscaledZ > zoom) { + tileID = tileID.scaledTo(tileID.overscaledZ - 1); + + if (idealTiles[tileID.key]) { + // found a parent that needed a loaded child; retain that child + retain[topmostLoadedID.key] = topmostLoadedID; + break; + } + } + } + } + + /** + * Find a loaded parent of the given tile (up to minCoveringZoom) + * @private + */ + findLoadedParent(tileID: OverscaledTileID, minCoveringZoom: number): ?Tile { + if (tileID.key in this._loadedParentTiles) { + const parent = this._loadedParentTiles[tileID.key]; + if (parent && parent.tileID.overscaledZ >= minCoveringZoom) { + return parent; + } else { + return null; + } + } + for (let z = tileID.overscaledZ - 1; z >= minCoveringZoom; z--) { + const parentTileID = tileID.scaledTo(z); + const tile = this._getLoadedTile(parentTileID); + if (tile) { + return tile; + } + } + } + + _getLoadedTile(tileID: OverscaledTileID): ?Tile { + const tile = this._tiles[tileID.key]; + if (tile && tile.hasData()) { + return tile; + } + // TileCache ignores wrap in lookup. + const cachedTile = this._cache.getByKey(tileID.wrapped().key); + return cachedTile; + } + + /** + * Resizes the tile cache based on the current viewport's size + * or the maxTileCacheSize option passed during map creation + * + * Larger viewports use more tiles and need larger caches. Larger viewports + * are more likely to be found on devices with more memory and on pages where + * the map is more important. + * @private + */ + updateCacheSize(transform: Transform) { + const widthInTiles = Math.ceil(transform.width / this._source.tileSize) + 1; + const heightInTiles = Math.ceil(transform.height / this._source.tileSize) + 1; + const approxTilesInView = widthInTiles * heightInTiles; + const commonZoomRange = 5; + + const viewDependentMaxSize = Math.floor(approxTilesInView * commonZoomRange); + const maxSize = typeof this._maxTileCacheSize === 'number' ? Math.min(this._maxTileCacheSize, viewDependentMaxSize) : viewDependentMaxSize; + + this._cache.setMaxSize(maxSize); + } + + handleWrapJump(lng: number) { + // On top of the regular z/x/y values, TileIDs have a `wrap` value that specify + // which cppy of the world the tile belongs to. For example, at `lng: 10` you + // might render z/x/y/0 while at `lng: 370` you would render z/x/y/1. + // + // When lng values get wrapped (going from `lng: 370` to `long: 10`) you expect + // to see the same thing on the screen (370 degrees and 10 degrees is the same + // place in the world) but all the TileIDs will have different wrap values. + // + // In order to make this transition seamless, we calculate the rounded difference of + // "worlds" between the last frame and the current frame. If the map panned by + // a world, then we can assign all the tiles new TileIDs with updated wrap values. + // For example, assign z/x/y/1 a new id: z/x/y/0. It is the same tile, just rendered + // in a different position. + // + // This enables us to reuse the tiles at more ideal locations and prevent flickering. + const prevLng = this._prevLng === undefined ? lng : this._prevLng; + const lngDifference = lng - prevLng; + const worldDifference = lngDifference / 360; + const wrapDelta = Math.round(worldDifference); + this._prevLng = lng; + + if (wrapDelta) { + const tiles: {[_: string]: Tile} = {}; + for (const key in this._tiles) { + const tile = this._tiles[key]; + tile.tileID = tile.tileID.unwrapTo(tile.tileID.wrap + wrapDelta); + tiles[tile.tileID.key] = tile; + } + this._tiles = tiles; + + // Reset tile reload timers + for (const id in this._timers) { + clearTimeout(this._timers[id]); + delete this._timers[id]; + } + for (const id in this._tiles) { + const tile = this._tiles[id]; + this._setTileReloadTimer(id, tile); + } + } + } + + /** + * Removes tiles that are outside the viewport and adds new tiles that + * are inside the viewport. + * @private + */ + update(transform: Transform) { + this.transform = transform; + if (!this._sourceLoaded || this._paused) { return; } + + this.updateCacheSize(transform); + this.handleWrapJump(this.transform.center.lng); + + // Covered is a list of retained tiles who's areas are fully covered by other, + // better, retained tiles. They are not drawn separately. + this._coveredTiles = {}; + + let idealTileIDs; + if (!this.used) { + idealTileIDs = []; + } else if (this._source.tileID) { + idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID) + .map((unwrapped) => new OverscaledTileID(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y)); + } else { + idealTileIDs = transform.coveringTiles({ + tileSize: this._source.tileSize, + minzoom: this._source.minzoom, + maxzoom: this._source.maxzoom, + roundZoom: this._source.roundZoom, + reparseOverscaled: this._source.reparseOverscaled + }); + + if (this._source.hasTile) { + idealTileIDs = idealTileIDs.filter((coord) => (this._source.hasTile: any)(coord)); + } + } + + // Determine the overzooming/underzooming amounts. + const zoom = transform.coveringZoomLevel(this._source); + const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom); + const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom); + + // Retain is a list of tiles that we shouldn't delete, even if they are not + // the most ideal tile for the current viewport. This may include tiles like + // parent or child tiles that are *already* loaded. + const retain = this._updateRetainedTiles(idealTileIDs, zoom); + + if (isRasterType(this._source.type)) { + const parentsForFading: {[_: string]: OverscaledTileID} = {}; + const fadingTiles = {}; + const ids = Object.keys(retain); + for (const id of ids) { + const tileID = retain[id]; + assert(tileID.key === id); + + const tile = this._tiles[id]; + if (!tile || tile.fadeEndTime && tile.fadeEndTime <= browser.now()) continue; + + // if the tile is loaded but still fading in, find parents to cross-fade with it + const parentTile = this.findLoadedParent(tileID, minCoveringZoom); + if (parentTile) { + this._addTile(parentTile.tileID); + parentsForFading[parentTile.tileID.key] = parentTile.tileID; + } + + fadingTiles[id] = tileID; + } + + // for tiles that are still fading in, also find children to cross-fade with + this._retainLoadedChildren(fadingTiles, zoom, maxCoveringZoom, retain); + + for (const id in parentsForFading) { + if (!retain[id]) { + // If a tile is only needed for fading, mark it as covered so that it isn't rendered on it's own. + this._coveredTiles[id] = true; + retain[id] = parentsForFading[id]; + } + } + } + + for (const retainedId in retain) { + // Make sure retained tiles always clear any existing fade holds + // so that if they're removed again their fade timer starts fresh. + this._tiles[retainedId].clearFadeHold(); + } + + // Remove the tiles we don't need anymore. + const remove = keysDifference(this._tiles, retain); + for (const tileID of remove) { + const tile = this._tiles[tileID]; + if (tile.hasSymbolBuckets && !tile.holdingForFade()) { + tile.setHoldDuration(this.map._fadeDuration); + } else if (!tile.hasSymbolBuckets || tile.symbolFadeFinished()) { + this._removeTile(tileID); + } + } + + // Construct a cache of loaded parents + this._updateLoadedParentTileCache(); + } + + releaseSymbolFadeTiles() { + for (const id in this._tiles) { + if (this._tiles[id].holdingForFade()) { + this._removeTile(id); + } + } + } + + _updateRetainedTiles(idealTileIDs: Array, zoom: number): {[_: string]: OverscaledTileID} { + const retain: {[_: string]: OverscaledTileID} = {}; + const checked: {[_: string]: boolean } = {}; + const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom); + const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom); + + const missingTiles = {}; + for (const tileID of idealTileIDs) { + const tile = this._addTile(tileID); + + // retain the tile even if it's not loaded because it's an ideal tile. + retain[tileID.key] = tileID; + + if (tile.hasData()) continue; + + if (zoom < this._source.maxzoom) { + // save missing tiles that potentially have loaded children + missingTiles[tileID.key] = tileID; + } + } + + // retain any loaded children of ideal tiles up to maxCoveringZoom + this._retainLoadedChildren(missingTiles, zoom, maxCoveringZoom, retain); + + for (const tileID of idealTileIDs) { + let tile = this._tiles[tileID.key]; + + if (tile.hasData()) continue; + + // The tile we require is not yet loaded or does not exist; + // Attempt to find children that fully cover it. + + if (zoom + 1 > this._source.maxzoom) { + // We're looking for an overzoomed child tile. + const childCoord = tileID.children(this._source.maxzoom)[0]; + const childTile = this.getTile(childCoord); + if (!!childTile && childTile.hasData()) { + retain[childCoord.key] = childCoord; + continue; // tile is covered by overzoomed child + } + } else { + // check if all 4 immediate children are loaded (i.e. the missing ideal tile is covered) + const children = tileID.children(this._source.maxzoom); + + if (retain[children[0].key] && + retain[children[1].key] && + retain[children[2].key] && + retain[children[3].key]) continue; // tile is covered by children + } + + // We couldn't find child tiles that entirely cover the ideal tile; look for parents now. + + // As we ascend up the tile pyramid of the ideal tile, we check whether the parent + // tile has been previously requested (and errored because we only loop over tiles with no data) + // in order to determine if we need to request its parent. + let parentWasRequested = tile.wasRequested(); + + for (let overscaledZ = tileID.overscaledZ - 1; overscaledZ >= minCoveringZoom; --overscaledZ) { + const parentId = tileID.scaledTo(overscaledZ); + + // Break parent tile ascent if this route has been previously checked by another child. + if (checked[parentId.key]) break; + checked[parentId.key] = true; + + tile = this.getTile(parentId); + if (!tile && parentWasRequested) { + tile = this._addTile(parentId); + } + if (tile) { + retain[parentId.key] = parentId; + // Save the current values, since they're the parent of the next iteration + // of the parent tile ascent loop. + parentWasRequested = tile.wasRequested(); + if (tile.hasData()) break; + } + } + } + + return retain; + } + + _updateLoadedParentTileCache() { + this._loadedParentTiles = {}; + + for (const tileKey in this._tiles) { + const path = []; + let parentTile: ?Tile; + let currentId = this._tiles[tileKey].tileID; + + // Find the closest loaded ancestor by traversing the tile tree towards the root and + // caching results along the way + while (currentId.overscaledZ > 0) { + + // Do we have a cached result from previous traversals? + if (currentId.key in this._loadedParentTiles) { + parentTile = this._loadedParentTiles[currentId.key]; + break; + } + + path.push(currentId.key); + + // Is the parent loaded? + const parentId = currentId.scaledTo(currentId.overscaledZ - 1); + parentTile = this._getLoadedTile(parentId); + if (parentTile) { + break; + } + + currentId = parentId; + } + + // Cache the result of this traversal to all newly visited tiles + for (const key of path) { + this._loadedParentTiles[key] = parentTile; + } + } + } + + /** + * Add a tile, given its coordinate, to the pyramid. + * @private + */ + _addTile(tileID: OverscaledTileID): Tile { + let tile = this._tiles[tileID.key]; + if (tile) + return tile; + + tile = this._cache.getAndRemove(tileID); + if (tile) { + this._setTileReloadTimer(tileID.key, tile); + // set the tileID because the cached tile could have had a different wrap value + tile.tileID = tileID; + this._state.initializeTileState(tile, this.map ? this.map.painter : null); + if (this._cacheTimers[tileID.key]) { + clearTimeout(this._cacheTimers[tileID.key]); + delete this._cacheTimers[tileID.key]; + this._setTileReloadTimer(tileID.key, tile); + } + } + + const cached = Boolean(tile); + if (!cached) { + tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor()); + this._loadTile(tile, this._tileLoaded.bind(this, tile, tileID.key, tile.state)); + } + + // Impossible, but silence flow. + if (!tile) return (null: any); + + tile.uses++; + this._tiles[tileID.key] = tile; + if (!cached) this._source.fire(new Event('dataloading', {tile, coord: tile.tileID, dataType: 'source'})); + + return tile; + } + + _setTileReloadTimer(id: string, tile: Tile) { + if (id in this._timers) { + clearTimeout(this._timers[id]); + delete this._timers[id]; + } + + const expiryTimeout = tile.getExpiryTimeout(); + if (expiryTimeout) { + this._timers[id] = setTimeout(() => { + this._reloadTile(id, 'expired'); + delete this._timers[id]; + }, expiryTimeout); + } + } + + /** + * Remove a tile, given its id, from the pyramid + * @private + */ + _removeTile(id: string) { + const tile = this._tiles[id]; + if (!tile) + return; + + tile.uses--; + delete this._tiles[id]; + if (this._timers[id]) { + clearTimeout(this._timers[id]); + delete this._timers[id]; + } + + if (tile.uses > 0) + return; + + if (tile.hasData() && tile.state !== 'reloading') { + this._cache.add(tile.tileID, tile, tile.getExpiryTimeout()); + } else { + tile.aborted = true; + this._abortTile(tile); + this._unloadTile(tile); + } + } + + /** + * Remove all tiles from this pyramid + */ + clearTiles() { + this._shouldReloadOnResume = false; + this._paused = false; + + for (const id in this._tiles) + this._removeTile(id); + + this._cache.reset(); + } + + /** + * Search through our current tiles and attempt to find the tiles that + * cover the given bounds. + * @param pointQueryGeometry coordinates of the corners of bounding rectangle + * @returns {Array} result items have {tile, minX, maxX, minY, maxY}, where min/max bounding values are the given bounds transformed in into the coordinate space of this tile. + * @private + */ + tilesIn(pointQueryGeometry: Array, maxPitchScaleFactor: number, has3DLayer: boolean) { + + const tileResults = []; + + const transform = this.transform; + if (!transform) return tileResults; + + const cameraPointQueryGeometry = has3DLayer ? + transform.getCameraQueryGeometry(pointQueryGeometry) : + pointQueryGeometry; + + const queryGeometry = pointQueryGeometry.map((p) => transform.pointCoordinate(p)); + const cameraQueryGeometry = cameraPointQueryGeometry.map((p) => transform.pointCoordinate(p)); + + const ids = this.getIds(); + + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + + for (const p of cameraQueryGeometry) { + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + + for (let i = 0; i < ids.length; i++) { + const tile = this._tiles[ids[i]]; + if (tile.holdingForFade()) { + // Tiles held for fading are covered by tiles that are closer to ideal + continue; + } + const tileID = tile.tileID; + const scale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ); + const queryPadding = maxPitchScaleFactor * tile.queryPadding * EXTENT / tile.tileSize / scale; + + const tileSpaceBounds = [ + tileID.getTilePoint(new MercatorCoordinate(minX, minY)), + tileID.getTilePoint(new MercatorCoordinate(maxX, maxY)) + ]; + + if (tileSpaceBounds[0].x - queryPadding < EXTENT && tileSpaceBounds[0].y - queryPadding < EXTENT && + tileSpaceBounds[1].x + queryPadding >= 0 && tileSpaceBounds[1].y + queryPadding >= 0) { + + const tileSpaceQueryGeometry: Array = queryGeometry.map((c) => tileID.getTilePoint(c)); + const tileSpaceCameraQueryGeometry = cameraQueryGeometry.map((c) => tileID.getTilePoint(c)); + + tileResults.push({ + tile, + tileID, + queryGeometry: tileSpaceQueryGeometry, + cameraQueryGeometry: tileSpaceCameraQueryGeometry, + scale + }); + } + } + + return tileResults; + } + + getVisibleCoordinates(symbolLayer?: boolean): Array { + const coords = this.getRenderableIds(symbolLayer).map((id) => this._tiles[id].tileID); + for (const coord of coords) { + coord.posMatrix = this.transform.calculatePosMatrix(coord.toUnwrapped()); + } + return coords; + } + + hasTransition() { + if (this._source.hasTransition()) { + return true; + } + + if (isRasterType(this._source.type)) { + for (const id in this._tiles) { + const tile = this._tiles[id]; + if (tile.fadeEndTime !== undefined && tile.fadeEndTime >= browser.now()) { + return true; + } + } + } + + return false; + } + + /** + * Set the value of a particular state for a feature + * @private + */ + setFeatureState(sourceLayer?: string, featureId: number | string, state: Object) { + sourceLayer = sourceLayer || '_geojsonTileLayer'; + this._state.updateState(sourceLayer, featureId, state); + } + + /** + * Resets the value of a particular state key for a feature + * @private + */ + removeFeatureState(sourceLayer?: string, featureId?: number | string, key?: string) { + sourceLayer = sourceLayer || '_geojsonTileLayer'; + this._state.removeFeatureState(sourceLayer, featureId, key); + } + + /** + * Get the entire state object for a feature + * @private + */ + getFeatureState(sourceLayer?: string, featureId: number | string) { + sourceLayer = sourceLayer || '_geojsonTileLayer'; + return this._state.getState(sourceLayer, featureId); + } + + /** + * Sets the set of keys that the tile depends on. This allows tiles to + * be reloaded when their dependencies change. + * @private + */ + setDependencies(tileKey: string, namespace: string, dependencies: Array) { + const tile = this._tiles[tileKey]; + if (tile) { + tile.setDependencies(namespace, dependencies); + } + } + + /** + * Reloads all tiles that depend on the given keys. + * @private + */ + reloadTilesForDependencies(namespaces: Array, keys: Array) { + for (const id in this._tiles) { + const tile = this._tiles[id]; + if (tile.hasDependency(namespaces, keys)) { + this._reloadTile(id, 'reloading'); + } + } + this._cache.filter(tile => !tile.hasDependency(namespaces, keys)); + } +} + +SourceCache.maxOverzooming = 10; +SourceCache.maxUnderzooming = 3; + +function compareTileId(a: OverscaledTileID, b: OverscaledTileID): number { + // Different copies of the world are sorted based on their distance to the center. + // Wrap values are converted to unsigned distances by reserving odd number for copies + // with negative wrap and even numbers for copies with positive wrap. + const aWrap = Math.abs(a.wrap * 2) - +(a.wrap < 0); + const bWrap = Math.abs(b.wrap * 2) - +(b.wrap < 0); + return a.overscaledZ - b.overscaledZ || bWrap - aWrap || b.canonical.y - a.canonical.y || b.canonical.x - a.canonical.x; +} + +function isRasterType(type) { + return type === 'raster' || type === 'image' || type === 'video'; +} + +export default SourceCache; diff --git a/node_modules/mapbox-gl/src/source/source_state.js b/node_modules/mapbox-gl/src/source/source_state.js new file mode 100644 index 0000000000000000000000000000000000000000..1cc4d03d99f0fd9ea7e522b5c58567d823361965 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/source_state.js @@ -0,0 +1,159 @@ +// @flow + +import {extend} from '../util/util'; +import Tile from './tile'; +import type {FeatureState} from '../style-spec/expression'; + +export type FeatureStates = {[feature_id: string]: FeatureState}; +export type LayerFeatureStates = {[layer: string]: FeatureStates}; + +/** + * SourceFeatureState manages the state and pending changes + * to features in a source, separated by source layer. + * stateChanges and deletedStates batch all changes to the tile (updates and removes, respectively) + * between coalesce() events. addFeatureState() and removeFeatureState() also update their counterpart's + * list of changes, such that coalesce() can apply the proper state changes while agnostic to the order of operations. + * In deletedStates, all null's denote complete removal of state at that scope + * @private +*/ +class SourceFeatureState { + state: LayerFeatureStates; + stateChanges: LayerFeatureStates; + deletedStates: {}; + + constructor() { + this.state = {}; + this.stateChanges = {}; + this.deletedStates = {}; + } + + updateState(sourceLayer: string, featureId: number | string, newState: Object) { + const feature = String(featureId); + this.stateChanges[sourceLayer] = this.stateChanges[sourceLayer] || {}; + this.stateChanges[sourceLayer][feature] = this.stateChanges[sourceLayer][feature] || {}; + extend(this.stateChanges[sourceLayer][feature], newState); + + if (this.deletedStates[sourceLayer] === null) { + this.deletedStates[sourceLayer] = {}; + for (const ft in this.state[sourceLayer]) { + if (ft !== feature) this.deletedStates[sourceLayer][ft] = null; + } + } else { + const featureDeletionQueued = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] === null; + if (featureDeletionQueued) { + this.deletedStates[sourceLayer][feature] = {}; + for (const prop in this.state[sourceLayer][feature]) { + if (!newState[prop]) this.deletedStates[sourceLayer][feature][prop] = null; + } + } else { + for (const key in newState) { + const deletionInQueue = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] && this.deletedStates[sourceLayer][feature][key] === null; + if (deletionInQueue) delete this.deletedStates[sourceLayer][feature][key]; + } + } + } + } + + removeFeatureState(sourceLayer: string, featureId?: number | string, key?: string) { + const sourceLayerDeleted = this.deletedStates[sourceLayer] === null; + if (sourceLayerDeleted) return; + + const feature = String(featureId); + + this.deletedStates[sourceLayer] = this.deletedStates[sourceLayer] || {}; + + if (key && featureId !== undefined) { + if (this.deletedStates[sourceLayer][feature] !== null) { + this.deletedStates[sourceLayer][feature] = this.deletedStates[sourceLayer][feature] || {}; + this.deletedStates[sourceLayer][feature][key] = null; + } + } else if (featureId !== undefined) { + const updateInQueue = this.stateChanges[sourceLayer] && this.stateChanges[sourceLayer][feature]; + if (updateInQueue) { + this.deletedStates[sourceLayer][feature] = {}; + for (key in this.stateChanges[sourceLayer][feature]) this.deletedStates[sourceLayer][feature][key] = null; + + } else { + this.deletedStates[sourceLayer][feature] = null; + } + } else { + this.deletedStates[sourceLayer] = null; + } + + } + + getState(sourceLayer: string, featureId: number | string) { + const feature = String(featureId); + const base = this.state[sourceLayer] || {}; + const changes = this.stateChanges[sourceLayer] || {}; + + const reconciledState = extend({}, base[feature], changes[feature]); + + //return empty object if the whole source layer is awaiting deletion + if (this.deletedStates[sourceLayer] === null) return {}; + else if (this.deletedStates[sourceLayer]) { + const featureDeletions = this.deletedStates[sourceLayer][featureId]; + if (featureDeletions === null) return {}; + for (const prop in featureDeletions) delete reconciledState[prop]; + } + return reconciledState; + } + + initializeTileState(tile: Tile, painter: any) { + tile.setFeatureState(this.state, painter); + } + + coalesceChanges(tiles: {[_: any]: Tile}, painter: any) { + //track changes with full state objects, but only for features that got modified + const featuresChanged: LayerFeatureStates = {}; + + for (const sourceLayer in this.stateChanges) { + this.state[sourceLayer] = this.state[sourceLayer] || {}; + const layerStates = {}; + for (const feature in this.stateChanges[sourceLayer]) { + if (!this.state[sourceLayer][feature]) this.state[sourceLayer][feature] = {}; + extend(this.state[sourceLayer][feature], this.stateChanges[sourceLayer][feature]); + layerStates[feature] = this.state[sourceLayer][feature]; + } + featuresChanged[sourceLayer] = layerStates; + } + + for (const sourceLayer in this.deletedStates) { + this.state[sourceLayer] = this.state[sourceLayer] || {}; + const layerStates = {}; + + if (this.deletedStates[sourceLayer] === null) { + for (const ft in this.state[sourceLayer]) { + layerStates[ft] = {}; + this.state[sourceLayer][ft] = {}; + } + } else { + for (const feature in this.deletedStates[sourceLayer]) { + const deleteWholeFeatureState = this.deletedStates[sourceLayer][feature] === null; + if (deleteWholeFeatureState) this.state[sourceLayer][feature] = {}; + else { + for (const key of Object.keys(this.deletedStates[sourceLayer][feature])) { + delete this.state[sourceLayer][feature][key]; + } + } + layerStates[feature] = this.state[sourceLayer][feature]; + } + } + + featuresChanged[sourceLayer] = featuresChanged[sourceLayer] || {}; + extend(featuresChanged[sourceLayer], layerStates); + } + + this.stateChanges = {}; + this.deletedStates = {}; + + if (Object.keys(featuresChanged).length === 0) return; + + for (const id in tiles) { + const tile = tiles[id]; + tile.setFeatureState(featuresChanged, painter); + } + } +} + +export default SourceFeatureState; diff --git a/node_modules/mapbox-gl/src/source/tile.js b/node_modules/mapbox-gl/src/source/tile.js new file mode 100644 index 0000000000000000000000000000000000000000..419059b7ac2bcc68f97c7ad35fdf5e96ce10c44e --- /dev/null +++ b/node_modules/mapbox-gl/src/source/tile.js @@ -0,0 +1,458 @@ +// @flow + +import {uniqueId, parseCacheControl} from '../util/util'; +import {deserialize as deserializeBucket} from '../data/bucket'; +import FeatureIndex from '../data/feature_index'; +import GeoJSONFeature from '../util/vectortile_to_geojson'; +import featureFilter from '../style-spec/feature_filter'; +import SymbolBucket from '../data/bucket/symbol_bucket'; +import {CollisionBoxArray} from '../data/array_types'; +import Texture from '../render/texture'; +import browser from '../util/browser'; +import toEvaluationFeature from '../data/evaluation_feature'; +import EvaluationParameters from '../style/evaluation_parameters'; +import SourceFeatureState from '../source/source_state'; +import {lazyLoadRTLTextPlugin} from './rtl_text_plugin'; + +const CLOCK_SKEW_RETRY_TIMEOUT = 30000; + +import type {Bucket} from '../data/bucket'; +import type StyleLayer from '../style/style_layer'; +import type {WorkerTileResult} from './worker_source'; +import type Actor from '../util/actor'; +import type DEMData from '../data/dem_data'; +import type {AlphaImage} from '../util/image'; +import type ImageAtlas from '../render/image_atlas'; +import type ImageManager from '../render/image_manager'; +import type Context from '../gl/context'; +import type {OverscaledTileID} from './tile_id'; +import type Framebuffer from '../gl/framebuffer'; +import type Transform from '../geo/transform'; +import type {LayerFeatureStates} from './source_state'; +import type {Cancelable} from '../types/cancelable'; +import type {FilterSpecification} from '../style-spec/types'; + +export type TileState = + | 'loading' // Tile data is in the process of loading. + | 'loaded' // Tile data has been loaded. Tile can be rendered. + | 'reloading' // Tile data has been loaded and is being updated. Tile can be rendered. + | 'unloaded' // Tile data has been deleted. + | 'errored' // Tile data was not loaded because of an error. + | 'expired'; /* Tile data was previously loaded, but has expired per its + * HTTP headers and is in the process of refreshing. */ + +/** + * A tile object is the combination of a Coordinate, which defines + * its place, as well as a unique ID and data tracking for its content + * + * @private + */ +class Tile { + tileID: OverscaledTileID; + uid: number; + uses: number; + tileSize: number; + buckets: {[_: string]: Bucket}; + latestFeatureIndex: ?FeatureIndex; + latestRawTileData: ?ArrayBuffer; + imageAtlas: ?ImageAtlas; + imageAtlasTexture: Texture; + glyphAtlasImage: ?AlphaImage; + glyphAtlasTexture: Texture; + expirationTime: any; + expiredRequestCount: number; + state: TileState; + timeAdded: any; + fadeEndTime: any; + collisionBoxArray: ?CollisionBoxArray; + redoWhenDone: boolean; + showCollisionBoxes: boolean; + placementSource: any; + actor: ?Actor; + vtLayers: {[_: string]: VectorTileLayer}; + + neighboringTiles: ?Object; + dem: ?DEMData; + aborted: ?boolean; + needsHillshadePrepare: ?boolean; + request: ?Cancelable; + texture: any; + fbo: ?Framebuffer; + demTexture: ?Texture; + refreshedUponExpiration: boolean; + reloadCallback: any; + resourceTiming: ?Array; + queryPadding: number; + + symbolFadeHoldUntil: ?number; + hasSymbolBuckets: boolean; + hasRTLText: boolean; + dependencies: Object; + + /** + * @param {OverscaledTileID} tileID + * @param size + * @private + */ + constructor(tileID: OverscaledTileID, size: number) { + this.tileID = tileID; + this.uid = uniqueId(); + this.uses = 0; + this.tileSize = size; + this.buckets = {}; + this.expirationTime = null; + this.queryPadding = 0; + this.hasSymbolBuckets = false; + this.hasRTLText = false; + this.dependencies = {}; + + // Counts the number of times a response was already expired when + // received. We're using this to add a delay when making a new request + // so we don't have to keep retrying immediately in case of a server + // serving expired tiles. + this.expiredRequestCount = 0; + + this.state = 'loading'; + } + + registerFadeDuration(duration: number) { + const fadeEndTime = duration + this.timeAdded; + if (fadeEndTime < browser.now()) return; + if (this.fadeEndTime && fadeEndTime < this.fadeEndTime) return; + + this.fadeEndTime = fadeEndTime; + } + + wasRequested() { + return this.state === 'errored' || this.state === 'loaded' || this.state === 'reloading'; + } + + /** + * Given a data object with a 'buffers' property, load it into + * this tile's elementGroups and buffers properties and set loaded + * to true. If the data is null, like in the case of an empty + * GeoJSON tile, no-op but still set loaded to true. + * @param {Object} data + * @param painter + * @returns {undefined} + * @private + */ + loadVectorData(data: WorkerTileResult, painter: any, justReloaded: ?boolean) { + if (this.hasData()) { + this.unloadVectorData(); + } + + this.state = 'loaded'; + + // empty GeoJSON tile + if (!data) { + this.collisionBoxArray = new CollisionBoxArray(); + return; + } + + if (data.featureIndex) { + this.latestFeatureIndex = data.featureIndex; + if (data.rawTileData) { + // Only vector tiles have rawTileData, and they won't update it for + // 'reloadTile' + this.latestRawTileData = data.rawTileData; + this.latestFeatureIndex.rawTileData = data.rawTileData; + } else if (this.latestRawTileData) { + // If rawTileData hasn't updated, hold onto a pointer to the last + // one we received + this.latestFeatureIndex.rawTileData = this.latestRawTileData; + } + } + this.collisionBoxArray = data.collisionBoxArray; + this.buckets = deserializeBucket(data.buckets, painter.style); + + this.hasSymbolBuckets = false; + for (const id in this.buckets) { + const bucket = this.buckets[id]; + if (bucket instanceof SymbolBucket) { + this.hasSymbolBuckets = true; + if (justReloaded) { + bucket.justReloaded = true; + } else { + break; + } + } + } + + this.hasRTLText = false; + if (this.hasSymbolBuckets) { + for (const id in this.buckets) { + const bucket = this.buckets[id]; + if (bucket instanceof SymbolBucket) { + if (bucket.hasRTLText) { + this.hasRTLText = true; + lazyLoadRTLTextPlugin(); + break; + } + } + } + } + + this.queryPadding = 0; + for (const id in this.buckets) { + const bucket = this.buckets[id]; + this.queryPadding = Math.max(this.queryPadding, painter.style.getLayer(id).queryRadius(bucket)); + } + + if (data.imageAtlas) { + this.imageAtlas = data.imageAtlas; + } + if (data.glyphAtlasImage) { + this.glyphAtlasImage = data.glyphAtlasImage; + } + } + + /** + * Release any data or WebGL resources referenced by this tile. + * @returns {undefined} + * @private + */ + unloadVectorData() { + for (const id in this.buckets) { + this.buckets[id].destroy(); + } + this.buckets = {}; + + if (this.imageAtlasTexture) { + this.imageAtlasTexture.destroy(); + } + + if (this.imageAtlas) { + this.imageAtlas = null; + } + + if (this.glyphAtlasTexture) { + this.glyphAtlasTexture.destroy(); + } + + this.latestFeatureIndex = null; + this.state = 'unloaded'; + } + + getBucket(layer: StyleLayer) { + return this.buckets[layer.id]; + } + + upload(context: Context) { + for (const id in this.buckets) { + const bucket = this.buckets[id]; + if (bucket.uploadPending()) { + bucket.upload(context); + } + } + + const gl = context.gl; + if (this.imageAtlas && !this.imageAtlas.uploaded) { + this.imageAtlasTexture = new Texture(context, this.imageAtlas.image, gl.RGBA); + this.imageAtlas.uploaded = true; + } + + if (this.glyphAtlasImage) { + this.glyphAtlasTexture = new Texture(context, this.glyphAtlasImage, gl.ALPHA); + this.glyphAtlasImage = null; + } + } + + prepare(imageManager: ImageManager) { + if (this.imageAtlas) { + this.imageAtlas.patchUpdatedImages(imageManager, this.imageAtlasTexture); + } + } + + // Queries non-symbol features rendered for this tile. + // Symbol features are queried globally + queryRenderedFeatures(layers: {[_: string]: StyleLayer}, + serializedLayers: {[string]: Object}, + sourceFeatureState: SourceFeatureState, + queryGeometry: Array, + cameraQueryGeometry: Array, + scale: number, + params: { filter: FilterSpecification, layers: Array, availableImages: Array }, + transform: Transform, + maxPitchScaleFactor: number, + pixelPosMatrix: Float32Array): {[_: string]: Array<{ featureIndex: number, feature: GeoJSONFeature }>} { + if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData) + return {}; + + return this.latestFeatureIndex.query({ + queryGeometry, + cameraQueryGeometry, + scale, + tileSize: this.tileSize, + pixelPosMatrix, + transform, + params, + queryPadding: this.queryPadding * maxPitchScaleFactor + }, layers, serializedLayers, sourceFeatureState); + } + + querySourceFeatures(result: Array, params: any) { + const featureIndex = this.latestFeatureIndex; + if (!featureIndex || !featureIndex.rawTileData) return; + + const vtLayers = featureIndex.loadVTLayers(); + + const sourceLayer = params ? params.sourceLayer : ''; + const layer = vtLayers._geojsonTileLayer || vtLayers[sourceLayer]; + + if (!layer) return; + + const filter = featureFilter(params && params.filter); + const {z, x, y} = this.tileID.canonical; + const coord = {z, x, y}; + + for (let i = 0; i < layer.length; i++) { + const feature = layer.feature(i); + if (filter.needGeometry) { + const evaluationFeature = toEvaluationFeature(feature, true); + if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) continue; + } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) { + continue; + } + const id = featureIndex.getId(feature, sourceLayer); + const geojsonFeature = new GeoJSONFeature(feature, z, x, y, id); + (geojsonFeature: any).tile = coord; + result.push(geojsonFeature); + } + } + + hasData() { + return this.state === 'loaded' || this.state === 'reloading' || this.state === 'expired'; + } + + patternsLoaded() { + return this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length; + } + + setExpiryData(data: any) { + const prior = this.expirationTime; + + if (data.cacheControl) { + const parsedCC = parseCacheControl(data.cacheControl); + if (parsedCC['max-age']) this.expirationTime = Date.now() + parsedCC['max-age'] * 1000; + } else if (data.expires) { + this.expirationTime = new Date(data.expires).getTime(); + } + + if (this.expirationTime) { + const now = Date.now(); + let isExpired = false; + + if (this.expirationTime > now) { + isExpired = false; + } else if (!prior) { + isExpired = true; + } else if (this.expirationTime < prior) { + // Expiring date is going backwards: + // fall back to exponential backoff + isExpired = true; + + } else { + const delta = this.expirationTime - prior; + + if (!delta) { + // Server is serving the same expired resource over and over: fall + // back to exponential backoff. + isExpired = true; + + } else { + // Assume that either the client or the server clock is wrong and + // try to interpolate a valid expiration date (from the client POV) + // observing a minimum timeout. + this.expirationTime = now + Math.max(delta, CLOCK_SKEW_RETRY_TIMEOUT); + + } + } + + if (isExpired) { + this.expiredRequestCount++; + this.state = 'expired'; + } else { + this.expiredRequestCount = 0; + } + } + } + + getExpiryTimeout() { + if (this.expirationTime) { + if (this.expiredRequestCount) { + return 1000 * (1 << Math.min(this.expiredRequestCount - 1, 31)); + } else { + // Max value for `setTimeout` implementations is a 32 bit integer; cap this accordingly + return Math.min(this.expirationTime - new Date().getTime(), Math.pow(2, 31) - 1); + } + } + } + + setFeatureState(states: LayerFeatureStates, painter: any) { + if (!this.latestFeatureIndex || + !this.latestFeatureIndex.rawTileData || + Object.keys(states).length === 0) { + return; + } + + const vtLayers = this.latestFeatureIndex.loadVTLayers(); + + for (const id in this.buckets) { + if (!painter.style.hasLayer(id)) continue; + + const bucket = this.buckets[id]; + // Buckets are grouped by common source-layer + const sourceLayerId = bucket.layers[0]['sourceLayer'] || '_geojsonTileLayer'; + const sourceLayer = vtLayers[sourceLayerId]; + const sourceLayerStates = states[sourceLayerId]; + if (!sourceLayer || !sourceLayerStates || Object.keys(sourceLayerStates).length === 0) continue; + + bucket.update(sourceLayerStates, sourceLayer, this.imageAtlas && this.imageAtlas.patternPositions || {}); + const layer = painter && painter.style && painter.style.getLayer(id); + if (layer) { + this.queryPadding = Math.max(this.queryPadding, layer.queryRadius(bucket)); + } + } + } + + holdingForFade(): boolean { + return this.symbolFadeHoldUntil !== undefined; + } + + symbolFadeFinished(): boolean { + return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < browser.now(); + } + + clearFadeHold() { + this.symbolFadeHoldUntil = undefined; + } + + setHoldDuration(duration: number) { + this.symbolFadeHoldUntil = browser.now() + duration; + } + + setDependencies(namespace: string, dependencies: Array) { + const index = {}; + for (const dep of dependencies) { + index[dep] = true; + } + this.dependencies[namespace] = index; + } + + hasDependency(namespaces: Array, keys: Array) { + for (const namespace of namespaces) { + const dependencies = this.dependencies[namespace]; + if (dependencies) { + for (const key of keys) { + if (dependencies[key]) { + return true; + } + } + } + } + return false; + } +} + +export default Tile; diff --git a/node_modules/mapbox-gl/src/source/tile_bounds.js b/node_modules/mapbox-gl/src/source/tile_bounds.js new file mode 100644 index 0000000000000000000000000000000000000000..de9de3a47b9e80d5ea8f130315af196d0a8ef66e --- /dev/null +++ b/node_modules/mapbox-gl/src/source/tile_bounds.js @@ -0,0 +1,38 @@ +// @flow + +import LngLatBounds from '../geo/lng_lat_bounds'; +import {mercatorXfromLng, mercatorYfromLat} from '../geo/mercator_coordinate'; + +import type {CanonicalTileID} from './tile_id'; + +class TileBounds { + bounds: LngLatBounds; + minzoom: number; + maxzoom: number; + + constructor(bounds: [number, number, number, number], minzoom: ?number, maxzoom: ?number) { + this.bounds = LngLatBounds.convert(this.validateBounds(bounds)); + this.minzoom = minzoom || 0; + this.maxzoom = maxzoom || 24; + } + + validateBounds(bounds: [number, number, number, number]) { + // make sure the bounds property contains valid longitude and latitudes + if (!Array.isArray(bounds) || bounds.length !== 4) return [-180, -90, 180, 90]; + return [Math.max(-180, bounds[0]), Math.max(-90, bounds[1]), Math.min(180, bounds[2]), Math.min(90, bounds[3])]; + } + + contains(tileID: CanonicalTileID) { + const worldSize = Math.pow(2, tileID.z); + const level = { + minX: Math.floor(mercatorXfromLng(this.bounds.getWest()) * worldSize), + minY: Math.floor(mercatorYfromLat(this.bounds.getNorth()) * worldSize), + maxX: Math.ceil(mercatorXfromLng(this.bounds.getEast()) * worldSize), + maxY: Math.ceil(mercatorYfromLat(this.bounds.getSouth()) * worldSize) + }; + const hit = tileID.x >= level.minX && tileID.x < level.maxX && tileID.y >= level.minY && tileID.y < level.maxY; + return hit; + } +} + +export default TileBounds; diff --git a/node_modules/mapbox-gl/src/source/tile_cache.js b/node_modules/mapbox-gl/src/source/tile_cache.js new file mode 100644 index 0000000000000000000000000000000000000000..581d8548c6305ea0e6d829a41da4b45269974c11 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/tile_cache.js @@ -0,0 +1,212 @@ +// @flow + +import {OverscaledTileID} from './tile_id'; +import type Tile from './tile'; + +/** + * A [least-recently-used cache](http://en.wikipedia.org/wiki/Cache_algorithms) + * with hash lookup made possible by keeping a list of keys in parallel to + * an array of dictionary of values + * + * @private + */ +class TileCache { + max: number; + data: {[key: string]: Array<{ value: Tile, timeout: ?TimeoutID}>}; + order: Array; + onRemove: (element: Tile) => void; + /** + * @param {number} max number of permitted values + * @param {Function} onRemove callback called with items when they expire + */ + constructor(max: number, onRemove: (element: Tile) => void) { + this.max = max; + this.onRemove = onRemove; + this.reset(); + } + + /** + * Clear the cache + * + * @returns {TileCache} this cache + * @private + */ + reset() { + for (const key in this.data) { + for (const removedData of this.data[key]) { + if (removedData.timeout) clearTimeout(removedData.timeout); + this.onRemove(removedData.value); + } + } + + this.data = {}; + this.order = []; + + return this; + } + + /** + * Add a key, value combination to the cache, trimming its size if this pushes + * it over max length. + * + * @param {OverscaledTileID} tileID lookup key for the item + * @param {*} data any value + * + * @returns {TileCache} this cache + * @private + */ + add(tileID: OverscaledTileID, data: Tile, expiryTimeout: number | void) { + const key = tileID.wrapped().key; + if (this.data[key] === undefined) { + this.data[key] = []; + } + + const dataWrapper = { + value: data, + timeout: undefined + }; + + if (expiryTimeout !== undefined) { + dataWrapper.timeout = setTimeout(() => { + this.remove(tileID, dataWrapper); + }, expiryTimeout); + } + + this.data[key].push(dataWrapper); + this.order.push(key); + + if (this.order.length > this.max) { + const removedData = this._getAndRemoveByKey(this.order[0]); + if (removedData) this.onRemove(removedData); + } + + return this; + } + + /** + * Determine whether the value attached to `key` is present + * + * @param {OverscaledTileID} tileID the key to be looked-up + * @returns {boolean} whether the cache has this value + * @private + */ + has(tileID: OverscaledTileID): boolean { + return tileID.wrapped().key in this.data; + } + + /** + * Get the value attached to a specific key and remove data from cache. + * If the key is not found, returns `null` + * + * @param {OverscaledTileID} tileID the key to look up + * @returns {*} the data, or null if it isn't found + * @private + */ + getAndRemove(tileID: OverscaledTileID): ?Tile { + if (!this.has(tileID)) { return null; } + return this._getAndRemoveByKey(tileID.wrapped().key); + } + + /* + * Get and remove the value with the specified key. + */ + _getAndRemoveByKey(key: string): ?Tile { + const data = this.data[key].shift(); + if (data.timeout) clearTimeout(data.timeout); + + if (this.data[key].length === 0) { + delete this.data[key]; + } + this.order.splice(this.order.indexOf(key), 1); + + return data.value; + } + + /* + * Get the value with the specified (wrapped tile) key. + */ + getByKey(key: string): ?Tile { + const data = this.data[key]; + return data ? data[0].value : null; + } + + /** + * Get the value attached to a specific key without removing data + * from the cache. If the key is not found, returns `null` + * + * @param {OverscaledTileID} tileID the key to look up + * @returns {*} the data, or null if it isn't found + * @private + */ + get(tileID: OverscaledTileID): ?Tile { + if (!this.has(tileID)) { return null; } + + const data = this.data[tileID.wrapped().key][0]; + return data.value; + } + + /** + * Remove a key/value combination from the cache. + * + * @param {OverscaledTileID} tileID the key for the pair to delete + * @param {Tile} value If a value is provided, remove that exact version of the value. + * @returns {TileCache} this cache + * @private + */ + remove(tileID: OverscaledTileID, value: ?{ value: Tile, timeout: ?TimeoutID}) { + if (!this.has(tileID)) { return this; } + const key = tileID.wrapped().key; + + const dataIndex = value === undefined ? 0 : this.data[key].indexOf(value); + const data = this.data[key][dataIndex]; + this.data[key].splice(dataIndex, 1); + if (data.timeout) clearTimeout(data.timeout); + if (this.data[key].length === 0) { + delete this.data[key]; + } + this.onRemove(data.value); + this.order.splice(this.order.indexOf(key), 1); + + return this; + } + + /** + * Change the max size of the cache. + * + * @param {number} max the max size of the cache + * @returns {TileCache} this cache + * @private + */ + setMaxSize(max: number): TileCache { + this.max = max; + + while (this.order.length > this.max) { + const removedData = this._getAndRemoveByKey(this.order[0]); + if (removedData) this.onRemove(removedData); + } + + return this; + } + + /** + * Remove entries that do not pass a filter function. Used for removing + * stale tiles from the cache. + * + * @param {function} filterFn Determines whether the tile is filtered. If the supplied function returns false, the tile will be filtered out. + */ + filter(filterFn: (tile: Tile) => boolean) { + const removed = []; + for (const key in this.data) { + for (const entry of this.data[key]) { + if (!filterFn(entry.value)) { + removed.push(entry); + } + } + } + for (const r of removed) { + this.remove(r.value.tileID, r); + } + } +} + +export default TileCache; diff --git a/node_modules/mapbox-gl/src/source/tile_id.js b/node_modules/mapbox-gl/src/source/tile_id.js new file mode 100644 index 0000000000000000000000000000000000000000..244209cee0bd5c34edfa158e25b318d91c2b2600 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/tile_id.js @@ -0,0 +1,199 @@ +// @flow + +import {getTileBBox} from '@mapbox/whoots-js'; +import EXTENT from '../data/extent'; +import Point from '@mapbox/point-geometry'; +import MercatorCoordinate from '../geo/mercator_coordinate'; + +import assert from 'assert'; +import {register} from '../util/web_worker_transfer'; + +export class CanonicalTileID { + z: number; + x: number; + y: number; + key: string; + + constructor(z: number, x: number, y: number) { + assert(z >= 0 && z <= 25); + assert(x >= 0 && x < Math.pow(2, z)); + assert(y >= 0 && y < Math.pow(2, z)); + this.z = z; + this.x = x; + this.y = y; + this.key = calculateKey(0, z, z, x, y); + } + + equals(id: CanonicalTileID) { + return this.z === id.z && this.x === id.x && this.y === id.y; + } + + // given a list of urls, choose a url template and return a tile URL + url(urls: Array, scheme: ?string) { + const bbox = getTileBBox(this.x, this.y, this.z); + const quadkey = getQuadkey(this.z, this.x, this.y); + + return urls[(this.x + this.y) % urls.length] + .replace('{prefix}', (this.x % 16).toString(16) + (this.y % 16).toString(16)) + .replace('{z}', String(this.z)) + .replace('{x}', String(this.x)) + .replace('{y}', String(scheme === 'tms' ? (Math.pow(2, this.z) - this.y - 1) : this.y)) + .replace('{quadkey}', quadkey) + .replace('{bbox-epsg-3857}', bbox); + } + + getTilePoint(coord: MercatorCoordinate) { + const tilesAtZoom = Math.pow(2, this.z); + return new Point( + (coord.x * tilesAtZoom - this.x) * EXTENT, + (coord.y * tilesAtZoom - this.y) * EXTENT); + } + + toString() { + return `${this.z}/${this.x}/${this.y}`; + } +} + +export class UnwrappedTileID { + wrap: number; + canonical: CanonicalTileID; + key: string; + + constructor(wrap: number, canonical: CanonicalTileID) { + this.wrap = wrap; + this.canonical = canonical; + this.key = calculateKey(wrap, canonical.z, canonical.z, canonical.x, canonical.y); + } +} + +export class OverscaledTileID { + overscaledZ: number; + wrap: number; + canonical: CanonicalTileID; + key: string; + posMatrix: Float32Array; + + constructor(overscaledZ: number, wrap: number, z: number, x: number, y: number) { + assert(overscaledZ >= z); + this.overscaledZ = overscaledZ; + this.wrap = wrap; + this.canonical = new CanonicalTileID(z, +x, +y); + this.key = calculateKey(wrap, overscaledZ, z, x, y); + } + + equals(id: OverscaledTileID) { + return this.overscaledZ === id.overscaledZ && this.wrap === id.wrap && this.canonical.equals(id.canonical); + } + + scaledTo(targetZ: number) { + assert(targetZ <= this.overscaledZ); + const zDifference = this.canonical.z - targetZ; + if (targetZ > this.canonical.z) { + return new OverscaledTileID(targetZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y); + } else { + return new OverscaledTileID(targetZ, this.wrap, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference); + } + } + + /* + * calculateScaledKey is an optimization: + * when withWrap == true, implements the same as this.scaledTo(z).key, + * when withWrap == false, implements the same as this.scaledTo(z).wrapped().key. + */ + calculateScaledKey(targetZ: number, withWrap: boolean): string { + assert(targetZ <= this.overscaledZ); + const zDifference = this.canonical.z - targetZ; + if (targetZ > this.canonical.z) { + return calculateKey(this.wrap * +withWrap, targetZ, this.canonical.z, this.canonical.x, this.canonical.y); + } else { + return calculateKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference); + } + } + + isChildOf(parent: OverscaledTileID) { + if (parent.wrap !== this.wrap) { + // We can't be a child if we're in a different world copy + return false; + } + const zDifference = this.canonical.z - parent.canonical.z; + // We're first testing for z == 0, to avoid a 32 bit shift, which is undefined. + return parent.overscaledZ === 0 || ( + parent.overscaledZ < this.overscaledZ && + parent.canonical.x === (this.canonical.x >> zDifference) && + parent.canonical.y === (this.canonical.y >> zDifference)); + } + + children(sourceMaxZoom: number) { + if (this.overscaledZ >= sourceMaxZoom) { + // return a single tile coord representing a an overscaled tile + return [new OverscaledTileID(this.overscaledZ + 1, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y)]; + } + + const z = this.canonical.z + 1; + const x = this.canonical.x * 2; + const y = this.canonical.y * 2; + return [ + new OverscaledTileID(z, this.wrap, z, x, y), + new OverscaledTileID(z, this.wrap, z, x + 1, y), + new OverscaledTileID(z, this.wrap, z, x, y + 1), + new OverscaledTileID(z, this.wrap, z, x + 1, y + 1) + ]; + } + + isLessThan(rhs: OverscaledTileID) { + if (this.wrap < rhs.wrap) return true; + if (this.wrap > rhs.wrap) return false; + + if (this.overscaledZ < rhs.overscaledZ) return true; + if (this.overscaledZ > rhs.overscaledZ) return false; + + if (this.canonical.x < rhs.canonical.x) return true; + if (this.canonical.x > rhs.canonical.x) return false; + + if (this.canonical.y < rhs.canonical.y) return true; + return false; + } + + wrapped() { + return new OverscaledTileID(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y); + } + + unwrapTo(wrap: number) { + return new OverscaledTileID(this.overscaledZ, wrap, this.canonical.z, this.canonical.x, this.canonical.y); + } + + overscaleFactor() { + return Math.pow(2, this.overscaledZ - this.canonical.z); + } + + toUnwrapped() { + return new UnwrappedTileID(this.wrap, this.canonical); + } + + toString() { + return `${this.overscaledZ}/${this.canonical.x}/${this.canonical.y}`; + } + + getTilePoint(coord: MercatorCoordinate) { + return this.canonical.getTilePoint(new MercatorCoordinate(coord.x - this.wrap, coord.y)); + } +} + +function calculateKey(wrap: number, overscaledZ: number, z: number, x: number, y: number): string { + wrap *= 2; + if (wrap < 0) wrap = wrap * -1 - 1; + const dim = 1 << z; + return (dim * dim * wrap + dim * y + x).toString(36) + z.toString(36) + overscaledZ.toString(36); +} + +function getQuadkey(z, x, y) { + let quadkey = '', mask; + for (let i = z; i > 0; i--) { + mask = 1 << (i - 1); + quadkey += ((x & mask ? 1 : 0) + (y & mask ? 2 : 0)); + } + return quadkey; +} + +register('CanonicalTileID', CanonicalTileID); +register('OverscaledTileID', OverscaledTileID, {omit: ['posMatrix']}); diff --git a/node_modules/mapbox-gl/src/source/vector_tile_source.js b/node_modules/mapbox-gl/src/source/vector_tile_source.js new file mode 100644 index 0000000000000000000000000000000000000000..c0ba8eea6d1ef6d8637bfd1b4dc9f0c15c252192 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/vector_tile_source.js @@ -0,0 +1,259 @@ +// @flow + +import {Event, ErrorEvent, Evented} from '../util/evented'; + +import {extend, pick} from '../util/util'; +import loadTileJSON from './load_tilejson'; +import {postTurnstileEvent, postMapLoadEvent} from '../util/mapbox'; +import TileBounds from './tile_bounds'; +import {ResourceType} from '../util/ajax'; +import browser from '../util/browser'; +import {cacheEntryPossiblyAdded} from '../util/tile_request_cache'; + +import type {Source} from './source'; +import type {OverscaledTileID} from './tile_id'; +import type Map from '../ui/map'; +import type Dispatcher from '../util/dispatcher'; +import type Tile from './tile'; +import type {Callback} from '../types/callback'; +import type {Cancelable} from '../types/cancelable'; +import type {VectorSourceSpecification, PromoteIdSpecification} from '../style-spec/types'; + +/** + * A source containing vector tiles in [Mapbox Vector Tile format](https://docs.mapbox.com/vector-tiles/reference/). + * (See the [Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector) for detailed documentation of options.) + * + * @example + * map.addSource('some id', { + * type: 'vector', + * url: 'mapbox://mapbox.mapbox-streets-v6' + * }); + * + * @example + * map.addSource('some id', { + * type: 'vector', + * tiles: ['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt'], + * minzoom: 6, + * maxzoom: 14 + * }); + * + * @example + * map.getSource('some id').setUrl("mapbox://mapbox.mapbox-streets-v6"); + * + * @example + * map.getSource('some id').setTiles(['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt']); + * @see [Add a vector tile source](https://docs.mapbox.com/mapbox-gl-js/example/vector-source/) + * @see [Add a third party vector tile source](https://docs.mapbox.com/mapbox-gl-js/example/third-party/) + */ +class VectorTileSource extends Evented implements Source { + type: 'vector'; + id: string; + minzoom: number; + maxzoom: number; + url: string; + scheme: string; + tileSize: number; + promoteId: ?PromoteIdSpecification; + + _options: VectorSourceSpecification; + _collectResourceTiming: boolean; + dispatcher: Dispatcher; + map: Map; + bounds: ?[number, number, number, number]; + tiles: Array; + tileBounds: TileBounds; + reparseOverscaled: boolean; + isTileClipped: boolean; + _tileJSONRequest: ?Cancelable; + _loaded: boolean; + + constructor(id: string, options: VectorSourceSpecification & {collectResourceTiming: boolean}, dispatcher: Dispatcher, eventedParent: Evented) { + super(); + this.id = id; + this.dispatcher = dispatcher; + + this.type = 'vector'; + this.minzoom = 0; + this.maxzoom = 22; + this.scheme = 'xyz'; + this.tileSize = 512; + this.reparseOverscaled = true; + this.isTileClipped = true; + this._loaded = false; + + extend(this, pick(options, ['url', 'scheme', 'tileSize', 'promoteId'])); + this._options = extend({type: 'vector'}, options); + + this._collectResourceTiming = options.collectResourceTiming; + + if (this.tileSize !== 512) { + throw new Error('vector tile sources must have a tileSize of 512'); + } + + this.setEventedParent(eventedParent); + } + + load() { + this._loaded = false; + this.fire(new Event('dataloading', {dataType: 'source'})); + this._tileJSONRequest = loadTileJSON(this._options, this.map._requestManager, (err, tileJSON) => { + this._tileJSONRequest = null; + this._loaded = true; + if (err) { + this.fire(new ErrorEvent(err)); + } else if (tileJSON) { + extend(this, tileJSON); + if (tileJSON.bounds) this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom); + postTurnstileEvent(tileJSON.tiles, this.map._requestManager._customAccessToken); + postMapLoadEvent(tileJSON.tiles, this.map._getMapId(), this.map._requestManager._skuToken, this.map._requestManager._customAccessToken); + + // `content` is included here to prevent a race condition where `Style#_updateSources` is called + // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives + // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088 + this.fire(new Event('data', {dataType: 'source', sourceDataType: 'metadata'})); + this.fire(new Event('data', {dataType: 'source', sourceDataType: 'content'})); + } + }); + } + + loaded(): boolean { + return this._loaded; + } + + hasTile(tileID: OverscaledTileID) { + return !this.tileBounds || this.tileBounds.contains(tileID.canonical); + } + + onAdd(map: Map) { + this.map = map; + this.load(); + } + + setSourceProperty(callback: Function) { + if (this._tileJSONRequest) { + this._tileJSONRequest.cancel(); + } + + callback(); + + const sourceCache = this.map.style.sourceCaches[this.id]; + sourceCache.clearTiles(); + this.load(); + } + + /** + * Sets the source `tiles` property and re-renders the map. + * + * @param {string[]} tiles An array of one or more tile source URLs, as in the TileJSON spec. + * @returns {VectorTileSource} this + */ + setTiles(tiles: Array) { + this.setSourceProperty(() => { + this._options.tiles = tiles; + }); + + return this; + } + + /** + * Sets the source `url` property and re-renders the map. + * + * @param {string} url A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://`. + * @returns {VectorTileSource} this + */ + setUrl(url: string) { + this.setSourceProperty(() => { + this.url = url; + this._options.url = url; + }); + + return this; + } + + onRemove() { + if (this._tileJSONRequest) { + this._tileJSONRequest.cancel(); + this._tileJSONRequest = null; + } + } + + serialize() { + return extend({}, this._options); + } + + loadTile(tile: Tile, callback: Callback) { + const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme)); + const params = { + request: this.map._requestManager.transformRequest(url, ResourceType.Tile), + uid: tile.uid, + tileID: tile.tileID, + zoom: tile.tileID.overscaledZ, + tileSize: this.tileSize * tile.tileID.overscaleFactor(), + type: this.type, + source: this.id, + pixelRatio: browser.devicePixelRatio, + showCollisionBoxes: this.map.showCollisionBoxes, + promoteId: this.promoteId + }; + params.request.collectResourceTiming = this._collectResourceTiming; + + if (!tile.actor || tile.state === 'expired') { + tile.actor = this.dispatcher.getActor(); + tile.request = tile.actor.send('loadTile', params, done.bind(this)); + } else if (tile.state === 'loading') { + // schedule tile reloading after it has been loaded + tile.reloadCallback = callback; + } else { + tile.request = tile.actor.send('reloadTile', params, done.bind(this)); + } + + function done(err, data) { + delete tile.request; + + if (tile.aborted) + return callback(null); + + if (err && err.status !== 404) { + return callback(err); + } + + if (data && data.resourceTiming) + tile.resourceTiming = data.resourceTiming; + + if (this.map._refreshExpiredTiles && data) tile.setExpiryData(data); + tile.loadVectorData(data, this.map.painter); + + cacheEntryPossiblyAdded(this.dispatcher); + + callback(null); + + if (tile.reloadCallback) { + this.loadTile(tile, tile.reloadCallback); + tile.reloadCallback = null; + } + } + } + + abortTile(tile: Tile) { + if (tile.request) { + tile.request.cancel(); + delete tile.request; + } + if (tile.actor) { + tile.actor.send('abortTile', {uid: tile.uid, type: this.type, source: this.id}, undefined); + } + } + + unloadTile(tile: Tile) { + tile.unloadVectorData(); + if (tile.actor) { + tile.actor.send('removeTile', {uid: tile.uid, type: this.type, source: this.id}, undefined); + } + } + + hasTransition() { + return false; + } +} + +export default VectorTileSource; diff --git a/node_modules/mapbox-gl/src/source/vector_tile_worker_source.js b/node_modules/mapbox-gl/src/source/vector_tile_worker_source.js new file mode 100644 index 0000000000000000000000000000000000000000..1effce4be14a457bbf84419e29249ca0708d0adc --- /dev/null +++ b/node_modules/mapbox-gl/src/source/vector_tile_worker_source.js @@ -0,0 +1,216 @@ +// @flow + +import {getArrayBuffer} from '../util/ajax'; + +import vt from '@mapbox/vector-tile'; +import Protobuf from 'pbf'; +import WorkerTile from './worker_tile'; +import {extend} from '../util/util'; +import {RequestPerformance} from '../util/performance'; + +import type { + WorkerSource, + WorkerTileParameters, + WorkerTileCallback, + TileParameters +} from '../source/worker_source'; + +import type Actor from '../util/actor'; +import type StyleLayerIndex from '../style/style_layer_index'; +import type {Callback} from '../types/callback'; + +export type LoadVectorTileResult = { + vectorTile: VectorTile; + rawData: ArrayBuffer; + expires?: any; + cacheControl?: any; + resourceTiming?: Array; +}; + +/** + * @callback LoadVectorDataCallback + * @param error + * @param vectorTile + * @private + */ +export type LoadVectorDataCallback = Callback; + +export type AbortVectorData = () => void; +export type LoadVectorData = (params: WorkerTileParameters, callback: LoadVectorDataCallback) => ?AbortVectorData; + +/** + * @private + */ +function loadVectorTile(params: WorkerTileParameters, callback: LoadVectorDataCallback) { + const request = getArrayBuffer(params.request, (err: ?Error, data: ?ArrayBuffer, cacheControl: ?string, expires: ?string) => { + if (err) { + callback(err); + } else if (data) { + callback(null, { + vectorTile: new vt.VectorTile(new Protobuf(data)), + rawData: data, + cacheControl, + expires + }); + } + }); + return () => { + request.cancel(); + callback(); + }; +} + +/** + * The {@link WorkerSource} implementation that supports {@link VectorTileSource}. + * This class is designed to be easily reused to support custom source types + * for data formats that can be parsed/converted into an in-memory VectorTile + * representation. To do so, create it with + * `new VectorTileWorkerSource(actor, styleLayers, customLoadVectorDataFunction)`. + * + * @private + */ +class VectorTileWorkerSource implements WorkerSource { + actor: Actor; + layerIndex: StyleLayerIndex; + availableImages: Array; + loadVectorData: LoadVectorData; + loading: {[_: string]: WorkerTile }; + loaded: {[_: string]: WorkerTile }; + + /** + * @param [loadVectorData] Optional method for custom loading of a VectorTile + * object based on parameters passed from the main-thread Source. See + * {@link VectorTileWorkerSource#loadTile}. The default implementation simply + * loads the pbf at `params.url`. + * @private + */ + constructor(actor: Actor, layerIndex: StyleLayerIndex, availableImages: Array, loadVectorData: ?LoadVectorData) { + this.actor = actor; + this.layerIndex = layerIndex; + this.availableImages = availableImages; + this.loadVectorData = loadVectorData || loadVectorTile; + this.loading = {}; + this.loaded = {}; + } + + /** + * Implements {@link WorkerSource#loadTile}. Delegates to + * {@link VectorTileWorkerSource#loadVectorData} (which by default expects + * a `params.url` property) for fetching and producing a VectorTile object. + * @private + */ + loadTile(params: WorkerTileParameters, callback: WorkerTileCallback) { + const uid = params.uid; + + if (!this.loading) + this.loading = {}; + + const perf = (params && params.request && params.request.collectResourceTiming) ? + new RequestPerformance(params.request) : false; + + const workerTile = this.loading[uid] = new WorkerTile(params); + workerTile.abort = this.loadVectorData(params, (err, response) => { + delete this.loading[uid]; + + if (err || !response) { + workerTile.status = 'done'; + this.loaded[uid] = workerTile; + return callback(err); + } + + const rawTileData = response.rawData; + const cacheControl = {}; + if (response.expires) cacheControl.expires = response.expires; + if (response.cacheControl) cacheControl.cacheControl = response.cacheControl; + + const resourceTiming = {}; + if (perf) { + const resourceTimingData = perf.finish(); + // it's necessary to eval the result of getEntriesByName() here via parse/stringify + // late evaluation in the main thread causes TypeError: illegal invocation + if (resourceTimingData) + resourceTiming.resourceTiming = JSON.parse(JSON.stringify(resourceTimingData)); + } + + workerTile.vectorTile = response.vectorTile; + workerTile.parse(response.vectorTile, this.layerIndex, this.availableImages, this.actor, (err, result) => { + if (err || !result) return callback(err); + + // Transferring a copy of rawTileData because the worker needs to retain its copy. + callback(null, extend({rawTileData: rawTileData.slice(0)}, result, cacheControl, resourceTiming)); + }); + + this.loaded = this.loaded || {}; + this.loaded[uid] = workerTile; + }); + } + + /** + * Implements {@link WorkerSource#reloadTile}. + * @private + */ + reloadTile(params: WorkerTileParameters, callback: WorkerTileCallback) { + const loaded = this.loaded, + uid = params.uid, + vtSource = this; + if (loaded && loaded[uid]) { + const workerTile = loaded[uid]; + workerTile.showCollisionBoxes = params.showCollisionBoxes; + + const done = (err, data) => { + const reloadCallback = workerTile.reloadCallback; + if (reloadCallback) { + delete workerTile.reloadCallback; + workerTile.parse(workerTile.vectorTile, vtSource.layerIndex, this.availableImages, vtSource.actor, reloadCallback); + } + callback(err, data); + }; + + if (workerTile.status === 'parsing') { + workerTile.reloadCallback = done; + } else if (workerTile.status === 'done') { + // if there was no vector tile data on the initial load, don't try and re-parse tile + if (workerTile.vectorTile) { + workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, done); + } else { + done(); + } + } + } + } + + /** + * Implements {@link WorkerSource#abortTile}. + * + * @param params + * @param params.uid The UID for this tile. + * @private + */ + abortTile(params: TileParameters, callback: WorkerTileCallback) { + const loading = this.loading, + uid = params.uid; + if (loading && loading[uid] && loading[uid].abort) { + loading[uid].abort(); + delete loading[uid]; + } + callback(); + } + + /** + * Implements {@link WorkerSource#removeTile}. + * + * @param params + * @param params.uid The UID for this tile. + * @private + */ + removeTile(params: TileParameters, callback: WorkerTileCallback) { + const loaded = this.loaded, + uid = params.uid; + if (loaded && loaded[uid]) { + delete loaded[uid]; + } + callback(); + } +} + +export default VectorTileWorkerSource; diff --git a/node_modules/mapbox-gl/src/source/video_source.js b/node_modules/mapbox-gl/src/source/video_source.js new file mode 100644 index 0000000000000000000000000000000000000000..a6d235847430e48d4834e232ce23132f449a81f1 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/video_source.js @@ -0,0 +1,206 @@ +// @flow + +import {getVideo, ResourceType} from '../util/ajax'; + +import ImageSource from './image_source'; +import rasterBoundsAttributes from '../data/raster_bounds_attributes'; +import SegmentVector from '../data/segment'; +import Texture from '../render/texture'; +import {ErrorEvent} from '../util/evented'; +import ValidationError from '../style-spec/error/validation_error'; + +import type Map from '../ui/map'; +import type Dispatcher from '../util/dispatcher'; +import type {Evented} from '../util/evented'; +import type {VideoSourceSpecification} from '../style-spec/types'; + +/** + * A data source containing video. + * (See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-video) for detailed documentation of options.) + * + * @example + * // add to map + * map.addSource('some id', { + * type: 'video', + * url: [ + * 'https://www.mapbox.com/blog/assets/baltimore-smoke.mp4', + * 'https://www.mapbox.com/blog/assets/baltimore-smoke.webm' + * ], + * coordinates: [ + * [-76.54, 39.18], + * [-76.52, 39.18], + * [-76.52, 39.17], + * [-76.54, 39.17] + * ] + * }); + * + * // update + * var mySource = map.getSource('some id'); + * mySource.setCoordinates([ + * [-76.54335737228394, 39.18579907229748], + * [-76.52803659439087, 39.1838364847587], + * [-76.5295386314392, 39.17683392507606], + * [-76.54520273208618, 39.17876344106642] + * ]); + * + * map.removeSource('some id'); // remove + * @see [Add a video](https://www.mapbox.com/mapbox-gl-js/example/video-on-a-map/) + */ +class VideoSource extends ImageSource { + options: VideoSourceSpecification; + urls: Array; + video: HTMLVideoElement; + roundZoom: boolean; + + /** + * @private + */ + constructor(id: string, options: VideoSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) { + super(id, options, dispatcher, eventedParent); + this.roundZoom = true; + this.type = 'video'; + this.options = options; + } + + load() { + this._loaded = false; + const options = this.options; + + this.urls = []; + for (const url of options.urls) { + this.urls.push(this.map._requestManager.transformRequest(url, ResourceType.Source).url); + } + + getVideo(this.urls, (err, video) => { + this._loaded = true; + if (err) { + this.fire(new ErrorEvent(err)); + } else if (video) { + this.video = video; + this.video.loop = true; + + // Prevent the video from taking over the screen in iOS + this.video.setAttribute('playsinline', ''); + + // Start repainting when video starts playing. hasTransition() will then return + // true to trigger additional frames as long as the videos continues playing. + this.video.addEventListener('playing', () => { + this.map.triggerRepaint(); + }); + + if (this.map) { + this.video.play(); + } + + this._finishLoading(); + } + }); + } + + /** + * Pauses the video. + */ + pause() { + if (this.video) { + this.video.pause(); + } + } + + /** + * Plays the video. + */ + play() { + if (this.video) { + this.video.play(); + } + } + + /** + * Sets playback to a timestamp, in seconds. + * @private + */ + seek(seconds: number) { + if (this.video) { + const seekableRange = this.video.seekable; + if (seconds < seekableRange.start(0) || seconds > seekableRange.end(0)) { + this.fire(new ErrorEvent(new ValidationError(`sources.${this.id}`, null, `Playback for this video can be set only between the ${seekableRange.start(0)} and ${seekableRange.end(0)}-second mark.`))); + } else this.video.currentTime = seconds; + } + } + + /** + * Returns the HTML `video` element. + * + * @returns {HTMLVideoElement} The HTML `video` element. + */ + getVideo() { + return this.video; + } + + onAdd(map: Map) { + if (this.map) return; + this.map = map; + this.load(); + if (this.video) { + this.video.play(); + this.setCoordinates(this.coordinates); + } + } + + /** + * Sets the video's coordinates and re-renders the map. + * + * @method setCoordinates + * @instance + * @memberof VideoSource + * @returns {VideoSource} this + */ + // setCoordinates inherited from ImageSource + + prepare() { + if (Object.keys(this.tiles).length === 0 || this.video.readyState < 2) { + return; // not enough data for current position + } + + const context = this.map.painter.context; + const gl = context.gl; + + if (!this.boundsBuffer) { + this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members); + } + + if (!this.boundsSegments) { + this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2); + } + + if (!this.texture) { + this.texture = new Texture(context, this.video, gl.RGBA); + this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + } else if (!this.video.paused) { + this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE); + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, this.video); + } + + for (const w in this.tiles) { + const tile = this.tiles[w]; + if (tile.state !== 'loaded') { + tile.state = 'loaded'; + tile.texture = this.texture; + } + } + } + + serialize() { + return { + type: 'video', + urls: this.urls, + coordinates: this.coordinates + }; + } + + hasTransition() { + return this.video && !this.video.paused; + } +} + +export default VideoSource; diff --git a/node_modules/mapbox-gl/src/source/worker.js b/node_modules/mapbox-gl/src/source/worker.js new file mode 100644 index 0000000000000000000000000000000000000000..27a10fa3a548039cd1cfd417191d4226597db81f --- /dev/null +++ b/node_modules/mapbox-gl/src/source/worker.js @@ -0,0 +1,240 @@ +// @flow + +import Actor from '../util/actor'; + +import StyleLayerIndex from '../style/style_layer_index'; +import VectorTileWorkerSource from './vector_tile_worker_source'; +import RasterDEMTileWorkerSource from './raster_dem_tile_worker_source'; +import GeoJSONWorkerSource from './geojson_worker_source'; +import assert from 'assert'; +import {plugin as globalRTLTextPlugin} from './rtl_text_plugin'; +import {enforceCacheSizeLimit} from '../util/tile_request_cache'; + +import type { + WorkerSource, + WorkerTileParameters, + WorkerDEMTileParameters, + WorkerTileCallback, + WorkerDEMTileCallback, + TileParameters +} from '../source/worker_source'; + +import type {WorkerGlobalScopeInterface} from '../util/web_worker'; +import type {Callback} from '../types/callback'; +import type {LayerSpecification} from '../style-spec/types'; +import type {PluginState} from './rtl_text_plugin'; + +/** + * @private + */ +export default class Worker { + self: WorkerGlobalScopeInterface; + actor: Actor; + layerIndexes: {[_: string]: StyleLayerIndex }; + availableImages: {[_: string]: Array }; + workerSourceTypes: {[_: string]: Class }; + workerSources: {[_: string]: {[_: string]: {[_: string]: WorkerSource } } }; + demWorkerSources: {[_: string]: {[_: string]: RasterDEMTileWorkerSource } }; + referrer: ?string; + + constructor(self: WorkerGlobalScopeInterface) { + this.self = self; + this.actor = new Actor(self, this); + + this.layerIndexes = {}; + this.availableImages = {}; + + this.workerSourceTypes = { + vector: VectorTileWorkerSource, + geojson: GeoJSONWorkerSource + }; + + // [mapId][sourceType][sourceName] => worker source instance + this.workerSources = {}; + this.demWorkerSources = {}; + + this.self.registerWorkerSource = (name: string, WorkerSource: Class) => { + if (this.workerSourceTypes[name]) { + throw new Error(`Worker source with name "${name}" already registered.`); + } + this.workerSourceTypes[name] = WorkerSource; + }; + + // This is invoked by the RTL text plugin when the download via the `importScripts` call has finished, and the code has been parsed. + this.self.registerRTLTextPlugin = (rtlTextPlugin: {applyArabicShaping: Function, processBidirectionalText: Function, processStyledBidirectionalText?: Function}) => { + if (globalRTLTextPlugin.isParsed()) { + throw new Error('RTL text plugin already registered.'); + } + globalRTLTextPlugin['applyArabicShaping'] = rtlTextPlugin.applyArabicShaping; + globalRTLTextPlugin['processBidirectionalText'] = rtlTextPlugin.processBidirectionalText; + globalRTLTextPlugin['processStyledBidirectionalText'] = rtlTextPlugin.processStyledBidirectionalText; + }; + } + + setReferrer(mapID: string, referrer: string) { + this.referrer = referrer; + } + + setImages(mapId: string, images: Array, callback: WorkerTileCallback) { + this.availableImages[mapId] = images; + for (const workerSource in this.workerSources[mapId]) { + const ws = this.workerSources[mapId][workerSource]; + for (const source in ws) { + ws[source].availableImages = images; + } + } + callback(); + } + + setLayers(mapId: string, layers: Array, callback: WorkerTileCallback) { + this.getLayerIndex(mapId).replace(layers); + callback(); + } + + updateLayers(mapId: string, params: {layers: Array, removedIds: Array}, callback: WorkerTileCallback) { + this.getLayerIndex(mapId).update(params.layers, params.removedIds); + callback(); + } + + loadTile(mapId: string, params: WorkerTileParameters & {type: string}, callback: WorkerTileCallback) { + assert(params.type); + this.getWorkerSource(mapId, params.type, params.source).loadTile(params, callback); + } + + loadDEMTile(mapId: string, params: WorkerDEMTileParameters, callback: WorkerDEMTileCallback) { + this.getDEMWorkerSource(mapId, params.source).loadTile(params, callback); + } + + reloadTile(mapId: string, params: WorkerTileParameters & {type: string}, callback: WorkerTileCallback) { + assert(params.type); + this.getWorkerSource(mapId, params.type, params.source).reloadTile(params, callback); + } + + abortTile(mapId: string, params: TileParameters & {type: string}, callback: WorkerTileCallback) { + assert(params.type); + this.getWorkerSource(mapId, params.type, params.source).abortTile(params, callback); + } + + removeTile(mapId: string, params: TileParameters & {type: string}, callback: WorkerTileCallback) { + assert(params.type); + this.getWorkerSource(mapId, params.type, params.source).removeTile(params, callback); + } + + removeDEMTile(mapId: string, params: TileParameters) { + this.getDEMWorkerSource(mapId, params.source).removeTile(params); + } + + removeSource(mapId: string, params: {source: string} & {type: string}, callback: WorkerTileCallback) { + assert(params.type); + assert(params.source); + + if (!this.workerSources[mapId] || + !this.workerSources[mapId][params.type] || + !this.workerSources[mapId][params.type][params.source]) { + return; + } + + const worker = this.workerSources[mapId][params.type][params.source]; + delete this.workerSources[mapId][params.type][params.source]; + + if (worker.removeSource !== undefined) { + worker.removeSource(params, callback); + } else { + callback(); + } + } + + /** + * Load a {@link WorkerSource} script at params.url. The script is run + * (using importScripts) with `registerWorkerSource` in scope, which is a + * function taking `(name, workerSourceObject)`. + * @private + */ + loadWorkerSource(map: string, params: { url: string }, callback: Callback) { + try { + this.self.importScripts(params.url); + callback(); + } catch (e) { + callback(e.toString()); + } + } + + syncRTLPluginState(map: string, state: PluginState, callback: Callback) { + try { + globalRTLTextPlugin.setState(state); + const pluginURL = globalRTLTextPlugin.getPluginURL(); + if ( + globalRTLTextPlugin.isLoaded() && + !globalRTLTextPlugin.isParsed() && + pluginURL != null // Not possible when `isLoaded` is true, but keeps flow happy + ) { + this.self.importScripts(pluginURL); + const complete = globalRTLTextPlugin.isParsed(); + const error = complete ? undefined : new Error(`RTL Text Plugin failed to import scripts from ${pluginURL}`); + callback(error, complete); + } + } catch (e) { + callback(e.toString()); + } + } + + getAvailableImages(mapId: string) { + let availableImages = this.availableImages[mapId]; + + if (!availableImages) { + availableImages = []; + } + + return availableImages; + } + + getLayerIndex(mapId: string) { + let layerIndexes = this.layerIndexes[mapId]; + if (!layerIndexes) { + layerIndexes = this.layerIndexes[mapId] = new StyleLayerIndex(); + } + return layerIndexes; + } + + getWorkerSource(mapId: string, type: string, source: string) { + if (!this.workerSources[mapId]) + this.workerSources[mapId] = {}; + if (!this.workerSources[mapId][type]) + this.workerSources[mapId][type] = {}; + + if (!this.workerSources[mapId][type][source]) { + // use a wrapped actor so that we can attach a target mapId param + // to any messages invoked by the WorkerSource + const actor = { + send: (type, data, callback) => { + this.actor.send(type, data, callback, mapId); + } + }; + this.workerSources[mapId][type][source] = new (this.workerSourceTypes[type]: any)((actor: any), this.getLayerIndex(mapId), this.getAvailableImages(mapId)); + } + + return this.workerSources[mapId][type][source]; + } + + getDEMWorkerSource(mapId: string, source: string) { + if (!this.demWorkerSources[mapId]) + this.demWorkerSources[mapId] = {}; + + if (!this.demWorkerSources[mapId][source]) { + this.demWorkerSources[mapId][source] = new RasterDEMTileWorkerSource(); + } + + return this.demWorkerSources[mapId][source]; + } + + enforceCacheSizeLimit(mapId: string, limit: number) { + enforceCacheSizeLimit(limit); + } +} + +/* global self, WorkerGlobalScope */ +if (typeof WorkerGlobalScope !== 'undefined' && + typeof self !== 'undefined' && + self instanceof WorkerGlobalScope) { + self.worker = new Worker(self); +} diff --git a/node_modules/mapbox-gl/src/source/worker_source.js b/node_modules/mapbox-gl/src/source/worker_source.js new file mode 100644 index 0000000000000000000000000000000000000000..c800049e3b36bc960e474ee7100a18dcc1effc93 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/worker_source.js @@ -0,0 +1,107 @@ +// @flow + +import type {RequestParameters} from '../util/ajax'; +import type {RGBAImage, AlphaImage} from '../util/image'; +import type {GlyphPositions} from '../render/glyph_atlas'; +import type ImageAtlas from '../render/image_atlas'; +import type {OverscaledTileID} from './tile_id'; +import type {Bucket} from '../data/bucket'; +import type FeatureIndex from '../data/feature_index'; +import type {CollisionBoxArray} from '../data/array_types'; +import type DEMData from '../data/dem_data'; +import type {StyleGlyph} from '../style/style_glyph'; +import type {StyleImage} from '../style/style_image'; +import type {PromoteIdSpecification} from '../style-spec/types'; +import window from '../util/window'; +const {ImageBitmap} = window; + +export type TileParameters = { + source: string, + uid: string, +}; + +export type WorkerTileParameters = TileParameters & { + tileID: OverscaledTileID, + request: RequestParameters, + zoom: number, + maxZoom: number, + tileSize: number, + promoteId: ?PromoteIdSpecification, + pixelRatio: number, + showCollisionBoxes: boolean, + collectResourceTiming?: boolean, + returnDependencies?: boolean +}; + +export type WorkerDEMTileParameters = TileParameters & { + coord: { z: number, x: number, y: number, w: number }, + rawImageData: RGBAImage | ImageBitmap, + encoding: "mapbox" | "terrarium" +}; + +export type WorkerTileResult = { + buckets: Array, + imageAtlas: ImageAtlas, + glyphAtlasImage: AlphaImage, + featureIndex: FeatureIndex, + collisionBoxArray: CollisionBoxArray, + rawTileData?: ArrayBuffer, + resourceTiming?: Array, + // Only used for benchmarking: + glyphMap?: {[_: string]: {[_: number]: ?StyleGlyph}} | null, + iconMap?: {[_: string]: StyleImage} | null, + glyphPositions?: GlyphPositions | null +}; + +export type WorkerTileCallback = (error: ?Error, result: ?WorkerTileResult) => void; +export type WorkerDEMTileCallback = (err: ?Error, result: ?DEMData) => void; + +/** + * May be implemented by custom source types to provide code that can be run on + * the WebWorkers. In addition to providing a custom + * {@link WorkerSource#loadTile}, any other methods attached to a `WorkerSource` + * implementation may also be targeted by the {@link Source} via + * `dispatcher.getActor().send('source-type.methodname', params, callback)`. + * + * @see {@link Map#addSourceType} + * @private + * + * @class WorkerSource + * @param actor + * @param layerIndex + */ +export interface WorkerSource { + availableImages: Array, + // Disabled due to https://github.com/facebook/flow/issues/5208 + // constructor(actor: Actor, layerIndex: StyleLayerIndex): WorkerSource; + + /** + * Loads a tile from the given params and parse it into buckets ready to send + * back to the main thread for rendering. Should call the callback with: + * `{ buckets, featureIndex, collisionIndex, rawTileData}`. + */ + loadTile(params: WorkerTileParameters, callback: WorkerTileCallback): void; + + /** + * Re-parses a tile that has already been loaded. Yields the same data as + * {@link WorkerSource#loadTile}. + */ + reloadTile(params: WorkerTileParameters, callback: WorkerTileCallback): void; + + /** + * Aborts loading a tile that is in progress. + */ + abortTile(params: TileParameters, callback: WorkerTileCallback): void; + + /** + * Removes this tile from any local caches. + */ + removeTile(params: TileParameters, callback: WorkerTileCallback): void; + + /** + * Tells the WorkerSource to abort in-progress tasks and release resources. + * The foreground Source is responsible for ensuring that 'removeSource' is + * the last message sent to the WorkerSource. + */ + removeSource?: (params: {source: string}, callback: WorkerTileCallback) => void; +} diff --git a/node_modules/mapbox-gl/src/source/worker_tile.js b/node_modules/mapbox-gl/src/source/worker_tile.js new file mode 100644 index 0000000000000000000000000000000000000000..fd5e8d5d502f84877002d488121e521733091263 --- /dev/null +++ b/node_modules/mapbox-gl/src/source/worker_tile.js @@ -0,0 +1,224 @@ +// @flow + +import FeatureIndex from '../data/feature_index'; + +import {performSymbolLayout} from '../symbol/symbol_layout'; +import {CollisionBoxArray} from '../data/array_types'; +import DictionaryCoder from '../util/dictionary_coder'; +import SymbolBucket from '../data/bucket/symbol_bucket'; +import LineBucket from '../data/bucket/line_bucket'; +import FillBucket from '../data/bucket/fill_bucket'; +import FillExtrusionBucket from '../data/bucket/fill_extrusion_bucket'; +import {warnOnce, mapObject, values} from '../util/util'; +import assert from 'assert'; +import ImageAtlas from '../render/image_atlas'; +import GlyphAtlas from '../render/glyph_atlas'; +import EvaluationParameters from '../style/evaluation_parameters'; +import {OverscaledTileID} from './tile_id'; + +import type {Bucket} from '../data/bucket'; +import type Actor from '../util/actor'; +import type StyleLayer from '../style/style_layer'; +import type StyleLayerIndex from '../style/style_layer_index'; +import type {StyleImage} from '../style/style_image'; +import type {StyleGlyph} from '../style/style_glyph'; +import type { + WorkerTileParameters, + WorkerTileCallback, +} from '../source/worker_source'; +import type {PromoteIdSpecification} from '../style-spec/types'; + +class WorkerTile { + tileID: OverscaledTileID; + uid: string; + zoom: number; + pixelRatio: number; + tileSize: number; + source: string; + promoteId: ?PromoteIdSpecification; + overscaling: number; + showCollisionBoxes: boolean; + collectResourceTiming: boolean; + returnDependencies: boolean; + + status: 'parsing' | 'done'; + data: VectorTile; + collisionBoxArray: CollisionBoxArray; + + abort: ?() => void; + reloadCallback: WorkerTileCallback; + vectorTile: VectorTile; + + constructor(params: WorkerTileParameters) { + this.tileID = new OverscaledTileID(params.tileID.overscaledZ, params.tileID.wrap, params.tileID.canonical.z, params.tileID.canonical.x, params.tileID.canonical.y); + this.uid = params.uid; + this.zoom = params.zoom; + this.pixelRatio = params.pixelRatio; + this.tileSize = params.tileSize; + this.source = params.source; + this.overscaling = this.tileID.overscaleFactor(); + this.showCollisionBoxes = params.showCollisionBoxes; + this.collectResourceTiming = !!params.collectResourceTiming; + this.returnDependencies = !!params.returnDependencies; + this.promoteId = params.promoteId; + } + + parse(data: VectorTile, layerIndex: StyleLayerIndex, availableImages: Array, actor: Actor, callback: WorkerTileCallback) { + this.status = 'parsing'; + this.data = data; + + this.collisionBoxArray = new CollisionBoxArray(); + const sourceLayerCoder = new DictionaryCoder(Object.keys(data.layers).sort()); + + const featureIndex = new FeatureIndex(this.tileID, this.promoteId); + featureIndex.bucketLayerIDs = []; + + const buckets: {[_: string]: Bucket} = {}; + + const options = { + featureIndex, + iconDependencies: {}, + patternDependencies: {}, + glyphDependencies: {}, + availableImages + }; + + const layerFamilies = layerIndex.familiesBySource[this.source]; + for (const sourceLayerId in layerFamilies) { + const sourceLayer = data.layers[sourceLayerId]; + if (!sourceLayer) { + continue; + } + + if (sourceLayer.version === 1) { + warnOnce(`Vector tile source "${this.source}" layer "${sourceLayerId}" ` + + `does not use vector tile spec v2 and therefore may have some rendering errors.`); + } + + const sourceLayerIndex = sourceLayerCoder.encode(sourceLayerId); + const features = []; + for (let index = 0; index < sourceLayer.length; index++) { + const feature = sourceLayer.feature(index); + const id = featureIndex.getId(feature, sourceLayerId); + features.push({feature, id, index, sourceLayerIndex}); + } + + for (const family of layerFamilies[sourceLayerId]) { + const layer = family[0]; + + assert(layer.source === this.source); + if (layer.minzoom && this.zoom < Math.floor(layer.minzoom)) continue; + if (layer.maxzoom && this.zoom >= layer.maxzoom) continue; + if (layer.visibility === 'none') continue; + + recalculateLayers(family, this.zoom, availableImages); + + const bucket = buckets[layer.id] = layer.createBucket({ + index: featureIndex.bucketLayerIDs.length, + layers: family, + zoom: this.zoom, + pixelRatio: this.pixelRatio, + overscaling: this.overscaling, + collisionBoxArray: this.collisionBoxArray, + sourceLayerIndex, + sourceID: this.source + }); + + bucket.populate(features, options, this.tileID.canonical); + featureIndex.bucketLayerIDs.push(family.map((l) => l.id)); + } + } + + let error: ?Error; + let glyphMap: ?{[_: string]: {[_: number]: ?StyleGlyph}}; + let iconMap: ?{[_: string]: StyleImage}; + let patternMap: ?{[_: string]: StyleImage}; + + const stacks = mapObject(options.glyphDependencies, (glyphs) => Object.keys(glyphs).map(Number)); + if (Object.keys(stacks).length) { + actor.send('getGlyphs', {uid: this.uid, stacks}, (err, result) => { + if (!error) { + error = err; + glyphMap = result; + maybePrepare.call(this); + } + }); + } else { + glyphMap = {}; + } + + const icons = Object.keys(options.iconDependencies); + if (icons.length) { + actor.send('getImages', {icons, source: this.source, tileID: this.tileID, type: 'icons'}, (err, result) => { + if (!error) { + error = err; + iconMap = result; + maybePrepare.call(this); + } + }); + } else { + iconMap = {}; + } + + const patterns = Object.keys(options.patternDependencies); + if (patterns.length) { + actor.send('getImages', {icons: patterns, source: this.source, tileID: this.tileID, type: 'patterns'}, (err, result) => { + if (!error) { + error = err; + patternMap = result; + maybePrepare.call(this); + } + }); + } else { + patternMap = {}; + } + + maybePrepare.call(this); + + function maybePrepare() { + if (error) { + return callback(error); + } else if (glyphMap && iconMap && patternMap) { + const glyphAtlas = new GlyphAtlas(glyphMap); + const imageAtlas = new ImageAtlas(iconMap, patternMap); + + for (const key in buckets) { + const bucket = buckets[key]; + if (bucket instanceof SymbolBucket) { + recalculateLayers(bucket.layers, this.zoom, availableImages); + performSymbolLayout(bucket, glyphMap, glyphAtlas.positions, iconMap, imageAtlas.iconPositions, this.showCollisionBoxes, this.tileID.canonical); + } else if (bucket.hasPattern && + (bucket instanceof LineBucket || + bucket instanceof FillBucket || + bucket instanceof FillExtrusionBucket)) { + recalculateLayers(bucket.layers, this.zoom, availableImages); + bucket.addFeatures(options, this.tileID.canonical, imageAtlas.patternPositions); + } + } + + this.status = 'done'; + callback(null, { + buckets: values(buckets).filter(b => !b.isEmpty()), + featureIndex, + collisionBoxArray: this.collisionBoxArray, + glyphAtlasImage: glyphAtlas.image, + imageAtlas, + // Only used for benchmarking: + glyphMap: this.returnDependencies ? glyphMap : null, + iconMap: this.returnDependencies ? iconMap : null, + glyphPositions: this.returnDependencies ? glyphAtlas.positions : null + }); + } + } + } +} + +function recalculateLayers(layers: $ReadOnlyArray, zoom: number, availableImages: Array) { + // Layers are shared and may have been used by a WorkerTile with a different zoom. + const parameters = new EvaluationParameters(zoom); + for (const layer of layers) { + layer.recalculate(parameters, availableImages); + } +} + +export default WorkerTile; diff --git a/node_modules/mapbox-gl/src/style-spec/.eslintrc b/node_modules/mapbox-gl/src/style-spec/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..f3fdb51db757b801c913dc837c2d41ebd3357c95 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/.eslintrc @@ -0,0 +1,5 @@ +{ + "rules": { + "flowtype/require-valid-file-annotation": [0] + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/CHANGELOG.md b/node_modules/mapbox-gl/src/style-spec/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..f3ab3d7ef2bb98f3c9d7b207b8a593c0f91fe7f9 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/CHANGELOG.md @@ -0,0 +1,468 @@ +## 13.17.0 + +### ✨ Features and improvements +* Add a `filter` option for GeoJSON sources to filter out features prior to processing (e.g. before clustering). [#9864](https://github.com/mapbox/mapbox-gl-js/pull/9864) + +## 13.16.0 + +### ✨ Features and improvements +* Added `volatile` source property to control storing the tiles in local storage. ([9702](https://github.com/mapbox/mapbox-gl-js/pull/9702)) + +* Added `clusterMinPoints` option for clustered GeoJSON sources that defines the minimum number of points to form a cluster. ([#9748](https://github.com/mapbox/mapbox-gl-js/pull/9748)) + +## 13.15.0 + +### ✨ Features and improvements +* Add `distance` expression to `style-spec`. This expression returns the shortest distance between a feature and an input geometry ([#9655](https://github.com/mapbox/mapbox-gl-js/pull/9655)) + +## 13.14.0 + +### ✨ Features and improvements +* Add `index-of` and `slice` expressions to search arrays and strings for the first occurrence of a specified value and return a section of the original array or string ([#9450](https://github.com/mapbox/mapbox-gl-js/pull/9450)) (h/t [lbutler](https://github.com/lbutler)) + +## 13.13.1 + +### ✨ Features and improvements +* Expose `expression.isExpressionFilter(..)` from the bundle. ([#9530](https://github.com/mapbox/mapbox-gl-js/pull/9530)) + +### 🐛 Bug fixes +* Fix a broken module import where the `style-spec` package was importing files from `mapbox-gl-js`, it's parent repo, causing downstream build systems to break. ([#9522](https://github.com/mapbox/mapbox-gl-js/pull/9522)) + +## 13.13.0 + +### ✨ Features and improvements +* Add `within` expression for testing whether an evaluated feature lies within a given GeoJSON object ([#9352](https://github.com/mapbox/mapbox-gl-js/pull/9352)). For example:
+`"icon-opacity": ["case", ["==", ["within", "some-polygon"], true], 1, +["==", ["within", "some-polygon"], false], 0]` +* Improve scaling of patterns used in `line-pattern` on all device resolutions and pixel ratios ([#9266](https://github.com/mapbox/mapbox-gl-js/pull/9266)) + +### 🐛 Bug fixes +* Allow needle argument to `in` expression to be false ([#9295](https://github.com/mapbox/mapbox-gl-js/pull/9295)) +* Fix a bug where `icon-image` expression that evaluates to an empty string (`''`) produced a warning ([#9380](https://github.com/mapbox/mapbox-gl-js/pull/9380)) +* Prevent exception resulting from `line-dash-array` of empty length ([#9385](https://github.com/mapbox/mapbox-gl-js/pull/9385)) + +## 13.12.0 + +* Update `image` expression SDK support table ([#9228](https://github.com/mapbox/mapbox-gl-js/pull/9228)) +* Fix `promoteId` for line layers ([#9210](https://github.com/mapbox/mapbox-gl-js/pull/9210), [#9212](https://github.com/mapbox/mapbox-gl-js/pull/9212)) + +## 13.11.0 + +### ✨ Features and improvements +* Add `promoteId` option to use a feature property as ID for feature state ([#8987](https://github.com/mapbox/mapbox-gl-js/pull/8987)) +* Update `symbol-avoid-edges` documentation regarding global collision detection ([#9157](https://github.com/mapbox/mapbox-gl-js/pull/9157)) +* Remove reference to `in` function which has been replaced by the `in` expression ([#9102](https://github.com/mapbox/mapbox-gl-js/pull/9102)) + +### 🐛 Bug fixes +* Fix bug where `symbol-sort-key` was not used for collisions that crossed tile boundaries ([#9054](https://github.com/mapbox/mapbox-gl-js/pull/9054)) + +## 13.10.2 + +### 🐛 Bug fixes +* Fix style validation error messages not being displayed ([#9073](https://github.com/mapbox/mapbox-gl-js/pull/9073)) + +## 13.10.0 + +### ✨ Features and improvements +* Add ability to insert images into text labels using an `image` expression within a `format` expression: `"text-field": ["format", "Some text", ["image", "my-image"], "some more text"]` ([#8904](https://github.com/mapbox/mapbox-gl-js/pull/8904)) +* Add `in` expression. It can check if a value is in an array (`["in", value, array]`) or a substring is in a string (`["in", substring, string]`) ([#8876](https://github.com/mapbox/mapbox-gl-js/pull/8876)) +* Add support for stretchable images (aka nine-part or nine-patch images). Stretchable images can be used with `icon-text-fit` to draw resized images with unstretched corners and borders. ([#8997](https://github.com/mapbox/mapbox-gl-js/pull/8997)) +* Add an es modules build of for mapbox-gl-style-spec in dist/ ([#8247](https://github.com/mapbox/mapbox-gl-js/pull/8247)) (h/t [ahocevar](https://github.com/ahocevar)) + +## 13.9.1 + +### ✨ Improvement +* Rename `Image` type to `ResolvedImage`, to better represent the result of an `image` expression evaluation. ([#8901](https://github.com/mapbox/mapbox-gl-js/pull/8901)) + +## 13.9.0 + +* Add `image` expression operator to determine image availability ([#8684](https://github.com/mapbox/mapbox-gl-js/pull/8684)) +* Add a style-spec function to validate that styles are compatible with the Mapbox API ([#8663](https://github.com/mapbox/mapbox-gl-js/pull/8663)) + +## 13.8.0 + +- Introduce `text-writing-mode` symbol layer property to allow placing point labels vertically. [#8399](https://github.com/mapbox/mapbox-gl-js/pull/8399) +- Allow `text-color` to be used in formatted expressions to be able to draw different parts of a label in different colors. [#8068](https://github.com/mapbox/mapbox-gl-js/pull/8068) +- Improve conversion of legacy filters with duplicate values. [#8542](https://github.com/mapbox/mapbox-gl-js/pull/8542) + +## 13.7.2 + +### 🐛 Bug fixes +* Fix SDK support spec section for variable label placement ([#8384](https://github.com/mapbox/mapbox-gl-js/pull/8384)) (h/t [@pozdnyakov](https://github.com/pozdnyakov)) + +### ✨ Features and improvements +* Add SDK support spec section for text-radial-offset ([#8401](https://github.com/mapbox/mapbox-gl-js/pull/8401)) +* Add `*-sort-key` layout property for circle, fill, line ([#8467](https://github.com/mapbox/mapbox-gl-js/pull/8467)) +* Expose convertFilter API in the style specification ([#8493](https://github.com/mapbox/mapbox-gl-js/pull/8493)) + +## 13.7.1 + +### 🐛 Bug fixes +* Fix format expression options validation ([#8339](https://github.com/mapbox/mapbox-gl-js/pull/8339)) +* Fix SDK support information for style properties added in v13.7.0: ([#8384](https://github.com/mapbox/mapbox-gl-js/pull/8384)) + * Add missing SDK support section for `text-radial-offset` property + * Assign SDK versions for `text-variable-anchor` and `text-justify: auto` + +## 13.7.0 + +### ✨ Features and improvements +* Add `text-radial-offset` style property ([#7596](https://github.com/mapbox/mapbox-gl-js/pull/7596)) +* Add `text-variable-anchor` style property ([#7596](https://github.com/mapbox/mapbox-gl-js/pull/7596)) +* Add `auto` value to `text-justify` style property ([#7596](https://github.com/mapbox/mapbox-gl-js/pull/7596)) + +## 13.6.0 + +### ✨ Features and improvements +* Add `clusterProperties` option for aggregated cluster properties ([#2412](https://github.com/mapbox/mapbox-gl-js/issues/2412), fixed by [#7584](https://github.com/mapbox/mapbox-gl-js/pull/7584)) +* Add `number-format` expression ([#7626](https://github.com/mapbox/mapbox-gl-js/pull/7626)) +* Add `symbol-sort-key` style property ([#7678](https://github.com/mapbox/mapbox-gl-js/pull/7678)) + +## 13.5.0 + +### Features and improvements +* Flattens `all` expressions in converted filters ([#7679](https://github.com/mapbox/mapbox-gl-js/pull/7679)) +* Compatibility tables are updated ([#7574](https://github.com/mapbox/mapbox-gl-js/pull/7574)) + +## 13.4.0 + +### ✨ Features and improvements +* **Tighten style validation** + * Disallow expressions as stop values ([#7396](https://github.com/mapbox/mapbox-gl-js/pull/7396)) + * Disallow `feature-state` expressions in filters ([#7366](https://github.com/mapbox/mapbox-gl-js/pull/7366)) + +## 13.3.0 + +### 🐛 Bug fixes +* **Expressions** + * Fix `let` expression stripping expected type during parsing ([#7300](https://github.com/mapbox/mapbox-gl-js/issues/7300), fixed by [#7301](https://github.com/mapbox/mapbox-gl-js/pull/7301)) + * Fix superfluous wrapping of literals in `literal` expression ([#7336](https://github.com/mapbox/mapbox-gl-js/issues/7336), fixed by [#7337](https://github.com/mapbox/mapbox-gl-js/pull/7337)) + * Allow calling `to-color` on values that are already of type `Color` ([#7260](https://github.com/mapbox/mapbox-gl-js/pull/7260)) + * Fix `to-array` for empty arrays (([#7261](https://github.com/mapbox/mapbox-gl-js/pull/7261))) + * Fix identity functions for `text-field` when using formatted text ([#7351](https://github.com/mapbox/mapbox-gl-js/pull/7351)) + * Fix coercion of `null` to `0` in `to-number` expression ([#7083](https://github.com/mapbox/mapbox-gl-js/issues/7083), fixed by [#7274](https://github.com/mapbox/mapbox-gl-js/pull/7274)) + +### ✨ Features and improvements +* Add `fill-extrusion-vertical-gradient` property for controlling shading of fill extrusions ([#5768](https://github.com/mapbox/mapbox-gl-js/issues/5768), fixed by [#6841](https://github.com/mapbox/mapbox-gl-js/pull/6841)) + +## 13.2.0 + +### 🐛 Bug fixes +* Update the style-spec's old `gl-style-migrate` script to include conversion of legacy functions and filters to their expression equivalents ([#6927](https://github.com/mapbox/mapbox-gl-js/issues/6927), fixed by [#7095](https://github.com/mapbox/mapbox-gl-js/pull/7095)) + +### ✨ Features and improvements +* Add `symbol-z-order` symbol layout property to style spec ([#7219](https://github.com/mapbox/mapbox-gl-js/pull/7219)) +* Implement data-driven styling support for `*-pattern properties` ([#6289](https://github.com/mapbox/mapbox-gl-js/pull/6289)) + +## 13.1.1 + +### 🐛 Bug fixes +* Fix broken module import in mapboxgl-style-spec (v13.0.1) ([#6984](https://github.com/mapbox/mapbox-gl-js/issues/6984), fixed by [#6997](https://api.github.com/repos/mapbox/mapbox-gl-js/pulls/6997)) + +### ✨ Features and improvements +* Improve formatting for style output ([#7029](https://github.com/mapbox/mapbox-gl-js/pull/7029)) + +## 13.1.0 + +### ✨ Features and improvements +* Add `raster-resampling` raster paint property ([#6411](https://github.com/mapbox/mapbox-gl-js/pull/6411)) (h/t [andrewharvey](https://github.com/andrewharvey)) +* Add `symbol-placement: line-center` ([#6821](https://github.com/mapbox/mapbox-gl-js/pull/6821)) + +## 13.0.1 + +### ⚠️ Breaking changes +* Align implicit type behavior of `match` expressions with with `case/==` ([#6684](https://github.com/mapbox/mapbox-gl-js/pull/6684)) +* Update spec so that documentation can automatically capture which functions and expressions can be used with which properties ([#6521](https://github.com/mapbox/mapbox-gl-js/pull/6521)) + +### ✨ Features and improvements +* Add `feature-state` [#6263](https://github.com/mapbox/mapbox-gl-js/pull/6263) +* Add support for GeoJSON attribution ([#6364](https://github.com/mapbox/mapbox-gl-js/pull/6364)) (h/t [andrewharvey](https://github.com/andrewharvey)) +* Upgrade to Flow 0.69 ([#6594](https://github.com/mapbox/mapbox-gl-js/pull/6594)) + +### 🐛 Bug fixes +* Use named exports for style-spec entrypoint module ([#6601](https://github.com/mapbox/mapbox-gl-js/issues/6601) + +## 13.0.0 +Malformed package published to NPM. + +## 12.0.0 + +### ⚠️ Breaking changes +* The `"to-string"` expression operator now converts null to an empty string rather than to `"null"`. [#6534](https://github.com/mapbox/mapbox-gl-js/pull/6534) + +### ✨ Features and improvements +* 🌈 Add line-gradient property [#6303](https://github.com/mapbox/mapbox-gl-js/pull/6303) +* Add collator expression for controlling case and diacritic sensitivity in string comparisons [#6270](https://github.com/mapbox/mapbox-gl-js/pull/6270) +* Add `is-supported-script` expression for determining if a script is supported. [#6260](https://github.com/mapbox/mapbox-gl-js/pull/6260) +* Add `collator` expression for controlling case and diacritic sensitivity in string comparisons [#6270](https://github.com/mapbox/mapbox-gl-js/pull/6270) +* Add `abs`, `round`, `floor`, and `ceil` expression operators [#6496](https://github.com/mapbox/mapbox-gl-js/pull/6496) +* Add support for Mapzen Terrarium tiles in raster-dem sources [#6110](https://github.com/mapbox/mapbox-gl-js/pull/6110) + +### 🐛 Bug fixes +- Fix Rollup build [6575](https://github.com/mapbox/mapbox-gl-js/pull/6575) + +## 11.1.1 + +### 🐛 Bug fixes + +* Update SDK support information for `text-font`, and `heatmap-color`, and `hillshade` layer properties. + +## 11.1.0 + +### ✨ Features and improvements + +* Avoid use of `new Function` for filters by converting old-style filters to expressions [#5665](https://github.com/mapbox/mapbox-gl-js/pull/5665). + +## 11.0.0 + +### ⚠️ Breaking changes + +* Remove constants validating code [#5885](https://github.com/mapbox/mapbox-gl-js/pull/5885) +* `"colorSpace": "hcl"` now uses shortest-path interpolation for hue [#5811](https://github.com/mapbox/mapbox-gl-js/issues/5811) + +### ✨ Features and improvements + +* Introduce client-side hillshading with `raster-dem` source type and `hillshade` layer type [#5286](https://github.com/mapbox/mapbox-gl-js/pull/5286) +* Add Color#toString and expose Color publicly [#5866](https://github.com/mapbox/mapbox-gl-js/pull/5866) +* Improve typing for `==` and `!=` expressions [#5840](https://github.com/mapbox/mapbox-gl-js/pull/5840) +* Made `coalesce` expressions more useful [#5755](https://github.com/mapbox/mapbox-gl-js/issues/5755) +* Enable implicit type assertions for array types [#5738](https://github.com/mapbox/mapbox-gl-js/pull/5738) + +### 🐛 Bug fixes + +* Fix standalone browser build [#5736](https://github.com/mapbox/mapbox-gl-js/pull/5736), [#5906](https://github.com/mapbox/mapbox-gl-js/pull/5906) +* Handle NaN as input to step and interpolate expressions [#5757](https://github.com/mapbox/mapbox-gl-js/pull/5757) +* Fix style diffing for changes to GeoJSON sources [#5745](https://github.com/mapbox/mapbox-gl-js/pull/5745) +* Mark layer "type" property as required [#5849](https://github.com/mapbox/mapbox-gl-js/pull/5849) + +## 10.1.0 + +* Remove support for validating and migrating v6 styles [#5604](https://github.com/mapbox/mapbox-gl-js/pull/5604) +* Remove support for validating v7 styles [#5604](https://github.com/mapbox/mapbox-gl-js/pull/5604) +* Remove spaces after commas in `to-string` representation of colors [#5480](https://github.com/mapbox/mapbox-gl-js/pull/5480) +* Fix bugs preventing `mapbox-gl-style-spec` package on NPM from being used externally [#5502](https://github.com/mapbox/mapbox-gl-js/pull/5502) +* Fix flow-typed interface generator [#5478](https://github.com/mapbox/mapbox-gl-js/pull/5478) +* Export `function` [#5584](https://github.com/mapbox/mapbox-gl-js/pull/5584) +* Export `StylePropertySpecification` type [#5593](https://github.com/mapbox/mapbox-gl-js/pull/5593) +* Split the `source_tile` entry in the JSON schema into `source_vector` and `source_raster` [#5604](https://github.com/mapbox/mapbox-gl-js/pull/5604) + +### Validation Changes + +* Require that `heatmap-color` use expressions instead of stop functions [#5624](https://github.com/mapbox/mapbox-gl-js/issues/5624) +* Remove support for including `{tokens}` in expressions for `text-field` and `icon-image` [#5599](https://github.com/mapbox/mapbox-gl-js/issues/5599) +* Disallow interpolation in expressions for `line-dasharray` [#5519](https://github.com/mapbox/mapbox-gl-js/pull/5519) +* Validate that zoom expressions only appear at the top level of an expression [#5609](https://github.com/mapbox/mapbox-gl-js/issues/5609) +* Validate that `step` and `interpolate` expressions don't have any duplicate stops [#5605](https://github.com/mapbox/mapbox-gl-js/issues/5605) +* Split `curve` expression into `step` and `interpolate` expressions [#5542](https://github.com/mapbox/mapbox-gl-js/pull/5542) +* Validate expression values for enum-typed properties [#5589](https://github.com/mapbox/mapbox-gl-js/pull/5589) +* Improve validation to catch uses of deprecated function syntax [#5667](https://github.com/mapbox/mapbox-gl-js/pull/5667) + +## 10.0.1 + +* Fix bug preventing @mapbox/mapbox-gl-style-spec package from being usable outside of mapbox-gl-js (#5502) + +## 10.0.0 + +* Add expression and heatmap layer support. See Mapbox GL JS v0.40.1 changelog entry for details. + +## 9.0.1 + +* Remove `fast-stable-stringify` dependency (#5152) + +## 9.0.0 + +* Fix validation error on categorical zoom-and-property functions (#4220) +* Relax requirement that styles using "icon-image" must have a "sprite" +* Prevent infinite loop in binarySearchForIndex when duplicate stops are present. (#4503) +* Ensure generated composite function stops are in the correct order (#4509) +* Update SDK support matrices to be current as of GL JS v0.35.1, iOS SDK v3.5.0, Android SDK 5.0.0 +* Remove support for implicitly-categorical functions +* BREAKING CHANGE: the API for the `function` module has changed. The `interpolated` and `piecewise-constant` exports +were replaced with a single unnamed export, a function which accepts an object conforming to the style spec "function" +definition, and an object defining a style spec property. It handles color parsing and validation of feature values +internally. +* Functions now support a "default" property. +* `parseColor` was promoted from gl-js. + +## 8.11.0 + +* Merge `feature-filter` repository into this repository #639 + +## 8.10.0 + +v8.0.0 styles are fully compatible with v8.10.0. + +### Style Specification Changes + +* Added `colorSpace` option to functions +* Added `fill-extrusion` layer type +* Add top-level `light` property +* Remove increase maximum `maxzoom` to 24 +* Deprecate paint classes :warning: +* Increase strictness of function validation + +### Reference JSON & API Changes + +* Added `deref` utility +* Added `group_by_layout` utility +* Merge `mapbox-gl-function` repository into this repository + +## 8.9.0 + +v8.0.0 styles are fully compatible with v8.9.0. + +* Added identity functions +* Added `auto` value which represents the calculated default value + +## 8.8.1 + +v8.0.0 styles are fully compatible with v8.8.1. + +* Fixed style validation for layers with invalid types + +## 8.8.0 + +v8.0.0 styles are fully compatible with v8.8.0. + +* Clarified documentation around fill-opacity. +* Update function documentation and validation for property functions. +* Add text-pitch-alignment property. +* Add icon-text-fit, icon-text-fit-padding properties. + +## 8.7.0 + +v8.0.0 styles are fully compatible with v8.7.0. + +* Add support for has / !has operators. + +## 8.6.0 + +v8.0.0 styles are fully compatible with v8.6.0. + +* Added support for zoom and feature driven functions. + +## 8.4.2 + +v8.0.0 styles are fully compatible with v8.4.2. + +* Refactored style validator to expose more granular validation methods + +## 8.4.1 + +v8.0.0 styles are fully compatible with v8.4.1. + +* Revert ramp validation checks that broke some styles. + +## 8.4.0 + +v8.0.0 styles are fully compatible with v8.4.0. + +* Added `cluster`, `clusterRadius`, `clusterMaxZoom` GeoJSON source properties. + +## 8.3.0 + +v8.0.0 styles are fully compatible with v8.3.0. + +* Added `line-offset` style property + +## 8.2.1 + +v8.0.0 styles are fully compatible with v8.2.1. + +* Enforce that all layers that use a vector source specify a "source-layer" + +## 8.2.0 + +v8.0.0 styles are fully compatible with v8.2.0. + +* Add inline `example` property. +* Enforce that all style properties must have documentation in `doc` property. +* Create minified style specs with `doc` and `example` properties removed. +* `validate` now validates against minified style spec. +* `format` now accepts `space` option to use with `JSON.stringify`. +* Remove `gl-style-spritify`. Mapbox GL sprites are now created automatically by + the Mapbox style APIs, or for hand-crafted styles, by [spritezero-cli](https://github.com/mapbox/spritezero-cli). + +## 8.1.0 + +v8.0.0 styles are fully compatible with v8.1.0. + +* [BREAKING] Simplified layout/paint layer property types to more closely align + with v7 types. +* Fixed migration script compatibility with newer versions of Node.js and io.js +* Removed `constants` from schema, they were deprecated in v8 +* Added style diff utility to generate semantic deltas between two stylesheets +* Added `visibility` property to `circle` layer type +* Added `pitch` property to stylesheet + +## 8.0.0 + +Introduction of Mapbox GL style specification v8. To migrate a v7 style to v8, +use the `gl-style-migrate` script as described in the README. + +* [BREAKING] The value of the `text-font` property is now an array of + strings, rather than a single comma separated string. +* [BREAKING] Renamed `symbol-min-distance` to `symbol-spacing`. +* [BREAKING] Renamed `background-image` to `background-pattern`. +* [BREAKING] Renamed `line-image` to `line-pattern`. +* [BREAKING] Renamed `fill-image` to `fill-pattern`. +* [BREAKING] Renamed the `url` property of the video source type to `urls`. +* [BREAKING] Coordinates in video sources are now specified in [lon, lat] order. +* [BREAKING] Removed `text-max-size` and `icon-max-size` properties; these + are now calculated automatically. +* [BREAKING] `text-size` and `icon-size` are now layout properties instead of paint properties. +* [BREAKING] Constants are no longer supported. If you are editing styles by + hand and want to use constants, you can use a preprocessing step with a tool + like [ScreeSS](https://github.com/screee/screess). +* [BREAKING] The format for `mapbox://` glyphs URLs has changed; you should + now use `mapbox://fonts/mapbox/{fontstack}/{range}.pbf`. +* [BREAKING] Reversed the priority of layers for calculating label placement: + labels for layers that appear later in the style now have priority over earlier + layers. +* Added a new `image` source type. +* Added a new `circle` layer type. +* Default map center location can now be set in the style. +* Added `mapbox://` sprite URLs `mapbox://sprite/{user | "mapbox"}/{id}` + +## 7.5.0 + +* Added gl-style-composite script, for auto-compositing sources in a style. + +## 7.4.1 + +* Use JSON.stringify for formatting instead of js-beautify + +## 7.0.0 + +Introduction of Mapbox GL style specification v7. + +* [BREAKING] Improve dashed lines (#234) +* [BREAKING] Remove prerendered layers (#232) +* Explicit visibility property (#212) +* Functions for all properties (#237) + +## 6.0.0 (Style spec v6) + +Introduction of Mapbox GL style specification v6. + +* [BREAKING] New filter syntax (#178) +* [BREAKING] Line gap property (#131) +* [BREAKING] Remove dashes from min/max-zoom (#175) +* [BREAKING] New layout/paint terminology (#166) +* [BREAKING] Single text positioning property (#197) +* Added requirements (#200) +* Added minimum, maximum, and period values (#198) + +## 0.0.5 (in progress) + +* [BREAKING] Switch to suffix for transition properties (`transition-*` -> `*-transition`). +* Added support for remote, non-Mapbox TileJSON sources. +* [BREAKING] Source `minZoom` and `maxZoom` renamed to `minzoom` and `maxzoom to match TileJSON. +* Added support for `mapbox://` glyph URLs. +* [BREAKING] Renamed `raster-fade` to `raster-fade-duration`. +* Added background-opacity property. +* Added "tokens" property to string values that can autocomplete fields from layers +* Added "units" property to describe value types + +## 0.0.4 (Aug 8 2014) + +* Initial public release diff --git a/node_modules/mapbox-gl/src/style-spec/README.md b/node_modules/mapbox-gl/src/style-spec/README.md new file mode 100644 index 0000000000000000000000000000000000000000..412e68485139f6fc01e16d39261d6ff1bca6339c --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/README.md @@ -0,0 +1,59 @@ +# Mapbox GL style specification & utilities + +This directory contains code and reference files that define the Mapbox GL style specification and provides some utilities for working with Mapbox styles. + +## npm package + +The Mapbox GL style specification and utilities are published as a seperate npm +package so that they can be installed without the bulk of GL JS. + + npm install @mapbox/mapbox-gl-style-spec + +## CLI Tools + +If you install this package globally, you will have access to several CLI tools. + + npm install @mapbox/mapbox-gl-style-spec --global + + +### `gl-style-composite` +```bash +$ gl-style-composite style.json +``` + +Will take a non-composited style and produce a [composite style](https://www.mapbox.com/blog/better-label-placement-in-mapbox-studio/). + +### `gl-style-migrate` + +This repo contains scripts for migrating GL styles of any version to the latest version +(currently v8). Migrate a style like this: + +```bash +$ gl-style-migrate bright-v7.json > bright-v8.json +``` + +To migrate a file in place, you can use the `sponge` utility from the `moreutils` package: + +```bash +$ brew install moreutils +$ gl-style-migrate bright.json | sponge bright.json +``` + +### `gl-style-format` + +```bash +$ gl-style-format style.json +``` + +Will format the given style JSON to use standard indentation and sorted object keys. + +### `gl-style-validate` + +```bash +$ gl-style-validate style.json +``` + +Will validate the given style JSON and print errors to stdout. Provide a +`--json` flag to get JSON output. + +To validate that a style can be uploaded to the Mapbox Styles API, use the `--mapbox-api-supported` flag. diff --git a/node_modules/mapbox-gl/src/style-spec/bin/gl-style-composite b/node_modules/mapbox-gl/src/style-spec/bin/gl-style-composite new file mode 100644 index 0000000000000000000000000000000000000000..ed9bdbc8640417f281f5ebeae4a7ccf706041147 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/bin/gl-style-composite @@ -0,0 +1,9 @@ +#!/usr/bin/env node + + +var fs = require('fs'), + argv = require('minimist')(process.argv.slice(2)), + format = require('../').format, + composite = require('../').composite; + +console.log(format(composite(JSON.parse(fs.readFileSync(argv._[0]))))); diff --git a/node_modules/mapbox-gl/src/style-spec/bin/gl-style-format b/node_modules/mapbox-gl/src/style-spec/bin/gl-style-format new file mode 100644 index 0000000000000000000000000000000000000000..96da14b5ffd26f5593c64d860ccd0a1be69eed3f --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/bin/gl-style-format @@ -0,0 +1,22 @@ +#!/usr/bin/env node + + +var fs = require('fs'), + argv = require('minimist')(process.argv.slice(2)), + format = require('../').format; + +if (argv.help || argv.h || (!argv._.length && process.stdin.isTTY)) { + return help(); +} + +console.log(format(JSON.parse(fs.readFileSync(argv._[0])), argv.space)); + +function help() { + console.log('usage:'); + console.log(' gl-style-format source.json > destination.json'); + console.log(''); + console.log('options:'); + console.log(' --space '); + console.log(' Number of spaces in output (default "2")'); + console.log(' Pass "0" for minified output.'); +} diff --git a/node_modules/mapbox-gl/src/style-spec/bin/gl-style-migrate b/node_modules/mapbox-gl/src/style-spec/bin/gl-style-migrate new file mode 100644 index 0000000000000000000000000000000000000000..0fdb3e5a6ed410fdd77453da7885a8445e99a52a --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/bin/gl-style-migrate @@ -0,0 +1,9 @@ +#!/usr/bin/env node + + +var fs = require('fs'), + argv = require('minimist')(process.argv.slice(2)), + format = require('../').format, + migrate = require('../').migrate; + +console.log(format(migrate(JSON.parse(fs.readFileSync(argv._[0]))))); diff --git a/node_modules/mapbox-gl/src/style-spec/bin/gl-style-validate b/node_modules/mapbox-gl/src/style-spec/bin/gl-style-validate new file mode 100644 index 0000000000000000000000000000000000000000..a112d65d133fb348b0c36198ac635d25ff633950 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/bin/gl-style-validate @@ -0,0 +1,50 @@ +#!/usr/bin/env node + + +var argv = require('minimist')(process.argv.slice(2), { + boolean: 'json', + boolean: 'mapbox-api-supported' + }), + validate = require('../').validate, + validateMapboxApiSupported = require('../').validateMapboxApiSupported + rw = require('rw'), + status = 0; + +if (argv.help || argv.h || (!argv._.length && process.stdin.isTTY)) { + return help(); +} + +if (!argv._.length) { + argv._.push('/dev/stdin'); +} + +argv._.forEach(function(file) { + var errors; + if (argv['mapbox-api-supported']) { + errors = validateMapboxApiSupported(rw.readFileSync(file, 'utf8')); + } else { + errors = validate(rw.readFileSync(file, 'utf8')); + } + if (errors.length) { + if (argv.json) { + process.stdout.write(JSON.stringify(errors, null, 2)); + } else { + errors.forEach(function (e) { + console.log('%s:%d: %s', file, e.line, e.message); + }); + } + status = 1; + } +}); + +process.exit(status); + +function help() { + console.log('usage:'); + console.log(' gl-style-validate file.json'); + console.log(' gl-style-validate < file.json'); + console.log(''); + console.log('options:'); + console.log('--json output errors as json'); + console.log('--mapbox-api-supported validate compatibility with Mapbox Styles API'); +} diff --git a/node_modules/mapbox-gl/src/style-spec/composite.js b/node_modules/mapbox-gl/src/style-spec/composite.js new file mode 100644 index 0000000000000000000000000000000000000000..b9858126a1524156120ad51e7b68a51b901ea809 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/composite.js @@ -0,0 +1,50 @@ + +export default function (style) { + const styleIDs = []; + const sourceIDs = []; + const compositedSourceLayers = []; + + for (const id in style.sources) { + const source = style.sources[id]; + + if (source.type !== "vector") + continue; + + const match = /^mapbox:\/\/(.*)/.exec(source.url); + if (!match) + continue; + + styleIDs.push(id); + sourceIDs.push(match[1]); + } + + if (styleIDs.length < 2) + return style; + + styleIDs.forEach((id) => { + delete style.sources[id]; + }); + + const compositeID = sourceIDs.join(","); + + style.sources[compositeID] = { + "type": "vector", + "url": `mapbox://${compositeID}` + }; + + style.layers.forEach((layer) => { + if (styleIDs.indexOf(layer.source) >= 0) { + layer.source = compositeID; + + if ('source-layer' in layer) { + if (compositedSourceLayers.indexOf(layer['source-layer']) >= 0) { + throw new Error('Conflicting source layer names'); + } else { + compositedSourceLayers.push(layer['source-layer']); + } + } + } + }); + + return style; +} diff --git a/node_modules/mapbox-gl/src/style-spec/declass.js b/node_modules/mapbox-gl/src/style-spec/declass.js new file mode 100644 index 0000000000000000000000000000000000000000..8d2140f99face79b7e4ba0ea2fd720a9bcb24311 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/declass.js @@ -0,0 +1,42 @@ + +import extend from './util/extend'; + +export default declassStyle; + +/** + * Returns a new style with the given 'paint classes' merged into each layer's + * main `paint` definiton, and with all `paint.*` properties removed. + * + * @private + * @param {Object} style A style JSON object. + * @param {Array} classes An array of paint classes to apply, in order. + * + * @example + * var declass = require('mapbox-gl-style-spec/lib/declass') + * var baseStyle = { ... style with a 'paint.night' property in some layers ... } + * var nightStyle = declass(baseStyle, ['night']) + * // nightStyle now has each layer's `paint.night` properties merged in to the + * // main `paint` property. + */ +function declassStyle(style, classes) { + return extend({}, style, { + layers: style.layers.map((layer) => { + const result = classes.reduce(declassLayer, layer); + + // strip away all `paint.CLASS` definitions + for (const key in result) { + if (/paint\..*/.test(key)) { + delete result[key]; + } + } + + return result; + }) + }); +} + +function declassLayer(layer, klass) { + return extend({}, layer, { + paint: extend({}, layer.paint, layer[`paint.${klass}`]) + }); +} diff --git a/node_modules/mapbox-gl/src/style-spec/deref.js b/node_modules/mapbox-gl/src/style-spec/deref.js new file mode 100644 index 0000000000000000000000000000000000000000..729c9c923fa4ce583944897138779ac63c8f343f --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/deref.js @@ -0,0 +1,52 @@ + +import refProperties from './util/ref_properties'; + +function deref(layer, parent) { + const result = {}; + + for (const k in layer) { + if (k !== 'ref') { + result[k] = layer[k]; + } + } + + refProperties.forEach((k) => { + if (k in parent) { + result[k] = parent[k]; + } + }); + + return result; +} + +export default derefLayers; + +/** + * Given an array of layers, some of which may contain `ref` properties + * whose value is the `id` of another property, return a new array where + * such layers have been augmented with the 'type', 'source', etc. properties + * from the parent layer, and the `ref` property has been removed. + * + * The input is not modified. The output may contain references to portions + * of the input. + * + * @private + * @param {Array} layers + * @returns {Array} + */ +function derefLayers(layers) { + layers = layers.slice(); + + const map = Object.create(null); + for (let i = 0; i < layers.length; i++) { + map[layers[i].id] = layers[i]; + } + + for (let i = 0; i < layers.length; i++) { + if ('ref' in layers[i]) { + layers[i] = deref(layers[i], map[layers[i].ref]); + } + } + + return layers; +} diff --git a/node_modules/mapbox-gl/src/style-spec/diff.js b/node_modules/mapbox-gl/src/style-spec/diff.js new file mode 100644 index 0000000000000000000000000000000000000000..9228552e4b065b6394087294f02d0c92606132d7 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/diff.js @@ -0,0 +1,393 @@ + +import isEqual from './util/deep_equal'; + +const operations = { + + /* + * { command: 'setStyle', args: [stylesheet] } + */ + setStyle: 'setStyle', + + /* + * { command: 'addLayer', args: [layer, 'beforeLayerId'] } + */ + addLayer: 'addLayer', + + /* + * { command: 'removeLayer', args: ['layerId'] } + */ + removeLayer: 'removeLayer', + + /* + * { command: 'setPaintProperty', args: ['layerId', 'prop', value] } + */ + setPaintProperty: 'setPaintProperty', + + /* + * { command: 'setLayoutProperty', args: ['layerId', 'prop', value] } + */ + setLayoutProperty: 'setLayoutProperty', + + /* + * { command: 'setFilter', args: ['layerId', filter] } + */ + setFilter: 'setFilter', + + /* + * { command: 'addSource', args: ['sourceId', source] } + */ + addSource: 'addSource', + + /* + * { command: 'removeSource', args: ['sourceId'] } + */ + removeSource: 'removeSource', + + /* + * { command: 'setGeoJSONSourceData', args: ['sourceId', data] } + */ + setGeoJSONSourceData: 'setGeoJSONSourceData', + + /* + * { command: 'setLayerZoomRange', args: ['layerId', 0, 22] } + */ + setLayerZoomRange: 'setLayerZoomRange', + + /* + * { command: 'setLayerProperty', args: ['layerId', 'prop', value] } + */ + setLayerProperty: 'setLayerProperty', + + /* + * { command: 'setCenter', args: [[lon, lat]] } + */ + setCenter: 'setCenter', + + /* + * { command: 'setZoom', args: [zoom] } + */ + setZoom: 'setZoom', + + /* + * { command: 'setBearing', args: [bearing] } + */ + setBearing: 'setBearing', + + /* + * { command: 'setPitch', args: [pitch] } + */ + setPitch: 'setPitch', + + /* + * { command: 'setSprite', args: ['spriteUrl'] } + */ + setSprite: 'setSprite', + + /* + * { command: 'setGlyphs', args: ['glyphsUrl'] } + */ + setGlyphs: 'setGlyphs', + + /* + * { command: 'setTransition', args: [transition] } + */ + setTransition: 'setTransition', + + /* + * { command: 'setLighting', args: [lightProperties] } + */ + setLight: 'setLight' + +}; + +function addSource(sourceId, after, commands) { + commands.push({command: operations.addSource, args: [sourceId, after[sourceId]]}); +} + +function removeSource(sourceId, commands, sourcesRemoved) { + commands.push({command: operations.removeSource, args: [sourceId]}); + sourcesRemoved[sourceId] = true; +} + +function updateSource(sourceId, after, commands, sourcesRemoved) { + removeSource(sourceId, commands, sourcesRemoved); + addSource(sourceId, after, commands); +} + +function canUpdateGeoJSON(before, after, sourceId) { + let prop; + for (prop in before[sourceId]) { + if (!before[sourceId].hasOwnProperty(prop)) continue; + if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + for (prop in after[sourceId]) { + if (!after[sourceId].hasOwnProperty(prop)) continue; + if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + return true; +} + +function diffSources(before, after, commands, sourcesRemoved) { + before = before || {}; + after = after || {}; + + let sourceId; + + // look for sources to remove + for (sourceId in before) { + if (!before.hasOwnProperty(sourceId)) continue; + if (!after.hasOwnProperty(sourceId)) { + removeSource(sourceId, commands, sourcesRemoved); + } + } + + // look for sources to add/update + for (sourceId in after) { + if (!after.hasOwnProperty(sourceId)) continue; + if (!before.hasOwnProperty(sourceId)) { + addSource(sourceId, after, commands); + } else if (!isEqual(before[sourceId], after[sourceId])) { + if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) { + commands.push({command: operations.setGeoJSONSourceData, args: [sourceId, after[sourceId].data]}); + } else { + // no update command, must remove then add + updateSource(sourceId, after, commands, sourcesRemoved); + } + } + } +} + +function diffLayerPropertyChanges(before, after, commands, layerId, klass, command) { + before = before || {}; + after = after || {}; + + let prop; + + for (prop in before) { + if (!before.hasOwnProperty(prop)) continue; + if (!isEqual(before[prop], after[prop])) { + commands.push({command, args: [layerId, prop, after[prop], klass]}); + } + } + for (prop in after) { + if (!after.hasOwnProperty(prop) || before.hasOwnProperty(prop)) continue; + if (!isEqual(before[prop], after[prop])) { + commands.push({command, args: [layerId, prop, after[prop], klass]}); + } + } +} + +function pluckId(layer) { + return layer.id; +} +function indexById(group, layer) { + group[layer.id] = layer; + return group; +} + +function diffLayers(before, after, commands) { + before = before || []; + after = after || []; + + // order of layers by id + const beforeOrder = before.map(pluckId); + const afterOrder = after.map(pluckId); + + // index of layer by id + const beforeIndex = before.reduce(indexById, {}); + const afterIndex = after.reduce(indexById, {}); + + // track order of layers as if they have been mutated + const tracker = beforeOrder.slice(); + + // layers that have been added do not need to be diffed + const clean = Object.create(null); + + let i, d, layerId, beforeLayer, afterLayer, insertBeforeLayerId, prop; + + // remove layers + for (i = 0, d = 0; i < beforeOrder.length; i++) { + layerId = beforeOrder[i]; + if (!afterIndex.hasOwnProperty(layerId)) { + commands.push({command: operations.removeLayer, args: [layerId]}); + tracker.splice(tracker.indexOf(layerId, d), 1); + } else { + // limit where in tracker we need to look for a match + d++; + } + } + + // add/reorder layers + for (i = 0, d = 0; i < afterOrder.length; i++) { + // work backwards as insert is before an existing layer + layerId = afterOrder[afterOrder.length - 1 - i]; + + if (tracker[tracker.length - 1 - i] === layerId) continue; + + if (beforeIndex.hasOwnProperty(layerId)) { + // remove the layer before we insert at the correct position + commands.push({command: operations.removeLayer, args: [layerId]}); + tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1); + } else { + // limit where in tracker we need to look for a match + d++; + } + + // add layer at correct position + insertBeforeLayerId = tracker[tracker.length - i]; + commands.push({command: operations.addLayer, args: [afterIndex[layerId], insertBeforeLayerId]}); + tracker.splice(tracker.length - i, 0, layerId); + clean[layerId] = true; + } + + // update layers + for (i = 0; i < afterOrder.length; i++) { + layerId = afterOrder[i]; + beforeLayer = beforeIndex[layerId]; + afterLayer = afterIndex[layerId]; + + // no need to update if previously added (new or moved) + if (clean[layerId] || isEqual(beforeLayer, afterLayer)) continue; + + // If source, source-layer, or type have changes, then remove the layer + // and add it back 'from scratch'. + if (!isEqual(beforeLayer.source, afterLayer.source) || !isEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !isEqual(beforeLayer.type, afterLayer.type)) { + commands.push({command: operations.removeLayer, args: [layerId]}); + // we add the layer back at the same position it was already in, so + // there's no need to update the `tracker` + insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1]; + commands.push({command: operations.addLayer, args: [afterLayer, insertBeforeLayerId]}); + continue; + } + + // layout, paint, filter, minzoom, maxzoom + diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, operations.setLayoutProperty); + diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, operations.setPaintProperty); + if (!isEqual(beforeLayer.filter, afterLayer.filter)) { + commands.push({command: operations.setFilter, args: [layerId, afterLayer.filter]}); + } + if (!isEqual(beforeLayer.minzoom, afterLayer.minzoom) || !isEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) { + commands.push({command: operations.setLayerZoomRange, args: [layerId, afterLayer.minzoom, afterLayer.maxzoom]}); + } + + // handle all other layer props, including paint.* + for (prop in beforeLayer) { + if (!beforeLayer.hasOwnProperty(prop)) continue; + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || + prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue; + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty); + } else if (!isEqual(beforeLayer[prop], afterLayer[prop])) { + commands.push({command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]]}); + } + } + for (prop in afterLayer) { + if (!afterLayer.hasOwnProperty(prop) || beforeLayer.hasOwnProperty(prop)) continue; + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || + prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue; + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty); + } else if (!isEqual(beforeLayer[prop], afterLayer[prop])) { + commands.push({command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]]}); + } + } + } +} + +/** + * Diff two stylesheet + * + * Creates semanticly aware diffs that can easily be applied at runtime. + * Operations produced by the diff closely resemble the mapbox-gl-js API. Any + * error creating the diff will fall back to the 'setStyle' operation. + * + * Example diff: + * [ + * { command: 'setConstant', args: ['@water', '#0000FF'] }, + * { command: 'setPaintProperty', args: ['background', 'background-color', 'black'] } + * ] + * + * @private + * @param {*} [before] stylesheet to compare from + * @param {*} after stylesheet to compare to + * @returns Array list of changes + */ +function diffStyles(before, after) { + if (!before) return [{command: operations.setStyle, args: [after]}]; + + let commands = []; + + try { + // Handle changes to top-level properties + if (!isEqual(before.version, after.version)) { + return [{command: operations.setStyle, args: [after]}]; + } + if (!isEqual(before.center, after.center)) { + commands.push({command: operations.setCenter, args: [after.center]}); + } + if (!isEqual(before.zoom, after.zoom)) { + commands.push({command: operations.setZoom, args: [after.zoom]}); + } + if (!isEqual(before.bearing, after.bearing)) { + commands.push({command: operations.setBearing, args: [after.bearing]}); + } + if (!isEqual(before.pitch, after.pitch)) { + commands.push({command: operations.setPitch, args: [after.pitch]}); + } + if (!isEqual(before.sprite, after.sprite)) { + commands.push({command: operations.setSprite, args: [after.sprite]}); + } + if (!isEqual(before.glyphs, after.glyphs)) { + commands.push({command: operations.setGlyphs, args: [after.glyphs]}); + } + if (!isEqual(before.transition, after.transition)) { + commands.push({command: operations.setTransition, args: [after.transition]}); + } + if (!isEqual(before.light, after.light)) { + commands.push({command: operations.setLight, args: [after.light]}); + } + + // Handle changes to `sources` + // If a source is to be removed, we also--before the removeSource + // command--need to remove all the style layers that depend on it. + const sourcesRemoved = {}; + + // First collect the {add,remove}Source commands + const removeOrAddSourceCommands = []; + diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved); + + // Push a removeLayer command for each style layer that depends on a + // source that's being removed. + // Also, exclude any such layers them from the input to `diffLayers` + // below, so that diffLayers produces the appropriate `addLayers` + // command + const beforeLayers = []; + if (before.layers) { + before.layers.forEach((layer) => { + if (sourcesRemoved[layer.source]) { + commands.push({command: operations.removeLayer, args: [layer.id]}); + } else { + beforeLayers.push(layer); + } + }); + } + commands = commands.concat(removeOrAddSourceCommands); + + // Handle changes to `layers` + diffLayers(beforeLayers, after.layers, commands); + + } catch (e) { + // fall back to setStyle + console.warn('Unable to compute style diff:', e); + commands = [{command: operations.setStyle, args: [after]}]; + } + + return commands; +} + +export default diffStyles; +export {operations}; diff --git a/node_modules/mapbox-gl/src/style-spec/dist/.gitkeep b/node_modules/mapbox-gl/src/style-spec/dist/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/mapbox-gl/src/style-spec/dist/index.es.js b/node_modules/mapbox-gl/src/style-spec/dist/index.es.js new file mode 100644 index 0000000000000000000000000000000000000000..94abe7354b80ad0d1e2f4327ab5f8cb0e37bc1ae --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/dist/index.es.js @@ -0,0 +1,15032 @@ +var $version = 8; +var $root = { + version: { + required: true, + type: "enum", + values: [ + 8 + ], + doc: "Style specification version number. Must be 8.", + example: 8 + }, + name: { + type: "string", + doc: "A human-readable name for the style.", + example: "Bright" + }, + metadata: { + type: "*", + doc: "Arbitrary properties useful to track with the stylesheet, but do not influence rendering. Properties should be prefixed to avoid collisions, like 'mapbox:'." + }, + center: { + type: "array", + value: "number", + doc: "Default map center in longitude and latitude. The style center will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + example: [ + -73.9749, + 40.7736 + ] + }, + zoom: { + type: "number", + doc: "Default zoom level. The style zoom will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + example: 12.5 + }, + bearing: { + type: "number", + "default": 0, + period: 360, + units: "degrees", + doc: "Default bearing, in degrees. The bearing is the compass direction that is \"up\"; for example, a bearing of 90° orients the map so that east is up. This value will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + example: 29 + }, + pitch: { + type: "number", + "default": 0, + units: "degrees", + doc: "Default pitch, in degrees. Zero is perpendicular to the surface, for a look straight down at the map, while a greater value like 60 looks ahead towards the horizon. The style pitch will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + example: 50 + }, + light: { + type: "light", + doc: "The global light source.", + example: { + anchor: "viewport", + color: "white", + intensity: 0.4 + } + }, + sources: { + required: true, + type: "sources", + doc: "Data source specifications.", + example: { + "mapbox-streets": { + type: "vector", + url: "mapbox://mapbox.mapbox-streets-v6" + } + } + }, + sprite: { + type: "string", + doc: "A base URL for retrieving the sprite image and metadata. The extensions `.png`, `.json` and scale factor `@2x.png` will be automatically appended. This property is required if any layer uses the `background-pattern`, `fill-pattern`, `line-pattern`, `fill-extrusion-pattern`, or `icon-image` properties. The URL must be absolute, containing the [scheme, authority and path components](https://en.wikipedia.org/wiki/URL#Syntax).", + example: "mapbox://sprites/mapbox/bright-v8" + }, + glyphs: { + type: "string", + doc: "A URL template for loading signed-distance-field glyph sets in PBF format. The URL must include `{fontstack}` and `{range}` tokens. This property is required if any layer uses the `text-field` layout property. The URL must be absolute, containing the [scheme, authority and path components](https://en.wikipedia.org/wiki/URL#Syntax).", + example: "mapbox://fonts/mapbox/{fontstack}/{range}.pbf" + }, + transition: { + type: "transition", + doc: "A global transition definition to use as a default across properties, to be used for timing transitions between one value and the next when no property-specific transition is set. Collision-based symbol fading is controlled independently of the style's `transition` property.", + example: { + duration: 300, + delay: 0 + } + }, + layers: { + required: true, + type: "array", + value: "layer", + doc: "Layers will be drawn in the order of this array.", + example: [ + { + id: "water", + source: "mapbox-streets", + "source-layer": "water", + type: "fill", + paint: { + "fill-color": "#00ffff" + } + } + ] + } +}; +var sources = { + "*": { + type: "source", + doc: "Specification of a data source. For vector and raster sources, either TileJSON or a URL to a TileJSON must be provided. For image and video sources, a URL must be provided. For GeoJSON sources, a URL or inline GeoJSON must be provided." + } +}; +var source = [ + "source_vector", + "source_raster", + "source_raster_dem", + "source_geojson", + "source_video", + "source_image" +]; +var source_vector = { + type: { + required: true, + type: "enum", + values: { + vector: { + doc: "A vector tile source." + } + }, + doc: "The type of the source." + }, + url: { + type: "string", + doc: "A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://`." + }, + tiles: { + type: "array", + value: "string", + doc: "An array of one or more tile source URLs, as in the TileJSON spec." + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ], + doc: "An array containing the longitude and latitude of the southwest and northeast corners of the source's bounding box in the following order: `[sw.lng, sw.lat, ne.lng, ne.lat]`. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL." + }, + scheme: { + type: "enum", + values: { + xyz: { + doc: "Slippy map tilenames scheme." + }, + tms: { + doc: "OSGeo spec scheme." + } + }, + "default": "xyz", + doc: "Influences the y direction of the tile coordinates. The global-mercator (aka Spherical Mercator) profile is assumed." + }, + minzoom: { + type: "number", + "default": 0, + doc: "Minimum zoom level for which tiles are available, as in the TileJSON spec." + }, + maxzoom: { + type: "number", + "default": 22, + doc: "Maximum zoom level for which tiles are available, as in the TileJSON spec. Data from tiles at the maxzoom are used when displaying the map at higher zoom levels." + }, + attribution: { + type: "string", + doc: "Contains an attribution to be displayed when the map is shown to a user." + }, + promoteId: { + type: "promoteId", + doc: "A property to use as a feature id (for feature state). Either a property name, or an object of the form `{: }`. If specified as a string for a vector tile source, the same property is used across all its source layers." + }, + volatile: { + type: "boolean", + "default": false, + doc: "A setting to determine whether a source's tiles are cached locally.", + "sdk-support": { + "basic functionality": { + android: "9.3.0", + ios: "5.10.0" + } + } + }, + "*": { + type: "*", + doc: "Other keys to configure the data source." + } +}; +var source_raster = { + type: { + required: true, + type: "enum", + values: { + raster: { + doc: "A raster tile source." + } + }, + doc: "The type of the source." + }, + url: { + type: "string", + doc: "A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://`." + }, + tiles: { + type: "array", + value: "string", + doc: "An array of one or more tile source URLs, as in the TileJSON spec." + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ], + doc: "An array containing the longitude and latitude of the southwest and northeast corners of the source's bounding box in the following order: `[sw.lng, sw.lat, ne.lng, ne.lat]`. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL." + }, + minzoom: { + type: "number", + "default": 0, + doc: "Minimum zoom level for which tiles are available, as in the TileJSON spec." + }, + maxzoom: { + type: "number", + "default": 22, + doc: "Maximum zoom level for which tiles are available, as in the TileJSON spec. Data from tiles at the maxzoom are used when displaying the map at higher zoom levels." + }, + tileSize: { + type: "number", + "default": 512, + units: "pixels", + doc: "The minimum visual size to display tiles for this layer. Only configurable for raster layers." + }, + scheme: { + type: "enum", + values: { + xyz: { + doc: "Slippy map tilenames scheme." + }, + tms: { + doc: "OSGeo spec scheme." + } + }, + "default": "xyz", + doc: "Influences the y direction of the tile coordinates. The global-mercator (aka Spherical Mercator) profile is assumed." + }, + attribution: { + type: "string", + doc: "Contains an attribution to be displayed when the map is shown to a user." + }, + volatile: { + type: "boolean", + "default": false, + doc: "A setting to determine whether a source's tiles are cached locally.", + "sdk-support": { + "basic functionality": { + android: "9.3.0", + ios: "5.10.0" + } + } + }, + "*": { + type: "*", + doc: "Other keys to configure the data source." + } +}; +var source_raster_dem = { + type: { + required: true, + type: "enum", + values: { + "raster-dem": { + doc: "A RGB-encoded raster DEM source" + } + }, + doc: "The type of the source." + }, + url: { + type: "string", + doc: "A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://`." + }, + tiles: { + type: "array", + value: "string", + doc: "An array of one or more tile source URLs, as in the TileJSON spec." + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ], + doc: "An array containing the longitude and latitude of the southwest and northeast corners of the source's bounding box in the following order: `[sw.lng, sw.lat, ne.lng, ne.lat]`. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL." + }, + minzoom: { + type: "number", + "default": 0, + doc: "Minimum zoom level for which tiles are available, as in the TileJSON spec." + }, + maxzoom: { + type: "number", + "default": 22, + doc: "Maximum zoom level for which tiles are available, as in the TileJSON spec. Data from tiles at the maxzoom are used when displaying the map at higher zoom levels." + }, + tileSize: { + type: "number", + "default": 512, + units: "pixels", + doc: "The minimum visual size to display tiles for this layer. Only configurable for raster layers." + }, + attribution: { + type: "string", + doc: "Contains an attribution to be displayed when the map is shown to a user." + }, + encoding: { + type: "enum", + values: { + terrarium: { + doc: "Terrarium format PNG tiles. See https://aws.amazon.com/es/public-datasets/terrain/ for more info." + }, + mapbox: { + doc: "Mapbox Terrain RGB tiles. See https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb for more info." + } + }, + "default": "mapbox", + doc: "The encoding used by this source. Mapbox Terrain RGB is used by default" + }, + volatile: { + type: "boolean", + "default": false, + doc: "A setting to determine whether a source's tiles are cached locally.", + "sdk-support": { + "basic functionality": { + android: "9.3.0", + ios: "5.10.0" + } + } + }, + "*": { + type: "*", + doc: "Other keys to configure the data source." + } +}; +var source_geojson = { + type: { + required: true, + type: "enum", + values: { + geojson: { + doc: "A GeoJSON data source." + } + }, + doc: "The data type of the GeoJSON source." + }, + data: { + type: "*", + doc: "A URL to a GeoJSON file, or inline GeoJSON." + }, + maxzoom: { + type: "number", + "default": 18, + doc: "Maximum zoom level at which to create vector tiles (higher means greater detail at high zoom levels)." + }, + attribution: { + type: "string", + doc: "Contains an attribution to be displayed when the map is shown to a user." + }, + buffer: { + type: "number", + "default": 128, + maximum: 512, + minimum: 0, + doc: "Size of the tile buffer on each side. A value of 0 produces no buffer. A value of 512 produces a buffer as wide as the tile itself. Larger values produce fewer rendering artifacts near tile edges and slower performance." + }, + filter: { + type: "*", + doc: "An expression for filtering features prior to processing them for rendering." + }, + tolerance: { + type: "number", + "default": 0.375, + doc: "Douglas-Peucker simplification tolerance (higher means simpler geometries and faster performance)." + }, + cluster: { + type: "boolean", + "default": false, + doc: "If the data is a collection of point features, setting this to true clusters the points by radius into groups. Cluster groups become new `Point` features in the source with additional properties:\n * `cluster` Is `true` if the point is a cluster \n * `cluster_id` A unqiue id for the cluster to be used in conjunction with the [cluster inspection methods](https://www.mapbox.com/mapbox-gl-js/api/#geojsonsource#getclusterexpansionzoom)\n * `point_count` Number of original points grouped into this cluster\n * `point_count_abbreviated` An abbreviated point count" + }, + clusterRadius: { + type: "number", + "default": 50, + minimum: 0, + doc: "Radius of each cluster if clustering is enabled. A value of 512 indicates a radius equal to the width of a tile." + }, + clusterMaxZoom: { + type: "number", + doc: "Max zoom on which to cluster points if clustering is enabled. Defaults to one zoom less than maxzoom (so that last zoom features are not clustered). Clusters are re-evaluated at integer zoom levels so setting clusterMaxZoom to 14 means the clusters will be displayed until z15." + }, + clusterMinPoints: { + type: "number", + doc: "Minimum number of points necessary to form a cluster if clustering is enabled. Defaults to `2`." + }, + clusterProperties: { + type: "*", + doc: "An object defining custom properties on the generated clusters if clustering is enabled, aggregating values from clustered points. Has the form `{\"property_name\": [operator, map_expression]}`. `operator` is any expression function that accepts at least 2 operands (e.g. `\"+\"` or `\"max\"`) — it accumulates the property value from clusters/points the cluster contains; `map_expression` produces the value of a single point.\n\nExample: `{\"sum\": [\"+\", [\"get\", \"scalerank\"]]}`.\n\nFor more advanced use cases, in place of `operator`, you can use a custom reduce expression that references a special `[\"accumulated\"]` value, e.g.:\n`{\"sum\": [[\"+\", [\"accumulated\"], [\"get\", \"sum\"]], [\"get\", \"scalerank\"]]}`" + }, + lineMetrics: { + type: "boolean", + "default": false, + doc: "Whether to calculate line distance metrics. This is required for line layers that specify `line-gradient` values." + }, + generateId: { + type: "boolean", + "default": false, + doc: "Whether to generate ids for the geojson features. When enabled, the `feature.id` property will be auto assigned based on its index in the `features` array, over-writing any previous values." + }, + promoteId: { + type: "promoteId", + doc: "A property to use as a feature id (for feature state). Either a property name, or an object of the form `{: }`." + } +}; +var source_video = { + type: { + required: true, + type: "enum", + values: { + video: { + doc: "A video data source." + } + }, + doc: "The data type of the video source." + }, + urls: { + required: true, + type: "array", + value: "string", + doc: "URLs to video content in order of preferred format." + }, + coordinates: { + required: true, + doc: "Corners of video specified in longitude, latitude pairs.", + type: "array", + length: 4, + value: { + type: "array", + length: 2, + value: "number", + doc: "A single longitude, latitude pair." + } + } +}; +var source_image = { + type: { + required: true, + type: "enum", + values: { + image: { + doc: "An image data source." + } + }, + doc: "The data type of the image source." + }, + url: { + required: true, + type: "string", + doc: "URL that points to an image." + }, + coordinates: { + required: true, + doc: "Corners of image specified in longitude, latitude pairs.", + type: "array", + length: 4, + value: { + type: "array", + length: 2, + value: "number", + doc: "A single longitude, latitude pair." + } + } +}; +var layer = { + id: { + type: "string", + doc: "Unique layer name.", + required: true + }, + type: { + type: "enum", + values: { + fill: { + doc: "A filled polygon with an optional stroked border.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + } + }, + line: { + doc: "A stroked line.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + } + }, + symbol: { + doc: "An icon or a text label.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + } + }, + circle: { + doc: "A filled circle.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + } + }, + heatmap: { + doc: "A heatmap.", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "fill-extrusion": { + doc: "An extruded (3D) polygon.", + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + } + }, + raster: { + doc: "Raster map textures such as satellite imagery.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + } + }, + hillshade: { + doc: "Client-side hillshading visualization based on DEM data. Currently, the implementation only supports Mapbox Terrain RGB and Mapzen Terrarium tiles.", + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + background: { + doc: "The background color or pattern of the map.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + } + } + }, + doc: "Rendering type of this layer.", + required: true + }, + metadata: { + type: "*", + doc: "Arbitrary properties useful to track with the layer, but do not influence rendering. Properties should be prefixed to avoid collisions, like 'mapbox:'." + }, + source: { + type: "string", + doc: "Name of a source description to be used for this layer. Required for all layer types except `background`." + }, + "source-layer": { + type: "string", + doc: "Layer to use from a vector tile source. Required for vector tile sources; prohibited for all other source types, including GeoJSON sources." + }, + minzoom: { + type: "number", + minimum: 0, + maximum: 24, + doc: "The minimum zoom level for the layer. At zoom levels less than the minzoom, the layer will be hidden." + }, + maxzoom: { + type: "number", + minimum: 0, + maximum: 24, + doc: "The maximum zoom level for the layer. At zoom levels equal to or greater than the maxzoom, the layer will be hidden." + }, + filter: { + type: "filter", + doc: "A expression specifying conditions on source features. Only features that match the filter are displayed. Zoom expressions in filters are only evaluated at integer zoom levels. The `feature-state` expression is not supported in filter expressions." + }, + layout: { + type: "layout", + doc: "Layout properties for the layer." + }, + paint: { + type: "paint", + doc: "Default paint properties for this layer." + } +}; +var layout = [ + "layout_fill", + "layout_line", + "layout_circle", + "layout_heatmap", + "layout_fill-extrusion", + "layout_symbol", + "layout_raster", + "layout_hillshade", + "layout_background" +]; +var layout_background = { + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + "property-type": "constant" + } +}; +var layout_fill = { + "fill-sort-key": { + type: "number", + doc: "Sorts features in ascending order based on this value. Features with a higher sort key will appear above features with a lower sort key.", + "sdk-support": { + "basic functionality": { + js: "1.2.0", + android: "9.1.0", + ios: "5.8.0", + macos: "0.15.0" + }, + "data-driven styling": { + js: "1.2.0", + android: "9.1.0", + ios: "5.8.0", + macos: "0.15.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + "property-type": "constant" + } +}; +var layout_circle = { + "circle-sort-key": { + type: "number", + doc: "Sorts features in ascending order based on this value. Features with a higher sort key will appear above features with a lower sort key.", + "sdk-support": { + "basic functionality": { + js: "1.2.0", + android: "9.2.0", + ios: "5.9.0", + macos: "0.16.0" + }, + "data-driven styling": { + js: "1.2.0", + android: "9.2.0", + ios: "5.9.0", + macos: "0.16.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + "property-type": "constant" + } +}; +var layout_heatmap = { + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + "property-type": "constant" + } +}; +var layout_line = { + "line-cap": { + type: "enum", + values: { + butt: { + doc: "A cap with a squared-off end which is drawn to the exact endpoint of the line." + }, + round: { + doc: "A cap with a rounded end which is drawn beyond the endpoint of the line at a radius of one-half of the line's width and centered on the endpoint of the line." + }, + square: { + doc: "A cap with a squared-off end which is drawn beyond the endpoint of the line at a distance of one-half of the line's width." + } + }, + "default": "butt", + doc: "The display of line endings.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-join": { + type: "enum", + values: { + bevel: { + doc: "A join with a squared-off end which is drawn beyond the endpoint of the line at a distance of one-half of the line's width." + }, + round: { + doc: "A join with a rounded end which is drawn beyond the endpoint of the line at a radius of one-half of the line's width and centered on the endpoint of the line." + }, + miter: { + doc: "A join with a sharp, angled corner which is drawn with the outer sides beyond the endpoint of the path until they meet." + } + }, + "default": "miter", + doc: "The display of lines when joining.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.40.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "line-miter-limit": { + type: "number", + "default": 2, + doc: "Used to automatically convert miter joins to bevel joins for sharp angles.", + requires: [ + { + "line-join": "miter" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-round-limit": { + type: "number", + "default": 1.05, + doc: "Used to automatically convert round joins to miter joins for shallow angles.", + requires: [ + { + "line-join": "round" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-sort-key": { + type: "number", + doc: "Sorts features in ascending order based on this value. Features with a higher sort key will appear above features with a lower sort key.", + "sdk-support": { + "basic functionality": { + js: "1.2.0", + android: "9.1.0", + ios: "5.8.0", + macos: "0.15.0" + }, + "data-driven styling": { + js: "1.2.0", + android: "9.1.0", + ios: "5.8.0", + macos: "0.15.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + "property-type": "constant" + } +}; +var layout_symbol = { + "symbol-placement": { + type: "enum", + values: { + point: { + doc: "The label is placed at the point where the geometry is located." + }, + line: { + doc: "The label is placed along the line of the geometry. Can only be used on `LineString` and `Polygon` geometries." + }, + "line-center": { + doc: "The label is placed at the center of the line of the geometry. Can only be used on `LineString` and `Polygon` geometries. Note that a single feature in a vector tile may contain multiple line geometries." + } + }, + "default": "point", + doc: "Label placement relative to its geometry.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "`line-center` value": { + js: "0.47.0", + android: "6.4.0", + ios: "4.3.0", + macos: "0.10.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-spacing": { + type: "number", + "default": 250, + minimum: 1, + units: "pixels", + doc: "Distance between two symbol anchors.", + requires: [ + { + "symbol-placement": "line" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-avoid-edges": { + type: "boolean", + "default": false, + doc: "If true, the symbols will not cross tile edges to avoid mutual collisions. Recommended in layers that don't have enough padding in the vector tile to prevent collisions, or if it is a point symbol layer placed after a line symbol layer. When using a client that supports global collision detection, like Mapbox GL JS version 0.42.0 or greater, enabling this property is not needed to prevent clipped labels at tile boundaries.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-sort-key": { + type: "number", + doc: "Sorts features in ascending order based on this value. Features with lower sort keys are drawn and placed first. When `icon-allow-overlap` or `text-allow-overlap` is `false`, features with a lower sort key will have priority during placement. When `icon-allow-overlap` or `text-allow-overlap` is set to `true`, features with a higher sort key will overlap over features with a lower sort key.", + "sdk-support": { + "basic functionality": { + js: "0.53.0", + android: "7.4.0", + ios: "4.11.0", + macos: "0.14.0" + }, + "data-driven styling": { + js: "0.53.0", + android: "7.4.0", + ios: "4.11.0", + macos: "0.14.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "symbol-z-order": { + type: "enum", + values: { + auto: { + doc: "Sorts symbols by `symbol-sort-key` if set. Otherwise, sorts symbols by their y-position relative to the viewport if `icon-allow-overlap` or `text-allow-overlap` is set to `true` or `icon-ignore-placement` or `text-ignore-placement` is `false`." + }, + "viewport-y": { + doc: "Sorts symbols by their y-position relative to the viewport if `icon-allow-overlap` or `text-allow-overlap` is set to `true` or `icon-ignore-placement` or `text-ignore-placement` is `false`." + }, + source: { + doc: "Sorts symbols by `symbol-sort-key` if set. Otherwise, no sorting is applied; symbols are rendered in the same order as the source data." + } + }, + "default": "auto", + doc: "Determines whether overlapping symbols in the same layer are rendered in the order that they appear in the data source or by their y-position relative to the viewport. To control the order and prioritization of symbols otherwise, use `symbol-sort-key`.", + "sdk-support": { + "basic functionality": { + js: "0.49.0", + android: "6.6.0", + ios: "4.5.0", + macos: "0.12.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-allow-overlap": { + type: "boolean", + "default": false, + doc: "If true, the icon will be visible even if it collides with other previously drawn symbols.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-ignore-placement": { + type: "boolean", + "default": false, + doc: "If true, other symbols can be visible even if they collide with the icon.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-optional": { + type: "boolean", + "default": false, + doc: "If true, text will display without their corresponding icons when the icon collides with other symbols and the text does not.", + requires: [ + "icon-image", + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-rotation-alignment": { + type: "enum", + values: { + map: { + doc: "When `symbol-placement` is set to `point`, aligns icons east-west. When `symbol-placement` is set to `line` or `line-center`, aligns icon x-axes with the line." + }, + viewport: { + doc: "Produces icons whose x-axes are aligned with the x-axis of the viewport, regardless of the value of `symbol-placement`." + }, + auto: { + doc: "When `symbol-placement` is set to `point`, this is equivalent to `viewport`. When `symbol-placement` is set to `line` or `line-center`, this is equivalent to `map`." + } + }, + "default": "auto", + doc: "In combination with `symbol-placement`, determines the rotation behavior of icons.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "`auto` value": { + js: "0.25.0", + android: "4.2.0", + ios: "3.4.0", + macos: "0.3.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-size": { + type: "number", + "default": 1, + minimum: 0, + units: "factor of the original icon size", + doc: "Scales the original size of the icon by the provided factor. The new pixel size of the image will be the original pixel size multiplied by `icon-size`. 1 is the original size; 3 triples the size of the image.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.35.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-text-fit": { + type: "enum", + values: { + none: { + doc: "The icon is displayed at its intrinsic aspect ratio." + }, + width: { + doc: "The icon is scaled in the x-dimension to fit the width of the text." + }, + height: { + doc: "The icon is scaled in the y-dimension to fit the height of the text." + }, + both: { + doc: "The icon is scaled in both x- and y-dimensions." + } + }, + "default": "none", + doc: "Scales the icon to fit around the associated text.", + requires: [ + "icon-image", + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.21.0", + android: "4.2.0", + ios: "3.4.0", + macos: "0.2.1" + }, + "stretchable icons": { + js: "1.6.0", + android: "9.2.0", + ios: "5.8.0", + macos: "0.15.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-text-fit-padding": { + type: "array", + value: "number", + length: 4, + "default": [ + 0, + 0, + 0, + 0 + ], + units: "pixels", + doc: "Size of the additional area added to dimensions determined by `icon-text-fit`, in clockwise order: top, right, bottom, left.", + requires: [ + "icon-image", + "text-field", + { + "icon-text-fit": [ + "both", + "width", + "height" + ] + } + ], + "sdk-support": { + "basic functionality": { + js: "0.21.0", + android: "4.2.0", + ios: "3.4.0", + macos: "0.2.1" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-image": { + type: "resolvedImage", + doc: "Name of image in sprite to use for drawing an image background.", + tokens: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.35.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-rotate": { + type: "number", + "default": 0, + period: 360, + units: "degrees", + doc: "Rotates the icon clockwise.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.21.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-padding": { + type: "number", + "default": 2, + minimum: 0, + units: "pixels", + doc: "Size of the additional area around the icon bounding box used for detecting symbol collisions.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-keep-upright": { + type: "boolean", + "default": false, + doc: "If true, the icon may be flipped to prevent it from being rendered upside-down.", + requires: [ + "icon-image", + { + "icon-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-offset": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + doc: "Offset distance of icon from its anchor. Positive values indicate right and down, while negative values indicate left and up. Each component is multiplied by the value of `icon-size` to obtain the final offset in pixels. When combined with `icon-rotate` the offset will be as if the rotated direction was up.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-anchor": { + type: "enum", + values: { + center: { + doc: "The center of the icon is placed closest to the anchor." + }, + left: { + doc: "The left side of the icon is placed closest to the anchor." + }, + right: { + doc: "The right side of the icon is placed closest to the anchor." + }, + top: { + doc: "The top of the icon is placed closest to the anchor." + }, + bottom: { + doc: "The bottom of the icon is placed closest to the anchor." + }, + "top-left": { + doc: "The top left corner of the icon is placed closest to the anchor." + }, + "top-right": { + doc: "The top right corner of the icon is placed closest to the anchor." + }, + "bottom-left": { + doc: "The bottom left corner of the icon is placed closest to the anchor." + }, + "bottom-right": { + doc: "The bottom right corner of the icon is placed closest to the anchor." + } + }, + "default": "center", + doc: "Part of the icon placed closest to the anchor.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.40.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + }, + "data-driven styling": { + js: "0.40.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-pitch-alignment": { + type: "enum", + values: { + map: { + doc: "The icon is aligned to the plane of the map." + }, + viewport: { + doc: "The icon is aligned to the plane of the viewport." + }, + auto: { + doc: "Automatically matches the value of `icon-rotation-alignment`." + } + }, + "default": "auto", + doc: "Orientation of icon when map is pitched.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.39.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-pitch-alignment": { + type: "enum", + values: { + map: { + doc: "The text is aligned to the plane of the map." + }, + viewport: { + doc: "The text is aligned to the plane of the viewport." + }, + auto: { + doc: "Automatically matches the value of `text-rotation-alignment`." + } + }, + "default": "auto", + doc: "Orientation of text when map is pitched.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.21.0", + android: "4.2.0", + ios: "3.4.0", + macos: "0.2.1" + }, + "`auto` value": { + js: "0.25.0", + android: "4.2.0", + ios: "3.4.0", + macos: "0.3.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotation-alignment": { + type: "enum", + values: { + map: { + doc: "When `symbol-placement` is set to `point`, aligns text east-west. When `symbol-placement` is set to `line` or `line-center`, aligns text x-axes with the line." + }, + viewport: { + doc: "Produces glyphs whose x-axes are aligned with the x-axis of the viewport, regardless of the value of `symbol-placement`." + }, + auto: { + doc: "When `symbol-placement` is set to `point`, this is equivalent to `viewport`. When `symbol-placement` is set to `line` or `line-center`, this is equivalent to `map`." + } + }, + "default": "auto", + doc: "In combination with `symbol-placement`, determines the rotation behavior of the individual glyphs forming the text.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "`auto` value": { + js: "0.25.0", + android: "4.2.0", + ios: "3.4.0", + macos: "0.3.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-field": { + type: "formatted", + "default": "", + tokens: true, + doc: "Value to use for a text label. If a plain `string` is provided, it will be treated as a `formatted` with default/inherited formatting options.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-font": { + type: "array", + value: "string", + "default": [ + "Open Sans Regular", + "Arial Unicode MS Regular" + ], + doc: "Font stack to use for displaying text.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-size": { + type: "number", + "default": 16, + minimum: 0, + units: "pixels", + doc: "Font size.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.35.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-width": { + type: "number", + "default": 10, + minimum: 0, + units: "ems", + doc: "The maximum line width for text wrapping.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.40.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-line-height": { + type: "number", + "default": 1.2, + units: "ems", + doc: "Text leading value for multi-line text.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-letter-spacing": { + type: "number", + "default": 0, + units: "ems", + doc: "Text tracking amount.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.40.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-justify": { + type: "enum", + values: { + auto: { + doc: "The text is aligned towards the anchor position." + }, + left: { + doc: "The text is aligned to the left." + }, + center: { + doc: "The text is centered." + }, + right: { + doc: "The text is aligned to the right." + } + }, + "default": "center", + doc: "Text justification options.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.39.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + }, + auto: { + js: "0.54.0", + android: "7.4.0", + ios: "4.10.0", + macos: "0.14.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-radial-offset": { + type: "number", + units: "ems", + "default": 0, + doc: "Radial offset of text, in the direction of the symbol's anchor. Useful in combination with `text-variable-anchor`, which defaults to using the two-dimensional `text-offset` if present.", + "sdk-support": { + "basic functionality": { + js: "0.54.0", + android: "7.4.0", + ios: "4.10.0", + macos: "0.14.0" + }, + "data-driven styling": { + js: "0.54.0", + android: "7.4.0", + ios: "4.10.0", + macos: "0.14.0" + } + }, + requires: [ + "text-field" + ], + "property-type": "data-driven", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + } + }, + "text-variable-anchor": { + type: "array", + value: "enum", + values: { + center: { + doc: "The center of the text is placed closest to the anchor." + }, + left: { + doc: "The left side of the text is placed closest to the anchor." + }, + right: { + doc: "The right side of the text is placed closest to the anchor." + }, + top: { + doc: "The top of the text is placed closest to the anchor." + }, + bottom: { + doc: "The bottom of the text is placed closest to the anchor." + }, + "top-left": { + doc: "The top left corner of the text is placed closest to the anchor." + }, + "top-right": { + doc: "The top right corner of the text is placed closest to the anchor." + }, + "bottom-left": { + doc: "The bottom left corner of the text is placed closest to the anchor." + }, + "bottom-right": { + doc: "The bottom right corner of the text is placed closest to the anchor." + } + }, + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + doc: "To increase the chance of placing high-priority labels on the map, you can provide an array of `text-anchor` locations: the renderer will attempt to place the label at each location, in order, before moving onto the next label. Use `text-justify: auto` to choose justification based on anchor position. To apply an offset, use the `text-radial-offset` or the two-dimensional `text-offset`.", + "sdk-support": { + "basic functionality": { + js: "0.54.0", + android: "7.4.0", + ios: "4.10.0", + macos: "0.14.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-anchor": { + type: "enum", + values: { + center: { + doc: "The center of the text is placed closest to the anchor." + }, + left: { + doc: "The left side of the text is placed closest to the anchor." + }, + right: { + doc: "The right side of the text is placed closest to the anchor." + }, + top: { + doc: "The top of the text is placed closest to the anchor." + }, + bottom: { + doc: "The bottom of the text is placed closest to the anchor." + }, + "top-left": { + doc: "The top left corner of the text is placed closest to the anchor." + }, + "top-right": { + doc: "The top right corner of the text is placed closest to the anchor." + }, + "bottom-left": { + doc: "The bottom left corner of the text is placed closest to the anchor." + }, + "bottom-right": { + doc: "The bottom right corner of the text is placed closest to the anchor." + } + }, + "default": "center", + doc: "Part of the text placed closest to the anchor.", + requires: [ + "text-field", + { + "!": "text-variable-anchor" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.39.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-angle": { + type: "number", + "default": 45, + units: "degrees", + doc: "Maximum angle change between adjacent characters.", + requires: [ + "text-field", + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-writing-mode": { + type: "array", + value: "enum", + values: { + horizontal: { + doc: "If a text's language supports horizontal writing mode, symbols with point placement would be laid out horizontally." + }, + vertical: { + doc: "If a text's language supports vertical writing mode, symbols with point placement would be laid out vertically." + } + }, + doc: "The property allows control over a symbol's orientation. Note that the property values act as a hint, so that a symbol whose language doesn’t support the provided orientation will be laid out in its natural orientation. Example: English point symbol will be rendered horizontally even if array value contains single 'vertical' enum value. The order of elements in an array define priority order for the placement of an orientation variant.", + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + "sdk-support": { + "basic functionality": { + js: "1.3.0", + android: "8.3.0", + ios: "5.3.0", + macos: "0.15.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotate": { + type: "number", + "default": 0, + period: 360, + units: "degrees", + doc: "Rotates the text clockwise.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.35.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-padding": { + type: "number", + "default": 2, + minimum: 0, + units: "pixels", + doc: "Size of the additional area around the text bounding box used for detecting symbol collisions.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-keep-upright": { + type: "boolean", + "default": true, + doc: "If true, the text may be flipped vertically to prevent it from being rendered upside-down.", + requires: [ + "text-field", + { + "text-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-transform": { + type: "enum", + values: { + none: { + doc: "The text is not altered." + }, + uppercase: { + doc: "Forces all letters to be displayed in uppercase." + }, + lowercase: { + doc: "Forces all letters to be displayed in lowercase." + } + }, + "default": "none", + doc: "Specifies how to capitalize text, similar to the CSS `text-transform` property.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-offset": { + type: "array", + doc: "Offset distance of text from its anchor. Positive values indicate right and down, while negative values indicate left and up. If used with text-variable-anchor, input values will be taken as absolute values. Offsets along the x- and y-axis will be applied automatically based on the anchor position.", + value: "number", + units: "ems", + length: 2, + "default": [ + 0, + 0 + ], + requires: [ + "text-field", + { + "!": "text-radial-offset" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.35.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-allow-overlap": { + type: "boolean", + "default": false, + doc: "If true, the text will be visible even if it collides with other previously drawn symbols.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-ignore-placement": { + type: "boolean", + "default": false, + doc: "If true, other symbols can be visible even if they collide with the text.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-optional": { + type: "boolean", + "default": false, + doc: "If true, icons will display without their corresponding text when the text collides with other symbols and the icon does not.", + requires: [ + "text-field", + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + "property-type": "constant" + } +}; +var layout_raster = { + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + "property-type": "constant" + } +}; +var layout_hillshade = { + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + "property-type": "constant" + } +}; +var filter = { + type: "array", + value: "*", + doc: "A filter selects specific features from a layer." +}; +var filter_operator = { + type: "enum", + values: { + "==": { + doc: "`[\"==\", key, value]` equality: `feature[key] = value`" + }, + "!=": { + doc: "`[\"!=\", key, value]` inequality: `feature[key] ≠ value`" + }, + ">": { + doc: "`[\">\", key, value]` greater than: `feature[key] > value`" + }, + ">=": { + doc: "`[\">=\", key, value]` greater than or equal: `feature[key] ≥ value`" + }, + "<": { + doc: "`[\"<\", key, value]` less than: `feature[key] < value`" + }, + "<=": { + doc: "`[\"<=\", key, value]` less than or equal: `feature[key] ≤ value`" + }, + "in": { + doc: "`[\"in\", key, v0, ..., vn]` set inclusion: `feature[key] ∈ {v0, ..., vn}`" + }, + "!in": { + doc: "`[\"!in\", key, v0, ..., vn]` set exclusion: `feature[key] ∉ {v0, ..., vn}`" + }, + all: { + doc: "`[\"all\", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`" + }, + any: { + doc: "`[\"any\", f0, ..., fn]` logical `OR`: `f0 ∨ ... ∨ fn`" + }, + none: { + doc: "`[\"none\", f0, ..., fn]` logical `NOR`: `¬f0 ∧ ... ∧ ¬fn`" + }, + has: { + doc: "`[\"has\", key]` `feature[key]` exists" + }, + "!has": { + doc: "`[\"!has\", key]` `feature[key]` does not exist" + }, + within: { + doc: "`[\"within\", object]` feature geometry is within object geometry" + } + }, + doc: "The filter operator." +}; +var geometry_type = { + type: "enum", + values: { + Point: { + doc: "Filter to point geometries." + }, + LineString: { + doc: "Filter to line geometries." + }, + Polygon: { + doc: "Filter to polygon geometries." + } + }, + doc: "The geometry type for the filter to select." +}; +var function_stop = { + type: "array", + minimum: 0, + maximum: 24, + value: [ + "number", + "color" + ], + length: 2, + doc: "Zoom level and value pair." +}; +var expression = { + type: "array", + value: "*", + minimum: 1, + doc: "An expression defines a function that can be used for data-driven style properties or feature filters." +}; +var expression_name = { + doc: "", + type: "enum", + values: { + "let": { + doc: "Binds expressions to named variables, which can then be referenced in the result expression using [\"var\", \"variable_name\"].", + group: "Variable binding", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "var": { + doc: "References variable bound using \"let\".", + group: "Variable binding", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + literal: { + doc: "Provides a literal array or object value.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + array: { + doc: "Asserts that the input is an array (optionally with a specific item type and length). If, when the input expression is evaluated, it is not of the asserted type, then this assertion will cause the whole expression to be aborted.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + at: { + doc: "Retrieves an item from an array.", + group: "Lookup", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "in": { + doc: "Determines whether an item exists in an array or a substring exists in a string.", + group: "Lookup", + "sdk-support": { + "basic functionality": { + js: "1.6.0", + android: "9.1.0", + ios: "5.8.0", + macos: "0.15.0" + } + } + }, + "index-of": { + doc: "Returns the first position at which an item can be found in an array or a substring can be found in a string, or `-1` if the input cannot be found. Accepts an optional index from where to begin the search.", + group: "Lookup", + "sdk-support": { + "basic functionality": { + js: "1.10.0" + } + } + }, + slice: { + doc: "Returns an item from an array or a substring from a string from a specified start index, or between a start index and an end index if set. The return value is inclusive of the start index but not of the end index.", + group: "Lookup", + "sdk-support": { + "basic functionality": { + js: "1.10.0" + } + } + }, + "case": { + doc: "Selects the first output whose corresponding test condition evaluates to true, or the fallback value otherwise.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + match: { + doc: "Selects the output whose label value matches the input value, or the fallback value if no match is found. The input can be any expression (e.g. `[\"get\", \"building_type\"]`). Each label must be either:\n - a single literal value; or\n - an array of literal values, whose values must be all strings or all numbers (e.g. `[100, 101]` or `[\"c\", \"b\"]`). The input matches if any of the values in the array matches, similar to the `\"in\"` operator.\nEach label must be unique. If the input type does not match the type of the labels, the result will be the fallback value.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + coalesce: { + doc: "Evaluates each expression in turn until the first non-null value is obtained, and returns that value.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + step: { + doc: "Produces discrete, stepped results by evaluating a piecewise-constant function defined by pairs of input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). Stop inputs must be numeric literals in strictly ascending order. Returns the output value of the stop just less than the input, or the first output if the input is less than the first stop.", + group: "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + js: "0.42.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + interpolate: { + doc: "Produces continuous, smooth results by interpolating between pairs of input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). Stop inputs must be numeric literals in strictly ascending order. The output type must be `number`, `array`, or `color`.\n\nInterpolation types:\n- `[\"linear\"]`: Interpolates linearly between the pair of stops just less than and just greater than the input.\n- `[\"exponential\", base]`: Interpolates exponentially between the stops just less than and just greater than the input. `base` controls the rate at which the output increases: higher values make the output increase more towards the high end of the range. With values close to 1 the output increases linearly.\n- `[\"cubic-bezier\", x1, y1, x2, y2]`: Interpolates using the cubic bezier curve defined by the given control points.", + group: "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + js: "0.42.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "interpolate-hcl": { + doc: "Produces continuous, smooth results by interpolating between pairs of input and output values (\"stops\"). Works like `interpolate`, but the output type must be `color`, and the interpolation is performed in the Hue-Chroma-Luminance color space.", + group: "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + js: "0.49.0" + } + } + }, + "interpolate-lab": { + doc: "Produces continuous, smooth results by interpolating between pairs of input and output values (\"stops\"). Works like `interpolate`, but the output type must be `color`, and the interpolation is performed in the CIELAB color space.", + group: "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + js: "0.49.0" + } + } + }, + ln2: { + doc: "Returns mathematical constant ln(2).", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + pi: { + doc: "Returns the mathematical constant pi.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + e: { + doc: "Returns the mathematical constant e.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "typeof": { + doc: "Returns a string describing the type of the given value.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + string: { + doc: "Asserts that the input value is a string. If multiple values are provided, each one is evaluated in order until a string is obtained. If none of the inputs are strings, the expression is an error.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + number: { + doc: "Asserts that the input value is a number. If multiple values are provided, each one is evaluated in order until a number is obtained. If none of the inputs are numbers, the expression is an error.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + boolean: { + doc: "Asserts that the input value is a boolean. If multiple values are provided, each one is evaluated in order until a boolean is obtained. If none of the inputs are booleans, the expression is an error.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + object: { + doc: "Asserts that the input value is an object. If multiple values are provided, each one is evaluated in order until an object is obtained. If none of the inputs are objects, the expression is an error.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + collator: { + doc: "Returns a `collator` for use in locale-dependent comparison operations. The `case-sensitive` and `diacritic-sensitive` options default to `false`. The `locale` argument specifies the IETF language tag of the locale to use. If none is provided, the default locale is used. If the requested locale is not available, the `collator` will use a system-defined fallback locale. Use `resolved-locale` to test the results of locale fallback behavior.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + }, + format: { + doc: "Returns a `formatted` string for displaying mixed-format text in the `text-field` property. The input may contain a string literal or expression, including an [`'image'`](#types-image) expression. Strings may be followed by a style override object that supports the following properties:\n- `\"text-font\"`: Overrides the font stack specified by the root layout property.\n- `\"text-color\"`: Overrides the color specified by the root paint property.\n- `\"font-scale\"`: Applies a scaling factor on `text-size` as specified by the root layout property.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.48.0", + android: "6.7.0", + ios: "4.6.0", + macos: "0.12.0" + }, + "text-font": { + js: "0.48.0", + android: "6.7.0", + ios: "4.6.0", + macos: "0.12.0" + }, + "font-scale": { + js: "0.48.0", + android: "6.7.0", + ios: "4.6.0", + macos: "0.12.0" + }, + "text-color": { + js: "1.3.0", + android: "7.3.0", + ios: "4.10.0", + macos: "0.14.0" + }, + image: { + js: "1.6.0", + android: "8.6.0", + ios: "5.7.0", + macos: "0.15.0" + } + } + }, + image: { + doc: "Returns an `image` type for use in `icon-image`, `*-pattern` entries and as a section in the `format` expression. If set, the `image` argument will check that the requested image exists in the style and will return either the resolved image name or `null`, depending on whether or not the image is currently in the style. This validation process is synchronous and requires the image to have been added to the style before requesting it in the `image` argument.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "1.4.0", + android: "8.6.0", + ios: "5.7.0", + macos: "0.15.0" + } + } + }, + "number-format": { + doc: "Converts the input number into a string representation using the providing formatting rules. If set, the `locale` argument specifies the locale to use, as a BCP 47 language tag. If set, the `currency` argument specifies an ISO 4217 code to use for currency-style formatting. If set, the `min-fraction-digits` and `max-fraction-digits` arguments specify the minimum and maximum number of fractional digits to include.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.54.0" + } + } + }, + "to-string": { + doc: "Converts the input value to a string. If the input is `null`, the result is `\"\"`. If the input is a boolean, the result is `\"true\"` or `\"false\"`. If the input is a number, it is converted to a string as specified by the [\"NumberToString\" algorithm](https://tc39.github.io/ecma262/#sec-tostring-applied-to-the-number-type) of the ECMAScript Language Specification. If the input is a color, it is converted to a string of the form `\"rgba(r,g,b,a)\"`, where `r`, `g`, and `b` are numerals ranging from 0 to 255, and `a` ranges from 0 to 1. Otherwise, the input is converted to a string in the format specified by the [`JSON.stringify`](https://tc39.github.io/ecma262/#sec-json.stringify) function of the ECMAScript Language Specification.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "to-number": { + doc: "Converts the input value to a number, if possible. If the input is `null` or `false`, the result is 0. If the input is `true`, the result is 1. If the input is a string, it is converted to a number as specified by the [\"ToNumber Applied to the String Type\" algorithm](https://tc39.github.io/ecma262/#sec-tonumber-applied-to-the-string-type) of the ECMAScript Language Specification. If multiple values are provided, each one is evaluated in order until the first successful conversion is obtained. If none of the inputs can be converted, the expression is an error.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "to-boolean": { + doc: "Converts the input value to a boolean. The result is `false` when then input is an empty string, 0, `false`, `null`, or `NaN`; otherwise it is `true`.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "to-rgba": { + doc: "Returns a four-element array containing the input color's red, green, blue, and alpha components, in that order.", + group: "Color", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "to-color": { + doc: "Converts the input value to a color. If multiple values are provided, each one is evaluated in order until the first successful conversion is obtained. If none of the inputs can be converted, the expression is an error.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + rgb: { + doc: "Creates a color value from red, green, and blue components, which must range between 0 and 255, and an alpha component of 1. If any component is out of range, the expression is an error.", + group: "Color", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + rgba: { + doc: "Creates a color value from red, green, blue components, which must range between 0 and 255, and an alpha component which must range between 0 and 1. If any component is out of range, the expression is an error.", + group: "Color", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + get: { + doc: "Retrieves a property value from the current feature's properties, or from another object if a second argument is provided. Returns null if the requested property is missing.", + group: "Lookup", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + has: { + doc: "Tests for the presence of an property value in the current feature's properties, or from another object if a second argument is provided.", + group: "Lookup", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + length: { + doc: "Gets the length of an array or string.", + group: "Lookup", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + properties: { + doc: "Gets the feature properties object. Note that in some cases, it may be more efficient to use [\"get\", \"property_name\"] directly.", + group: "Feature data", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "feature-state": { + doc: "Retrieves a property value from the current feature's state. Returns null if the requested property is not present on the feature's state. A feature's state is not part of the GeoJSON or vector tile data, and must be set programmatically on each feature. Features are identified by their `id` attribute, which must be an integer or a string that can be cast to an integer. Note that [\"feature-state\"] can only be used with paint properties that support data-driven styling.", + group: "Feature data", + "sdk-support": { + "basic functionality": { + js: "0.46.0" + } + } + }, + "geometry-type": { + doc: "Gets the feature's geometry type: `Point`, `MultiPoint`, `LineString`, `MultiLineString`, `Polygon`, `MultiPolygon`.", + group: "Feature data", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + id: { + doc: "Gets the feature's id, if it has one.", + group: "Feature data", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + zoom: { + doc: "Gets the current zoom level. Note that in style layout and paint properties, [\"zoom\"] may only appear as the input to a top-level \"step\" or \"interpolate\" expression.", + group: "Zoom", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "heatmap-density": { + doc: "Gets the kernel density estimation of a pixel in a heatmap layer, which is a relative measure of how many data points are crowded around a particular pixel. Can only be used in the `heatmap-color` property.", + group: "Heatmap", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "line-progress": { + doc: "Gets the progress along a gradient line. Can only be used in the `line-gradient` property.", + group: "Feature data", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.5.0", + ios: "4.6.0", + macos: "0.12.0" + } + } + }, + accumulated: { + doc: "Gets the value of a cluster property accumulated so far. Can only be used in the `clusterProperties` option of a clustered GeoJSON source.", + group: "Feature data", + "sdk-support": { + "basic functionality": { + js: "0.53.0" + } + } + }, + "+": { + doc: "Returns the sum of the inputs.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "*": { + doc: "Returns the product of the inputs.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "-": { + doc: "For two inputs, returns the result of subtracting the second input from the first. For a single input, returns the result of subtracting it from 0.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "/": { + doc: "Returns the result of floating point division of the first input by the second.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "%": { + doc: "Returns the remainder after integer division of the first input by the second.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "^": { + doc: "Returns the result of raising the first input to the power specified by the second.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + sqrt: { + doc: "Returns the square root of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.42.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + log10: { + doc: "Returns the base-ten logarithm of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + ln: { + doc: "Returns the natural logarithm of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + log2: { + doc: "Returns the base-two logarithm of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + sin: { + doc: "Returns the sine of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + cos: { + doc: "Returns the cosine of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + tan: { + doc: "Returns the tangent of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + asin: { + doc: "Returns the arcsine of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + acos: { + doc: "Returns the arccosine of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + atan: { + doc: "Returns the arctangent of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + min: { + doc: "Returns the minimum value of the inputs.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + max: { + doc: "Returns the maximum value of the inputs.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + round: { + doc: "Rounds the input to the nearest integer. Halfway values are rounded away from zero. For example, `[\"round\", -1.5]` evaluates to -2.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + abs: { + doc: "Returns the absolute value of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + ceil: { + doc: "Returns the smallest integer that is greater than or equal to the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + floor: { + doc: "Returns the largest integer that is less than or equal to the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + distance: { + doc: "Returns the shortest distance in meters between the evaluated feature and the input geometry. The input value can be a valid GeoJSON of type `Point`, `MultiPoint`, `LineString`, `MultiLineString`, `Polygon`, `MultiPolygon`, `Feature`, or `FeatureCollection`. Distance values returned may vary in precision due to loss in precision from encoding geometries, particularly below zoom level 13.", + group: "Math", + "sdk-support": { + "basic functionality": { + android: "9.2.0", + ios: "5.9.0", + macos: "0.16.0" + } + } + }, + "==": { + doc: "Returns `true` if the input values are equal, `false` otherwise. The comparison is strictly typed: values of different runtime types are always considered unequal. Cases where the types are known to be different at parse time are considered invalid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + collator: { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + }, + "!=": { + doc: "Returns `true` if the input values are not equal, `false` otherwise. The comparison is strictly typed: values of different runtime types are always considered unequal. Cases where the types are known to be different at parse time are considered invalid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + collator: { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + }, + ">": { + doc: "Returns `true` if the first input is strictly greater than the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + collator: { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + }, + "<": { + doc: "Returns `true` if the first input is strictly less than the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + collator: { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + }, + ">=": { + doc: "Returns `true` if the first input is greater than or equal to the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + collator: { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + }, + "<=": { + doc: "Returns `true` if the first input is less than or equal to the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + collator: { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + }, + all: { + doc: "Returns `true` if all the inputs are `true`, `false` otherwise. The inputs are evaluated in order, and evaluation is short-circuiting: once an input expression evaluates to `false`, the result is `false` and no further input expressions are evaluated.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + any: { + doc: "Returns `true` if any of the inputs are `true`, `false` otherwise. The inputs are evaluated in order, and evaluation is short-circuiting: once an input expression evaluates to `true`, the result is `true` and no further input expressions are evaluated.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "!": { + doc: "Logical negation. Returns `true` if the input is `false`, and `false` if the input is `true`.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + within: { + doc: "Returns `true` if the evaluated feature is fully contained inside a boundary of the input geometry, `false` otherwise. The input value can be a valid GeoJSON of type `Polygon`, `MultiPolygon`, `Feature`, or `FeatureCollection`. Supported features for evaluation:\n- `Point`: Returns `false` if a point is on the boundary or falls outside the boundary.\n- `LineString`: Returns `false` if any part of a line falls outside the boundary, the line intersects the boundary, or a line's endpoint is on the boundary.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "1.9.0", + android: "9.1.0", + ios: "5.8.0", + macos: "0.15.0" + } + } + }, + "is-supported-script": { + doc: "Returns `true` if the input string is expected to render legibly. Returns `false` if the input string contains sections that cannot be rendered without potential loss of meaning (e.g. Indic scripts that require complex text shaping, or right-to-left scripts if the the `mapbox-gl-rtl-text` plugin is not in use in Mapbox GL JS).", + group: "String", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.6.0" + } + } + }, + upcase: { + doc: "Returns the input string converted to uppercase. Follows the Unicode Default Case Conversion algorithm and the locale-insensitive case mappings in the Unicode Character Database.", + group: "String", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + downcase: { + doc: "Returns the input string converted to lowercase. Follows the Unicode Default Case Conversion algorithm and the locale-insensitive case mappings in the Unicode Character Database.", + group: "String", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + concat: { + doc: "Returns a `string` consisting of the concatenation of the inputs. Each input is converted to a string as if by `to-string`.", + group: "String", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "resolved-locale": { + doc: "Returns the IETF language tag of the locale being used by the provided `collator`. This can be used to determine the default system locale, or to determine if a requested locale was successfully loaded.", + group: "String", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + } + } +}; +var light = { + anchor: { + type: "enum", + "default": "viewport", + values: { + map: { + doc: "The position of the light source is aligned to the rotation of the map." + }, + viewport: { + doc: "The position of the light source is aligned to the rotation of the viewport." + } + }, + "property-type": "data-constant", + transition: false, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + doc: "Whether extruded geometries are lit relative to the map or viewport.", + example: "map", + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + } + }, + position: { + type: "array", + "default": [ + 1.15, + 210, + 30 + ], + length: 3, + value: "number", + "property-type": "data-constant", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + doc: "Position of the light source relative to lit (extruded) geometries, in [r radial coordinate, a azimuthal angle, p polar angle] where r indicates the distance from the center of the base of an object to its light, a indicates the position of the light relative to 0° (0° when `light.anchor` is set to `viewport` corresponds to the top of the viewport, or 0° when `light.anchor` is set to `map` corresponds to due north, and degrees proceed clockwise), and p indicates the height of the light (from 0°, directly above, to 180°, directly below).", + example: [ + 1.5, + 90, + 80 + ], + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + } + }, + color: { + type: "color", + "property-type": "data-constant", + "default": "#ffffff", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true, + doc: "Color tint for lighting extruded geometries.", + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + } + }, + intensity: { + type: "number", + "property-type": "data-constant", + "default": 0.5, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true, + doc: "Intensity of lighting (on a scale from 0 to 1). Higher numbers will present as more extreme contrast.", + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + } + } +}; +var paint = [ + "paint_fill", + "paint_line", + "paint_circle", + "paint_heatmap", + "paint_fill-extrusion", + "paint_symbol", + "paint_raster", + "paint_hillshade", + "paint_background" +]; +var paint_fill = { + "fill-antialias": { + type: "boolean", + "default": true, + doc: "Whether or not the fill should be antialiased.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + doc: "The opacity of the entire fill layer. In contrast to the `fill-color`, this value will also affect the 1px stroke around the fill, if the stroke is used.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.21.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-color": { + type: "color", + "default": "#000000", + doc: "The color of the filled part of this layer. This color can be specified as `rgba` with an alpha component and the color's opacity will not affect the opacity of the 1px stroke, if it is used.", + transition: true, + requires: [ + { + "!": "fill-pattern" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.19.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-outline-color": { + type: "color", + doc: "The outline color of the fill. Matches the value of `fill-color` if unspecified.", + transition: true, + requires: [ + { + "!": "fill-pattern" + }, + { + "fill-antialias": true + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.19.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + doc: "The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-translate-anchor": { + type: "enum", + values: { + map: { + doc: "The fill is translated relative to the map." + }, + viewport: { + doc: "The fill is translated relative to the viewport." + } + }, + doc: "Controls the frame of reference for `fill-translate`.", + "default": "map", + requires: [ + "fill-translate" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-pattern": { + type: "resolvedImage", + transition: true, + doc: "Name of image in sprite to use for drawing image fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.49.0", + android: "6.5.0", + macos: "0.11.0", + ios: "4.4.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + } +}; +var paint_line = { + "line-opacity": { + type: "number", + doc: "The opacity at which the line will be drawn.", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-color": { + type: "color", + doc: "The color with which the line will be drawn.", + "default": "#000000", + transition: true, + requires: [ + { + "!": "line-pattern" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.23.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + doc: "The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-translate-anchor": { + type: "enum", + values: { + map: { + doc: "The line is translated relative to the map." + }, + viewport: { + doc: "The line is translated relative to the viewport." + } + }, + doc: "Controls the frame of reference for `line-translate`.", + "default": "map", + requires: [ + "line-translate" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-width": { + type: "number", + "default": 1, + minimum: 0, + transition: true, + units: "pixels", + doc: "Stroke thickness.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.39.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-gap-width": { + type: "number", + "default": 0, + minimum: 0, + doc: "Draws a line casing outside of a line's actual path. Value indicates the width of the inner gap.", + transition: true, + units: "pixels", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-offset": { + type: "number", + "default": 0, + doc: "The line's offset. For linear features, a positive value offsets the line to the right, relative to the direction of the line, and a negative value to the left. For polygon features, a positive value results in an inset, and a negative value results in an outset.", + transition: true, + units: "pixels", + "sdk-support": { + "basic functionality": { + js: "0.12.1", + android: "3.0.0", + ios: "3.1.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + doc: "Blur applied to the line, in pixels.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-dasharray": { + type: "array", + value: "number", + doc: "Specifies the lengths of the alternating dashes and gaps that form the dash pattern. The lengths are later scaled by the line width. To convert a dash length to pixels, multiply the length by the current line width. Note that GeoJSON sources with `lineMetrics: true` specified won't render dashed lines to the expected scale. Also note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + minimum: 0, + transition: true, + units: "line widths", + requires: [ + { + "!": "line-pattern" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "line-pattern": { + type: "resolvedImage", + transition: true, + doc: "Name of image in sprite to use for drawing image lines. For seamless patterns, image width must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.49.0", + android: "6.5.0", + macos: "0.11.0", + ios: "4.4.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "line-gradient": { + type: "color", + doc: "Defines a gradient with which to color a line feature. Can only be used with GeoJSON sources that specify `\"lineMetrics\": true`.", + transition: false, + requires: [ + { + "!": "line-dasharray" + }, + { + "!": "line-pattern" + }, + { + source: "geojson", + has: { + lineMetrics: true + } + } + ], + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.5.0", + ios: "4.4.0", + macos: "0.11.0" + }, + "data-driven styling": { + } + }, + expression: { + interpolated: true, + parameters: [ + "line-progress" + ] + }, + "property-type": "color-ramp" + } +}; +var paint_circle = { + "circle-radius": { + type: "number", + "default": 5, + minimum: 0, + transition: true, + units: "pixels", + doc: "Circle radius.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.18.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-color": { + type: "color", + "default": "#000000", + doc: "The fill color of the circle.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.18.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-blur": { + type: "number", + "default": 0, + doc: "Amount to blur the circle. 1 blurs the circle such that only the centerpoint is full opacity.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.20.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-opacity": { + type: "number", + doc: "The opacity at which the circle will be drawn.", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.20.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + doc: "The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-translate-anchor": { + type: "enum", + values: { + map: { + doc: "The circle is translated relative to the map." + }, + viewport: { + doc: "The circle is translated relative to the viewport." + } + }, + doc: "Controls the frame of reference for `circle-translate`.", + "default": "map", + requires: [ + "circle-translate" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-scale": { + type: "enum", + values: { + map: { + doc: "Circles are scaled according to their apparent distance to the camera." + }, + viewport: { + doc: "Circles are not scaled." + } + }, + "default": "map", + doc: "Controls the scaling behavior of the circle when the map is pitched.", + "sdk-support": { + "basic functionality": { + js: "0.21.0", + android: "4.2.0", + ios: "3.4.0", + macos: "0.2.1" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-alignment": { + type: "enum", + values: { + map: { + doc: "The circle is aligned to the plane of the map." + }, + viewport: { + doc: "The circle is aligned to the plane of the viewport." + } + }, + "default": "viewport", + doc: "Orientation of circle when map is pitched.", + "sdk-support": { + "basic functionality": { + js: "0.39.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-stroke-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + doc: "The width of the circle's stroke. Strokes are placed outside of the `circle-radius`.", + "sdk-support": { + "basic functionality": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-color": { + type: "color", + "default": "#000000", + doc: "The stroke color of the circle.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-opacity": { + type: "number", + doc: "The opacity of the circle's stroke.", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + } +}; +var paint_heatmap = { + "heatmap-radius": { + type: "number", + "default": 30, + minimum: 1, + transition: true, + units: "pixels", + doc: "Radius of influence of one heatmap point in pixels. Increasing the value makes the heatmap smoother, but less detailed.", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + "data-driven styling": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-weight": { + type: "number", + "default": 1, + minimum: 0, + transition: false, + doc: "A measure of how much an individual point contributes to the heatmap. A value of 10 would be equivalent to having 10 points of weight 1 in the same spot. Especially useful when combined with clustering.", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + "data-driven styling": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-intensity": { + type: "number", + "default": 1, + minimum: 0, + transition: true, + doc: "Similar to `heatmap-weight` but controls the intensity of the heatmap globally. Primarily used for adjusting the heatmap based on zoom level.", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "heatmap-color": { + type: "color", + "default": [ + "interpolate", + [ + "linear" + ], + [ + "heatmap-density" + ], + 0, + "rgba(0, 0, 255, 0)", + 0.1, + "royalblue", + 0.3, + "cyan", + 0.5, + "lime", + 0.7, + "yellow", + 1, + "red" + ], + doc: "Defines the color of each pixel based on its density value in a heatmap. Should be an expression that uses `[\"heatmap-density\"]` as input.", + transition: false, + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + "data-driven styling": { + } + }, + expression: { + interpolated: true, + parameters: [ + "heatmap-density" + ] + }, + "property-type": "color-ramp" + }, + "heatmap-opacity": { + type: "number", + doc: "The global opacity at which the heatmap layer will be drawn.", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_symbol = { + "icon-opacity": { + doc: "The opacity at which the icon will be drawn.", + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-color": { + type: "color", + "default": "#000000", + transition: true, + doc: "The color of the icon. This can only be used with sdf icons.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-color": { + type: "color", + "default": "rgba(0, 0, 0, 0)", + transition: true, + doc: "The color of the icon's halo. Icon halos can only be used with SDF icons.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + doc: "Distance of halo to the icon outline.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + doc: "Fade out the halo towards the outside.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + doc: "Distance that the icon's anchor is moved from its original placement. Positive values indicate right and down, while negative values indicate left and up.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-translate-anchor": { + type: "enum", + values: { + map: { + doc: "Icons are translated relative to the map." + }, + viewport: { + doc: "Icons are translated relative to the viewport." + } + }, + doc: "Controls the frame of reference for `icon-translate`.", + "default": "map", + requires: [ + "icon-image", + "icon-translate" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-opacity": { + type: "number", + doc: "The opacity at which the text will be drawn.", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-color": { + type: "color", + doc: "The color with which the text will be drawn.", + "default": "#000000", + transition: true, + overridable: true, + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-color": { + type: "color", + "default": "rgba(0, 0, 0, 0)", + transition: true, + doc: "The color of the text's halo, which helps it stand out from backgrounds.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + doc: "Distance of halo to the font outline. Max text halo width is 1/4 of the font-size.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + doc: "The halo's fadeout distance towards the outside.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + doc: "Distance that the text's anchor is moved from its original placement. Positive values indicate right and down, while negative values indicate left and up.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-translate-anchor": { + type: "enum", + values: { + map: { + doc: "The text is translated relative to the map." + }, + viewport: { + doc: "The text is translated relative to the viewport." + } + }, + doc: "Controls the frame of reference for `text-translate`.", + "default": "map", + requires: [ + "text-field", + "text-translate" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_raster = { + "raster-opacity": { + type: "number", + doc: "The opacity at which the image will be drawn.", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-hue-rotate": { + type: "number", + "default": 0, + period: 360, + transition: true, + units: "degrees", + doc: "Rotates hues around the color wheel.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-min": { + type: "number", + doc: "Increase or reduce the brightness of the image. The value is the minimum brightness.", + "default": 0, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-max": { + type: "number", + doc: "Increase or reduce the brightness of the image. The value is the maximum brightness.", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-saturation": { + type: "number", + doc: "Increase or reduce the saturation of the image.", + "default": 0, + minimum: -1, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-contrast": { + type: "number", + doc: "Increase or reduce the contrast of the image.", + "default": 0, + minimum: -1, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-resampling": { + type: "enum", + doc: "The resampling/interpolation method to use for overscaling, also known as texture magnification filter", + values: { + linear: { + doc: "(Bi)linear filtering interpolates pixel values using the weighted average of the four closest original source pixels creating a smooth but blurry look when overscaled" + }, + nearest: { + doc: "Nearest neighbor filtering interpolates pixel values using the nearest original source pixel creating a sharp but pixelated look when overscaled" + } + }, + "default": "linear", + "sdk-support": { + "basic functionality": { + js: "0.47.0", + android: "6.3.0", + ios: "4.2.0", + macos: "0.9.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-fade-duration": { + type: "number", + "default": 300, + minimum: 0, + transition: false, + units: "milliseconds", + doc: "Fade duration when a new tile is added.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_hillshade = { + "hillshade-illumination-direction": { + type: "number", + "default": 335, + minimum: 0, + maximum: 359, + doc: "The direction of the light source used to generate the hillshading with 0 as the top of the viewport if `hillshade-illumination-anchor` is set to `viewport` and due north if `hillshade-illumination-anchor` is set to `map`.", + transition: false, + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-illumination-anchor": { + type: "enum", + values: { + map: { + doc: "The hillshade illumination is relative to the north direction." + }, + viewport: { + doc: "The hillshade illumination is relative to the top of the viewport." + } + }, + "default": "viewport", + doc: "Direction of light source when map is rotated.", + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-exaggeration": { + type: "number", + doc: "Intensity of the hillshade", + "default": 0.5, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-shadow-color": { + type: "color", + "default": "#000000", + doc: "The shading color of areas that face away from the light source.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-highlight-color": { + type: "color", + "default": "#FFFFFF", + doc: "The shading color of areas that faces towards the light source.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-accent-color": { + type: "color", + "default": "#000000", + doc: "The shading color used to accentuate rugged terrain like sharp cliffs and gorges.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var paint_background = { + "background-color": { + type: "color", + "default": "#000000", + doc: "The color with which the background will be drawn.", + transition: true, + requires: [ + { + "!": "background-pattern" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "background-pattern": { + type: "resolvedImage", + transition: true, + doc: "Name of image in sprite to use for drawing an image background. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "background-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + doc: "The opacity at which the background will be drawn.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}; +var transition = { + duration: { + type: "number", + "default": 300, + minimum: 0, + units: "milliseconds", + doc: "Time allotted for transitions to complete." + }, + delay: { + type: "number", + "default": 0, + minimum: 0, + units: "milliseconds", + doc: "Length of time before a transition begins." + } +}; +var promoteId = { + "*": { + type: "string", + doc: "A name of a feature property to use as ID for feature state." + } +}; +var v8 = { + $version: $version, + $root: $root, + sources: sources, + source: source, + source_vector: source_vector, + source_raster: source_raster, + source_raster_dem: source_raster_dem, + source_geojson: source_geojson, + source_video: source_video, + source_image: source_image, + layer: layer, + layout: layout, + layout_background: layout_background, + layout_fill: layout_fill, + layout_circle: layout_circle, + layout_heatmap: layout_heatmap, + "layout_fill-extrusion": { + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + "property-type": "constant" + } +}, + layout_line: layout_line, + layout_symbol: layout_symbol, + layout_raster: layout_raster, + layout_hillshade: layout_hillshade, + filter: filter, + filter_operator: filter_operator, + geometry_type: geometry_type, + "function": { + expression: { + type: "expression", + doc: "An expression." + }, + stops: { + type: "array", + doc: "An array of stops.", + value: "function_stop" + }, + base: { + type: "number", + "default": 1, + minimum: 0, + doc: "The exponential base of the interpolation curve. It controls the rate at which the result increases. Higher values make the result increase more towards the high end of the range. With `1` the stops are interpolated linearly." + }, + property: { + type: "string", + doc: "The name of a feature property to use as the function input.", + "default": "$zoom" + }, + type: { + type: "enum", + values: { + identity: { + doc: "Return the input value as the output value." + }, + exponential: { + doc: "Generate an output by interpolating between stops just less than and just greater than the function input." + }, + interval: { + doc: "Return the output value of the stop just less than the function input." + }, + categorical: { + doc: "Return the output value of the stop equal to the function input." + } + }, + doc: "The interpolation strategy to use in function evaluation.", + "default": "exponential" + }, + colorSpace: { + type: "enum", + values: { + rgb: { + doc: "Use the RGB color space to interpolate color values" + }, + lab: { + doc: "Use the LAB color space to interpolate color values." + }, + hcl: { + doc: "Use the HCL color space to interpolate color values, interpolating the Hue, Chroma, and Luminance channels individually." + } + }, + doc: "The color space in which colors interpolated. Interpolating colors in perceptual color spaces like LAB and HCL tend to produce color ramps that look more consistent and produce colors that can be differentiated more easily than those interpolated in RGB space.", + "default": "rgb" + }, + "default": { + type: "*", + required: false, + doc: "A value to serve as a fallback function result when a value isn't otherwise available. It is used in the following circumstances:\n* In categorical functions, when the feature value does not match any of the stop domain values.\n* In property and zoom-and-property functions, when a feature does not contain a value for the specified property.\n* In identity functions, when the feature value is not valid for the style property (for example, if the function is being used for a `circle-color` property but the feature property value is not a string or not a valid color).\n* In interval or exponential property and zoom-and-property functions, when the feature value is not numeric.\nIf no default is provided, the style property's default is used in these circumstances." + } +}, + function_stop: function_stop, + expression: expression, + expression_name: expression_name, + light: light, + paint: paint, + paint_fill: paint_fill, + "paint_fill-extrusion": { + "fill-extrusion-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + doc: "The opacity of the entire fill extrusion layer. This is rendered on a per-layer, not per-feature, basis, and data-driven styling is not available.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-color": { + type: "color", + "default": "#000000", + doc: "The base color of the extruded fill. The extrusion's surfaces will be shaded differently based on this color in combination with the root `light` settings. If this color is specified as `rgba` with an alpha component, the alpha component will be ignored; use `fill-extrusion-opacity` to set layer opacity.", + transition: true, + requires: [ + { + "!": "fill-extrusion-pattern" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + }, + "data-driven styling": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + doc: "The geometry's offset. Values are [x, y] where negatives indicate left and up (on the flat plane), respectively.", + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-translate-anchor": { + type: "enum", + values: { + map: { + doc: "The fill extrusion is translated relative to the map." + }, + viewport: { + doc: "The fill extrusion is translated relative to the viewport." + } + }, + doc: "Controls the frame of reference for `fill-extrusion-translate`.", + "default": "map", + requires: [ + "fill-extrusion-translate" + ], + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-pattern": { + type: "resolvedImage", + transition: true, + doc: "Name of image in sprite to use for drawing images on extruded fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + }, + "data-driven styling": { + js: "0.49.0", + android: "6.5.0", + macos: "0.11.0", + ios: "4.4.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "fill-extrusion-height": { + type: "number", + "default": 0, + minimum: 0, + units: "meters", + doc: "The height with which to extrude this layer.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + }, + "data-driven styling": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-base": { + type: "number", + "default": 0, + minimum: 0, + units: "meters", + doc: "The height with which to extrude the base of this layer. Must be less than or equal to `fill-extrusion-height`.", + transition: true, + requires: [ + "fill-extrusion-height" + ], + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + }, + "data-driven styling": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-vertical-gradient": { + type: "boolean", + "default": true, + doc: "Whether to apply a vertical gradient to the sides of a fill-extrusion layer. If true, sides will be shaded slightly darker farther down.", + transition: false, + "sdk-support": { + "basic functionality": { + js: "0.50.0", + ios: "4.7.0", + macos: "0.13.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } +}, + paint_line: paint_line, + paint_circle: paint_circle, + paint_heatmap: paint_heatmap, + paint_symbol: paint_symbol, + paint_raster: paint_raster, + paint_hillshade: paint_hillshade, + paint_background: paint_background, + transition: transition, + "property-type": { + "data-driven": { + type: "property-type", + doc: "Property is interpolable and can be represented using a property expression." + }, + "cross-faded": { + type: "property-type", + doc: "Property is non-interpolable; rather, its values will be cross-faded to smoothly transition between integer zooms." + }, + "cross-faded-data-driven": { + type: "property-type", + doc: "Property is non-interpolable; rather, its values will be cross-faded to smoothly transition between integer zooms. It can be represented using a property expression." + }, + "color-ramp": { + type: "property-type", + doc: "Property should be specified using a color ramp from which the output color can be sampled based on a property calculation." + }, + "data-constant": { + type: "property-type", + doc: "Property is interpolable but cannot be represented using a property expression." + }, + constant: { + type: "property-type", + doc: "Property is constant across all zoom levels and property values." + } +}, + promoteId: promoteId +}; + +// Note: This regex matches even invalid JSON strings, but since we’re +// working on the output of `JSON.stringify` we know that only valid strings +// are present (unless the user supplied a weird `options.indent` but in +// that case we don’t care since the output would be invalid anyway). +var stringOrChar = /("(?:[^\\"]|\\.)*")|[:,]/g; + +var jsonStringifyPrettyCompact = function stringify(passedObj, options) { + var indent, maxLength, replacer; + + options = options || {}; + indent = JSON.stringify( + [1], + undefined, + options.indent === undefined ? 2 : options.indent + ).slice(2, -3); + maxLength = + indent === "" + ? Infinity + : options.maxLength === undefined + ? 80 + : options.maxLength; + replacer = options.replacer; + + return (function _stringify(obj, currentIndent, reserved) { + // prettier-ignore + var end, index, items, key, keyPart, keys, length, nextIndent, prettified, start, string, value; + + if (obj && typeof obj.toJSON === "function") { + obj = obj.toJSON(); + } + + string = JSON.stringify(obj, replacer); + + if (string === undefined) { + return string; + } + + length = maxLength - currentIndent.length - reserved; + + if (string.length <= length) { + prettified = string.replace(stringOrChar, function(match, stringLiteral) { + return stringLiteral || match + " "; + }); + if (prettified.length <= length) { + return prettified; + } + } + + if (replacer != null) { + obj = JSON.parse(string); + replacer = undefined; + } + + if (typeof obj === "object" && obj !== null) { + nextIndent = currentIndent + indent; + items = []; + index = 0; + + if (Array.isArray(obj)) { + start = "["; + end = "]"; + length = obj.length; + for (; index < length; index++) { + items.push( + _stringify(obj[index], nextIndent, index === length - 1 ? 0 : 1) || + "null" + ); + } + } else { + start = "{"; + end = "}"; + keys = Object.keys(obj); + length = keys.length; + for (; index < length; index++) { + key = keys[index]; + keyPart = JSON.stringify(key) + ": "; + value = _stringify( + obj[key], + nextIndent, + keyPart.length + (index === length - 1 ? 0 : 1) + ); + if (value !== undefined) { + items.push(keyPart + value); + } + } + } + + if (items.length > 0) { + return [start, indent + items.join(",\n" + nextIndent), end].join( + "\n" + currentIndent + ); + } + } + + return string; + })(passedObj, "", 0); +}; + +function sortKeysBy(obj, reference) { + var result = {}; + for (var key in reference) { + if (obj[key] !== undefined) { + result[key] = obj[key]; + } + } + for (var key$1 in obj) { + if (result[key$1] === undefined) { + result[key$1] = obj[key$1]; + } + } + return result; +} +function format(style, space) { + if (space === void 0) + space = 2; + style = sortKeysBy(style, v8.$root); + if (style.layers) { + style.layers = style.layers.map(function (layer) { + return sortKeysBy(layer, v8.layer); + }); + } + return jsonStringifyPrettyCompact(style, { indent: space }); +} + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); +} + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var punycode = createCommonjsModule(function (module, exports) { +(function(root) { + + /** Detect free variables */ + var freeExports = exports && + !exports.nodeType && exports; + var freeModule = module && + !module.nodeType && module; + var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * http://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if (freeExports && freeModule) { + if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { // in Rhino or a web browser + root.punycode = punycode; + } + +}(commonjsGlobal)); +}); + +var util = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +// Copyright Joyent, Inc. and other Node contributors. + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var decode = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (Array.isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +// Copyright Joyent, Inc. and other Node contributors. + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +var encode = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return Object.keys(obj).map(function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (Array.isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) { return ''; } + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var querystring = createCommonjsModule(function (module, exports) { + +exports.decode = exports.parse = decode; +exports.encode = exports.stringify = encode; +}); +var querystring_1 = querystring.decode; +var querystring_2 = querystring.parse; +var querystring_3 = querystring.encode; +var querystring_4 = querystring.stringify; + +var parse = urlParse; +var resolve = urlResolve; +var resolveObject = urlResolveObject; +var format$1 = urlFormat; + +var Url_1 = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }; + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) { return url; } + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + { hostEnd = hec; } + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + { hostEnd = hec; } + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + { hostEnd = rest.length; } + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) { continue; } + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + { continue; } + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) { this.pathname = rest; } + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) { obj = urlParse(obj); } + if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); } + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; } + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; } + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; } + if (search && search.charAt(0) !== '?') { search = '?' + search; } + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) { return relative; } + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + { result[rkey] = relative[rkey]; } + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())){ } + if (!relative.host) { relative.host = ''; } + if (!relative.hostname) { relative.hostname = ''; } + if (relPath[0] !== '') { relPath.unshift(''); } + if (relPath.length < 2) { relPath.unshift(''); } + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') { srcPath[0] = result.host; } + else { srcPath.unshift(result.host); } + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') { relPath[0] = relative.host; } + else { relPath.unshift(relative.host); } + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) { srcPath = []; } + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) { this.hostname = host; } +}; + +var url = { + parse: parse, + resolve: resolve, + resolveObject: resolveObject, + format: format$1, + Url: Url_1 +}; + +function getPropertyReference(propertyName) { + for (var i = 0; i < v8.layout.length; i++) { + for (var key in v8[v8.layout[i]]) { + if (key === propertyName) { + return v8[v8.layout[i]][key]; + } + } + } + for (var i$1 = 0; i$1 < v8.paint.length; i$1++) { + for (var key$1 in v8[v8.paint[i$1]]) { + if (key$1 === propertyName) { + return v8[v8.paint[i$1]][key$1]; + } + } + } + return null; +} +function eachSource(style, callback) { + for (var k in style.sources) { + callback(style.sources[k]); + } +} +function eachLayer(style, callback) { + for (var i = 0, list = style.layers; i < list.length; i += 1) { + var layer = list[i]; + callback(layer); + } +} +function eachProperty(style, options, callback) { + function inner(layer, propertyType) { + var properties = layer[propertyType]; + if (!properties) { + return; + } + Object.keys(properties).forEach(function (key) { + callback({ + path: [ + layer.id, + propertyType, + key + ], + key: key, + value: properties[key], + reference: getPropertyReference(key), + set: function set(x) { + properties[key] = x; + } + }); + }); + } + eachLayer(style, function (layer) { + if (options.paint) { + inner(layer, 'paint'); + } + if (options.layout) { + inner(layer, 'layout'); + } + }); +} + +function eachLayout(layer, callback) { + for (var k in layer) { + if (k.indexOf('layout') === 0) { + callback(layer[k], k); + } + } +} +function eachPaint(layer, callback) { + for (var k in layer) { + if (k.indexOf('paint') === 0) { + callback(layer[k], k); + } + } +} +function resolveConstant(style, value) { + if (typeof value === 'string' && value[0] === '@') { + return resolveConstant(style, style.constants[value]); + } else { + return value; + } +} +function isFunction(value) { + return Array.isArray(value.stops); +} +function renameProperty(obj, from, to) { + obj[to] = obj[from]; + delete obj[from]; +} +function migrateToV8 (style) { + style.version = 8; + eachSource(style, function (source) { + if (source.type === 'video' && source.url !== undefined) { + renameProperty(source, 'url', 'urls'); + } + if (source.type === 'video') { + source.coordinates.forEach(function (coord) { + return coord.reverse(); + }); + } + }); + eachLayer(style, function (layer) { + eachLayout(layer, function (layout) { + if (layout['symbol-min-distance'] !== undefined) { + renameProperty(layout, 'symbol-min-distance', 'symbol-spacing'); + } + }); + eachPaint(layer, function (paint) { + if (paint['background-image'] !== undefined) { + renameProperty(paint, 'background-image', 'background-pattern'); + } + if (paint['line-image'] !== undefined) { + renameProperty(paint, 'line-image', 'line-pattern'); + } + if (paint['fill-image'] !== undefined) { + renameProperty(paint, 'fill-image', 'fill-pattern'); + } + }); + }); + eachProperty(style, { + paint: true, + layout: true + }, function (property) { + var value = resolveConstant(style, property.value); + if (isFunction(value)) { + value.stops.forEach(function (stop) { + stop[1] = resolveConstant(style, stop[1]); + }); + } + property.set(value); + }); + delete style.constants; + eachLayer(style, function (layer) { + eachLayout(layer, function (layout) { + delete layout['text-max-size']; + delete layout['icon-max-size']; + }); + eachPaint(layer, function (paint) { + if (paint['text-size']) { + if (!layer.layout) { + layer.layout = {}; + } + layer.layout['text-size'] = paint['text-size']; + delete paint['text-size']; + } + if (paint['icon-size']) { + if (!layer.layout) { + layer.layout = {}; + } + layer.layout['icon-size'] = paint['icon-size']; + delete paint['icon-size']; + } + }); + }); + function migrateFontstackURL(input) { + var inputParsed = url.parse(input); + var inputPathnameParts = inputParsed.pathname.split('/'); + if (inputParsed.protocol !== 'mapbox:') { + return input; + } else if (inputParsed.hostname === 'fontstack') { + return 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf'; + } else if (inputParsed.hostname === 'fonts') { + return 'mapbox://fonts/' + inputPathnameParts[2] + '/{fontstack}/{range}.pbf'; + } + } + if (style.glyphs) { + style.glyphs = migrateFontstackURL(style.glyphs); + } + function migrateFontStack(font) { + function splitAndTrim(string) { + return string.split(',').map(function (s) { + return s.trim(); + }); + } + if (Array.isArray(font)) { + return font; + } else if (typeof font === 'string') { + return splitAndTrim(font); + } else if (typeof font === 'object') { + font.stops.forEach(function (stop) { + stop[1] = splitAndTrim(stop[1]); + }); + return font; + } else { + throw new Error('unexpected font value'); + } + } + eachLayer(style, function (layer) { + eachLayout(layer, function (layout) { + if (layout['text-font']) { + layout['text-font'] = migrateFontStack(layout['text-font']); + } + }); + }); + var firstSymbolLayer = 0; + for (var i = style.layers.length - 1; i >= 0; i--) { + var layer = style.layers[i]; + if (layer.type !== 'symbol') { + firstSymbolLayer = i + 1; + break; + } + } + var symbolLayers = style.layers.splice(firstSymbolLayer); + symbolLayers.reverse(); + style.layers = style.layers.concat(symbolLayers); + return style; +} + +function extend (output) { + var inputs = [], len = arguments.length - 1; + while (len-- > 0) + inputs[len] = arguments[len + 1]; + for (var i = 0, list = inputs; i < list.length; i += 1) { + var input = list[i]; + for (var k in input) { + output[k] = input[k]; + } + } + return output; +} + +var ParsingError = function (Error) { + function ParsingError(key, message) { + Error.call(this, message); + this.message = message; + this.key = key; + } + if (Error) + ParsingError.__proto__ = Error; + ParsingError.prototype = Object.create(Error && Error.prototype); + ParsingError.prototype.constructor = ParsingError; + return ParsingError; +}(Error); + +var Scope = function Scope(parent, bindings) { + if (bindings === void 0) + bindings = []; + this.parent = parent; + this.bindings = {}; + for (var i = 0, list = bindings; i < list.length; i += 1) { + var ref = list[i]; + var name = ref[0]; + var expression = ref[1]; + this.bindings[name] = expression; + } +}; +Scope.prototype.concat = function concat(bindings) { + return new Scope(this, bindings); +}; +Scope.prototype.get = function get(name) { + if (this.bindings[name]) { + return this.bindings[name]; + } + if (this.parent) { + return this.parent.get(name); + } + throw new Error(name + ' not found in scope.'); +}; +Scope.prototype.has = function has(name) { + if (this.bindings[name]) { + return true; + } + return this.parent ? this.parent.has(name) : false; +}; + +var NullType = { kind: 'null' }; +var NumberType = { kind: 'number' }; +var StringType = { kind: 'string' }; +var BooleanType = { kind: 'boolean' }; +var ColorType = { kind: 'color' }; +var ObjectType = { kind: 'object' }; +var ValueType = { kind: 'value' }; +var ErrorType = { kind: 'error' }; +var CollatorType = { kind: 'collator' }; +var FormattedType = { kind: 'formatted' }; +var ResolvedImageType = { kind: 'resolvedImage' }; +function array(itemType, N) { + return { + kind: 'array', + itemType: itemType, + N: N + }; +} +function toString(type) { + if (type.kind === 'array') { + var itemType = toString(type.itemType); + return typeof type.N === 'number' ? 'array<' + itemType + ', ' + type.N + '>' : type.itemType.kind === 'value' ? 'array' : 'array<' + itemType + '>'; + } else { + return type.kind; + } +} +var valueMemberTypes = [ + NullType, + NumberType, + StringType, + BooleanType, + ColorType, + FormattedType, + ObjectType, + array(ValueType), + ResolvedImageType +]; +function checkSubtype(expected, t) { + if (t.kind === 'error') { + return null; + } else if (expected.kind === 'array') { + if (t.kind === 'array' && (t.N === 0 && t.itemType.kind === 'value' || !checkSubtype(expected.itemType, t.itemType)) && (typeof expected.N !== 'number' || expected.N === t.N)) { + return null; + } + } else if (expected.kind === t.kind) { + return null; + } else if (expected.kind === 'value') { + for (var i = 0, list = valueMemberTypes; i < list.length; i += 1) { + var memberType = list[i]; + if (!checkSubtype(memberType, t)) { + return null; + } + } + } + return 'Expected ' + toString(expected) + ' but found ' + toString(t) + ' instead.'; +} +function isValidType(provided, allowedTypes) { + return allowedTypes.some(function (t) { + return t.kind === provided.kind; + }); +} +function isValidNativeType(provided, allowedTypes) { + return allowedTypes.some(function (t) { + if (t === 'null') { + return provided === null; + } else if (t === 'array') { + return Array.isArray(provided); + } else if (t === 'object') { + return provided && !Array.isArray(provided) && typeof provided === 'object'; + } else { + return t === typeof provided; + } + }); +} + +var csscolorparser = createCommonjsModule(function (module, exports) { +// (c) Dean McNamee , 2012. +// +// https://github.com/deanm/css-color-parser-js +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. + +// http://www.w3.org/TR/css3-color/ +var kCSSColorTable = { + "transparent": [0,0,0,0], "aliceblue": [240,248,255,1], + "antiquewhite": [250,235,215,1], "aqua": [0,255,255,1], + "aquamarine": [127,255,212,1], "azure": [240,255,255,1], + "beige": [245,245,220,1], "bisque": [255,228,196,1], + "black": [0,0,0,1], "blanchedalmond": [255,235,205,1], + "blue": [0,0,255,1], "blueviolet": [138,43,226,1], + "brown": [165,42,42,1], "burlywood": [222,184,135,1], + "cadetblue": [95,158,160,1], "chartreuse": [127,255,0,1], + "chocolate": [210,105,30,1], "coral": [255,127,80,1], + "cornflowerblue": [100,149,237,1], "cornsilk": [255,248,220,1], + "crimson": [220,20,60,1], "cyan": [0,255,255,1], + "darkblue": [0,0,139,1], "darkcyan": [0,139,139,1], + "darkgoldenrod": [184,134,11,1], "darkgray": [169,169,169,1], + "darkgreen": [0,100,0,1], "darkgrey": [169,169,169,1], + "darkkhaki": [189,183,107,1], "darkmagenta": [139,0,139,1], + "darkolivegreen": [85,107,47,1], "darkorange": [255,140,0,1], + "darkorchid": [153,50,204,1], "darkred": [139,0,0,1], + "darksalmon": [233,150,122,1], "darkseagreen": [143,188,143,1], + "darkslateblue": [72,61,139,1], "darkslategray": [47,79,79,1], + "darkslategrey": [47,79,79,1], "darkturquoise": [0,206,209,1], + "darkviolet": [148,0,211,1], "deeppink": [255,20,147,1], + "deepskyblue": [0,191,255,1], "dimgray": [105,105,105,1], + "dimgrey": [105,105,105,1], "dodgerblue": [30,144,255,1], + "firebrick": [178,34,34,1], "floralwhite": [255,250,240,1], + "forestgreen": [34,139,34,1], "fuchsia": [255,0,255,1], + "gainsboro": [220,220,220,1], "ghostwhite": [248,248,255,1], + "gold": [255,215,0,1], "goldenrod": [218,165,32,1], + "gray": [128,128,128,1], "green": [0,128,0,1], + "greenyellow": [173,255,47,1], "grey": [128,128,128,1], + "honeydew": [240,255,240,1], "hotpink": [255,105,180,1], + "indianred": [205,92,92,1], "indigo": [75,0,130,1], + "ivory": [255,255,240,1], "khaki": [240,230,140,1], + "lavender": [230,230,250,1], "lavenderblush": [255,240,245,1], + "lawngreen": [124,252,0,1], "lemonchiffon": [255,250,205,1], + "lightblue": [173,216,230,1], "lightcoral": [240,128,128,1], + "lightcyan": [224,255,255,1], "lightgoldenrodyellow": [250,250,210,1], + "lightgray": [211,211,211,1], "lightgreen": [144,238,144,1], + "lightgrey": [211,211,211,1], "lightpink": [255,182,193,1], + "lightsalmon": [255,160,122,1], "lightseagreen": [32,178,170,1], + "lightskyblue": [135,206,250,1], "lightslategray": [119,136,153,1], + "lightslategrey": [119,136,153,1], "lightsteelblue": [176,196,222,1], + "lightyellow": [255,255,224,1], "lime": [0,255,0,1], + "limegreen": [50,205,50,1], "linen": [250,240,230,1], + "magenta": [255,0,255,1], "maroon": [128,0,0,1], + "mediumaquamarine": [102,205,170,1], "mediumblue": [0,0,205,1], + "mediumorchid": [186,85,211,1], "mediumpurple": [147,112,219,1], + "mediumseagreen": [60,179,113,1], "mediumslateblue": [123,104,238,1], + "mediumspringgreen": [0,250,154,1], "mediumturquoise": [72,209,204,1], + "mediumvioletred": [199,21,133,1], "midnightblue": [25,25,112,1], + "mintcream": [245,255,250,1], "mistyrose": [255,228,225,1], + "moccasin": [255,228,181,1], "navajowhite": [255,222,173,1], + "navy": [0,0,128,1], "oldlace": [253,245,230,1], + "olive": [128,128,0,1], "olivedrab": [107,142,35,1], + "orange": [255,165,0,1], "orangered": [255,69,0,1], + "orchid": [218,112,214,1], "palegoldenrod": [238,232,170,1], + "palegreen": [152,251,152,1], "paleturquoise": [175,238,238,1], + "palevioletred": [219,112,147,1], "papayawhip": [255,239,213,1], + "peachpuff": [255,218,185,1], "peru": [205,133,63,1], + "pink": [255,192,203,1], "plum": [221,160,221,1], + "powderblue": [176,224,230,1], "purple": [128,0,128,1], + "rebeccapurple": [102,51,153,1], + "red": [255,0,0,1], "rosybrown": [188,143,143,1], + "royalblue": [65,105,225,1], "saddlebrown": [139,69,19,1], + "salmon": [250,128,114,1], "sandybrown": [244,164,96,1], + "seagreen": [46,139,87,1], "seashell": [255,245,238,1], + "sienna": [160,82,45,1], "silver": [192,192,192,1], + "skyblue": [135,206,235,1], "slateblue": [106,90,205,1], + "slategray": [112,128,144,1], "slategrey": [112,128,144,1], + "snow": [255,250,250,1], "springgreen": [0,255,127,1], + "steelblue": [70,130,180,1], "tan": [210,180,140,1], + "teal": [0,128,128,1], "thistle": [216,191,216,1], + "tomato": [255,99,71,1], "turquoise": [64,224,208,1], + "violet": [238,130,238,1], "wheat": [245,222,179,1], + "white": [255,255,255,1], "whitesmoke": [245,245,245,1], + "yellow": [255,255,0,1], "yellowgreen": [154,205,50,1]}; + +function clamp_css_byte(i) { // Clamp to integer 0 .. 255. + i = Math.round(i); // Seems to be what Chrome does (vs truncation). + return i < 0 ? 0 : i > 255 ? 255 : i; +} + +function clamp_css_float(f) { // Clamp to float 0.0 .. 1.0. + return f < 0 ? 0 : f > 1 ? 1 : f; +} + +function parse_css_int(str) { // int or percentage. + if (str[str.length - 1] === '%') + { return clamp_css_byte(parseFloat(str) / 100 * 255); } + return clamp_css_byte(parseInt(str)); +} + +function parse_css_float(str) { // float or percentage. + if (str[str.length - 1] === '%') + { return clamp_css_float(parseFloat(str) / 100); } + return clamp_css_float(parseFloat(str)); +} + +function css_hue_to_rgb(m1, m2, h) { + if (h < 0) { h += 1; } + else if (h > 1) { h -= 1; } + + if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; } + if (h * 2 < 1) { return m2; } + if (h * 3 < 2) { return m1 + (m2 - m1) * (2/3 - h) * 6; } + return m1; +} + +function parseCSSColor(css_str) { + // Remove all whitespace, not compliant, but should just be more accepting. + var str = css_str.replace(/ /g, '').toLowerCase(); + + // Color keywords (and transparent) lookup. + if (str in kCSSColorTable) { return kCSSColorTable[str].slice(); } // dup. + + // #abc and #abc123 syntax. + if (str[0] === '#') { + if (str.length === 4) { + var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. + if (!(iv >= 0 && iv <= 0xfff)) { return null; } // Covers NaN. + return [((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8), + (iv & 0xf0) | ((iv & 0xf0) >> 4), + (iv & 0xf) | ((iv & 0xf) << 4), + 1]; + } else if (str.length === 7) { + var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. + if (!(iv >= 0 && iv <= 0xffffff)) { return null; } // Covers NaN. + return [(iv & 0xff0000) >> 16, + (iv & 0xff00) >> 8, + iv & 0xff, + 1]; + } + + return null; + } + + var op = str.indexOf('('), ep = str.indexOf(')'); + if (op !== -1 && ep + 1 === str.length) { + var fname = str.substr(0, op); + var params = str.substr(op+1, ep-(op+1)).split(','); + var alpha = 1; // To allow case fallthrough. + switch (fname) { + case 'rgba': + if (params.length !== 4) { return null; } + alpha = parse_css_float(params.pop()); + // Fall through. + case 'rgb': + if (params.length !== 3) { return null; } + return [parse_css_int(params[0]), + parse_css_int(params[1]), + parse_css_int(params[2]), + alpha]; + case 'hsla': + if (params.length !== 4) { return null; } + alpha = parse_css_float(params.pop()); + // Fall through. + case 'hsl': + if (params.length !== 3) { return null; } + var h = (((parseFloat(params[0]) % 360) + 360) % 360) / 360; // 0 .. 1 + // NOTE(deanm): According to the CSS spec s/l should only be + // percentages, but we don't bother and let float or percentage. + var s = parse_css_float(params[1]); + var l = parse_css_float(params[2]); + var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; + var m1 = l * 2 - m2; + return [clamp_css_byte(css_hue_to_rgb(m1, m2, h+1/3) * 255), + clamp_css_byte(css_hue_to_rgb(m1, m2, h) * 255), + clamp_css_byte(css_hue_to_rgb(m1, m2, h-1/3) * 255), + alpha]; + default: + return null; + } + } + + return null; +} + +try { exports.parseCSSColor = parseCSSColor; } catch(e) { } +}); +var csscolorparser_1 = csscolorparser.parseCSSColor; + +var Color = function Color(r, g, b, a) { + if (a === void 0) + a = 1; + this.r = r; + this.g = g; + this.b = b; + this.a = a; +}; +Color.parse = function parse(input) { + if (!input) { + return undefined; + } + if (input instanceof Color) { + return input; + } + if (typeof input !== 'string') { + return undefined; + } + var rgba = csscolorparser_1(input); + if (!rgba) { + return undefined; + } + return new Color(rgba[0] / 255 * rgba[3], rgba[1] / 255 * rgba[3], rgba[2] / 255 * rgba[3], rgba[3]); +}; +Color.prototype.toString = function toString() { + var ref = this.toArray(); + var r = ref[0]; + var g = ref[1]; + var b = ref[2]; + var a = ref[3]; + return 'rgba(' + Math.round(r) + ',' + Math.round(g) + ',' + Math.round(b) + ',' + a + ')'; +}; +Color.prototype.toArray = function toArray() { + var ref = this; + var r = ref.r; + var g = ref.g; + var b = ref.b; + var a = ref.a; + return a === 0 ? [ + 0, + 0, + 0, + 0 + ] : [ + r * 255 / a, + g * 255 / a, + b * 255 / a, + a + ]; +}; +Color.black = new Color(0, 0, 0, 1); +Color.white = new Color(1, 1, 1, 1); +Color.transparent = new Color(0, 0, 0, 0); +Color.red = new Color(1, 0, 0, 1); + +var Collator = function Collator(caseSensitive, diacriticSensitive, locale) { + if (caseSensitive) { + this.sensitivity = diacriticSensitive ? 'variant' : 'case'; + } else { + this.sensitivity = diacriticSensitive ? 'accent' : 'base'; + } + this.locale = locale; + this.collator = new Intl.Collator(this.locale ? this.locale : [], { + sensitivity: this.sensitivity, + usage: 'search' + }); +}; +Collator.prototype.compare = function compare(lhs, rhs) { + return this.collator.compare(lhs, rhs); +}; +Collator.prototype.resolvedLocale = function resolvedLocale() { + return new Intl.Collator(this.locale ? this.locale : []).resolvedOptions().locale; +}; + +var FormattedSection = function FormattedSection(text, image, scale, fontStack, textColor) { + this.text = text; + this.image = image; + this.scale = scale; + this.fontStack = fontStack; + this.textColor = textColor; +}; +var Formatted = function Formatted(sections) { + this.sections = sections; +}; +Formatted.fromString = function fromString(unformatted) { + return new Formatted([new FormattedSection(unformatted, null, null, null, null)]); +}; +Formatted.prototype.isEmpty = function isEmpty() { + if (this.sections.length === 0) { + return true; + } + return !this.sections.some(function (section) { + return section.text.length !== 0 || section.image && section.image.name.length !== 0; + }); +}; +Formatted.factory = function factory(text) { + if (text instanceof Formatted) { + return text; + } else { + return Formatted.fromString(text); + } +}; +Formatted.prototype.toString = function toString() { + if (this.sections.length === 0) { + return ''; + } + return this.sections.map(function (section) { + return section.text; + }).join(''); +}; +Formatted.prototype.serialize = function serialize() { + var serialized = ['format']; + for (var i = 0, list = this.sections; i < list.length; i += 1) { + var section = list[i]; + if (section.image) { + serialized.push([ + 'image', + section.image.name + ]); + continue; + } + serialized.push(section.text); + var options = {}; + if (section.fontStack) { + options['text-font'] = [ + 'literal', + section.fontStack.split(',') + ]; + } + if (section.scale) { + options['font-scale'] = section.scale; + } + if (section.textColor) { + options['text-color'] = ['rgba'].concat(section.textColor.toArray()); + } + serialized.push(options); + } + return serialized; +}; + +var ResolvedImage = function ResolvedImage(options) { + this.name = options.name; + this.available = options.available; +}; +ResolvedImage.prototype.toString = function toString() { + return this.name; +}; +ResolvedImage.fromString = function fromString(name) { + if (!name) { + return null; + } + return new ResolvedImage({ + name: name, + available: false + }); +}; +ResolvedImage.prototype.serialize = function serialize() { + return [ + 'image', + this.name + ]; +}; + +function validateRGBA(r, g, b, a) { + if (!(typeof r === 'number' && r >= 0 && r <= 255 && typeof g === 'number' && g >= 0 && g <= 255 && typeof b === 'number' && b >= 0 && b <= 255)) { + var value = typeof a === 'number' ? [ + r, + g, + b, + a + ] : [ + r, + g, + b + ]; + return 'Invalid rgba value [' + value.join(', ') + ']: \'r\', \'g\', and \'b\' must be between 0 and 255.'; + } + if (!(typeof a === 'undefined' || typeof a === 'number' && a >= 0 && a <= 1)) { + return 'Invalid rgba value [' + [ + r, + g, + b, + a + ].join(', ') + ']: \'a\' must be between 0 and 1.'; + } + return null; +} +function isValue(mixed) { + if (mixed === null) { + return true; + } else if (typeof mixed === 'string') { + return true; + } else if (typeof mixed === 'boolean') { + return true; + } else if (typeof mixed === 'number') { + return true; + } else if (mixed instanceof Color) { + return true; + } else if (mixed instanceof Collator) { + return true; + } else if (mixed instanceof Formatted) { + return true; + } else if (mixed instanceof ResolvedImage) { + return true; + } else if (Array.isArray(mixed)) { + for (var i = 0, list = mixed; i < list.length; i += 1) { + var item = list[i]; + if (!isValue(item)) { + return false; + } + } + return true; + } else if (typeof mixed === 'object') { + for (var key in mixed) { + if (!isValue(mixed[key])) { + return false; + } + } + return true; + } else { + return false; + } +} +function typeOf(value) { + if (value === null) { + return NullType; + } else if (typeof value === 'string') { + return StringType; + } else if (typeof value === 'boolean') { + return BooleanType; + } else if (typeof value === 'number') { + return NumberType; + } else if (value instanceof Color) { + return ColorType; + } else if (value instanceof Collator) { + return CollatorType; + } else if (value instanceof Formatted) { + return FormattedType; + } else if (value instanceof ResolvedImage) { + return ResolvedImageType; + } else if (Array.isArray(value)) { + var length = value.length; + var itemType; + for (var i = 0, list = value; i < list.length; i += 1) { + var item = list[i]; + var t = typeOf(item); + if (!itemType) { + itemType = t; + } else if (itemType === t) { + continue; + } else { + itemType = ValueType; + break; + } + } + return array(itemType || ValueType, length); + } else { + return ObjectType; + } +} +function toString$1(value) { + var type = typeof value; + if (value === null) { + return ''; + } else if (type === 'string' || type === 'number' || type === 'boolean') { + return String(value); + } else if (value instanceof Color || value instanceof Formatted || value instanceof ResolvedImage) { + return value.toString(); + } else { + return JSON.stringify(value); + } +} + +var Literal = function Literal(type, value) { + this.type = type; + this.value = value; +}; +Literal.parse = function parse(args, context) { + if (args.length !== 2) { + return context.error('\'literal\' expression requires exactly one argument, but found ' + (args.length - 1) + ' instead.'); + } + if (!isValue(args[1])) { + return context.error('invalid value'); + } + var value = args[1]; + var type = typeOf(value); + var expected = context.expectedType; + if (type.kind === 'array' && type.N === 0 && expected && expected.kind === 'array' && (typeof expected.N !== 'number' || expected.N === 0)) { + type = expected; + } + return new Literal(type, value); +}; +Literal.prototype.evaluate = function evaluate() { + return this.value; +}; +Literal.prototype.eachChild = function eachChild() { +}; +Literal.prototype.outputDefined = function outputDefined() { + return true; +}; +Literal.prototype.serialize = function serialize() { + if (this.type.kind === 'array' || this.type.kind === 'object') { + return [ + 'literal', + this.value + ]; + } else if (this.value instanceof Color) { + return ['rgba'].concat(this.value.toArray()); + } else if (this.value instanceof Formatted) { + return this.value.serialize(); + } else { + return this.value; + } +}; + +var RuntimeError = function RuntimeError(message) { + this.name = 'ExpressionEvaluationError'; + this.message = message; +}; +RuntimeError.prototype.toJSON = function toJSON() { + return this.message; +}; + +var types = { + string: StringType, + number: NumberType, + boolean: BooleanType, + object: ObjectType +}; +var Assertion = function Assertion(type, args) { + this.type = type; + this.args = args; +}; +Assertion.parse = function parse(args, context) { + if (args.length < 2) { + return context.error('Expected at least one argument.'); + } + var i = 1; + var type; + var name = args[0]; + if (name === 'array') { + var itemType; + if (args.length > 2) { + var type$1 = args[1]; + if (typeof type$1 !== 'string' || !(type$1 in types) || type$1 === 'object') { + return context.error('The item type argument of "array" must be one of string, number, boolean', 1); + } + itemType = types[type$1]; + i++; + } else { + itemType = ValueType; + } + var N; + if (args.length > 3) { + if (args[2] !== null && (typeof args[2] !== 'number' || args[2] < 0 || args[2] !== Math.floor(args[2]))) { + return context.error('The length argument to "array" must be a positive integer literal', 2); + } + N = args[2]; + i++; + } + type = array(itemType, N); + } else { + type = types[name]; + } + var parsed = []; + for (; i < args.length; i++) { + var input = context.parse(args[i], i, ValueType); + if (!input) { + return null; + } + parsed.push(input); + } + return new Assertion(type, parsed); +}; +Assertion.prototype.evaluate = function evaluate(ctx) { + for (var i = 0; i < this.args.length; i++) { + var value = this.args[i].evaluate(ctx); + var error = checkSubtype(this.type, typeOf(value)); + if (!error) { + return value; + } else if (i === this.args.length - 1) { + throw new RuntimeError('Expected value to be of type ' + toString(this.type) + ', but found ' + toString(typeOf(value)) + ' instead.'); + } + } + return null; +}; +Assertion.prototype.eachChild = function eachChild(fn) { + this.args.forEach(fn); +}; +Assertion.prototype.outputDefined = function outputDefined() { + return this.args.every(function (arg) { + return arg.outputDefined(); + }); +}; +Assertion.prototype.serialize = function serialize() { + var type = this.type; + var serialized = [type.kind]; + if (type.kind === 'array') { + var itemType = type.itemType; + if (itemType.kind === 'string' || itemType.kind === 'number' || itemType.kind === 'boolean') { + serialized.push(itemType.kind); + var N = type.N; + if (typeof N === 'number' || this.args.length > 1) { + serialized.push(N); + } + } + } + return serialized.concat(this.args.map(function (arg) { + return arg.serialize(); + })); +}; + +var FormatExpression = function FormatExpression(sections) { + this.type = FormattedType; + this.sections = sections; +}; +FormatExpression.parse = function parse(args, context) { + if (args.length < 2) { + return context.error('Expected at least one argument.'); + } + var firstArg = args[1]; + if (!Array.isArray(firstArg) && typeof firstArg === 'object') { + return context.error('First argument must be an image or text section.'); + } + var sections = []; + var nextTokenMayBeObject = false; + for (var i = 1; i <= args.length - 1; ++i) { + var arg = args[i]; + if (nextTokenMayBeObject && typeof arg === 'object' && !Array.isArray(arg)) { + nextTokenMayBeObject = false; + var scale = null; + if (arg['font-scale']) { + scale = context.parse(arg['font-scale'], 1, NumberType); + if (!scale) { + return null; + } + } + var font = null; + if (arg['text-font']) { + font = context.parse(arg['text-font'], 1, array(StringType)); + if (!font) { + return null; + } + } + var textColor = null; + if (arg['text-color']) { + textColor = context.parse(arg['text-color'], 1, ColorType); + if (!textColor) { + return null; + } + } + var lastExpression = sections[sections.length - 1]; + lastExpression.scale = scale; + lastExpression.font = font; + lastExpression.textColor = textColor; + } else { + var content = context.parse(args[i], 1, ValueType); + if (!content) { + return null; + } + var kind = content.type.kind; + if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage') { + return context.error('Formatted text type must be \'string\', \'value\', \'image\' or \'null\'.'); + } + nextTokenMayBeObject = true; + sections.push({ + content: content, + scale: null, + font: null, + textColor: null + }); + } + } + return new FormatExpression(sections); +}; +FormatExpression.prototype.evaluate = function evaluate(ctx) { + var evaluateSection = function (section) { + var evaluatedContent = section.content.evaluate(ctx); + if (typeOf(evaluatedContent) === ResolvedImageType) { + return new FormattedSection('', evaluatedContent, null, null, null); + } + return new FormattedSection(toString$1(evaluatedContent), null, section.scale ? section.scale.evaluate(ctx) : null, section.font ? section.font.evaluate(ctx).join(',') : null, section.textColor ? section.textColor.evaluate(ctx) : null); + }; + return new Formatted(this.sections.map(evaluateSection)); +}; +FormatExpression.prototype.eachChild = function eachChild(fn) { + for (var i = 0, list = this.sections; i < list.length; i += 1) { + var section = list[i]; + fn(section.content); + if (section.scale) { + fn(section.scale); + } + if (section.font) { + fn(section.font); + } + if (section.textColor) { + fn(section.textColor); + } + } +}; +FormatExpression.prototype.outputDefined = function outputDefined() { + return false; +}; +FormatExpression.prototype.serialize = function serialize() { + var serialized = ['format']; + for (var i = 0, list = this.sections; i < list.length; i += 1) { + var section = list[i]; + serialized.push(section.content.serialize()); + var options = {}; + if (section.scale) { + options['font-scale'] = section.scale.serialize(); + } + if (section.font) { + options['text-font'] = section.font.serialize(); + } + if (section.textColor) { + options['text-color'] = section.textColor.serialize(); + } + serialized.push(options); + } + return serialized; +}; + +var ImageExpression = function ImageExpression(input) { + this.type = ResolvedImageType; + this.input = input; +}; +ImageExpression.parse = function parse(args, context) { + if (args.length !== 2) { + return context.error('Expected two arguments.'); + } + var name = context.parse(args[1], 1, StringType); + if (!name) { + return context.error('No image name provided.'); + } + return new ImageExpression(name); +}; +ImageExpression.prototype.evaluate = function evaluate(ctx) { + var evaluatedImageName = this.input.evaluate(ctx); + var value = ResolvedImage.fromString(evaluatedImageName); + if (value && ctx.availableImages) { + value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1; + } + return value; +}; +ImageExpression.prototype.eachChild = function eachChild(fn) { + fn(this.input); +}; +ImageExpression.prototype.outputDefined = function outputDefined() { + return false; +}; +ImageExpression.prototype.serialize = function serialize() { + return [ + 'image', + this.input.serialize() + ]; +}; + +var types$1 = { + 'to-boolean': BooleanType, + 'to-color': ColorType, + 'to-number': NumberType, + 'to-string': StringType +}; +var Coercion = function Coercion(type, args) { + this.type = type; + this.args = args; +}; +Coercion.parse = function parse(args, context) { + if (args.length < 2) { + return context.error('Expected at least one argument.'); + } + var name = args[0]; + if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2) { + return context.error('Expected one argument.'); + } + var type = types$1[name]; + var parsed = []; + for (var i = 1; i < args.length; i++) { + var input = context.parse(args[i], i, ValueType); + if (!input) { + return null; + } + parsed.push(input); + } + return new Coercion(type, parsed); +}; +Coercion.prototype.evaluate = function evaluate(ctx) { + if (this.type.kind === 'boolean') { + return Boolean(this.args[0].evaluate(ctx)); + } else if (this.type.kind === 'color') { + var input; + var error; + for (var i = 0, list = this.args; i < list.length; i += 1) { + var arg = list[i]; + input = arg.evaluate(ctx); + error = null; + if (input instanceof Color) { + return input; + } else if (typeof input === 'string') { + var c = ctx.parseColor(input); + if (c) { + return c; + } + } else if (Array.isArray(input)) { + if (input.length < 3 || input.length > 4) { + error = 'Invalid rbga value ' + JSON.stringify(input) + ': expected an array containing either three or four numeric values.'; + } else { + error = validateRGBA(input[0], input[1], input[2], input[3]); + } + if (!error) { + return new Color(input[0] / 255, input[1] / 255, input[2] / 255, input[3]); + } + } + } + throw new RuntimeError(error || 'Could not parse color from value \'' + (typeof input === 'string' ? input : String(JSON.stringify(input))) + '\''); + } else if (this.type.kind === 'number') { + var value = null; + for (var i$1 = 0, list$1 = this.args; i$1 < list$1.length; i$1 += 1) { + var arg$1 = list$1[i$1]; + value = arg$1.evaluate(ctx); + if (value === null) { + return 0; + } + var num = Number(value); + if (isNaN(num)) { + continue; + } + return num; + } + throw new RuntimeError('Could not convert ' + JSON.stringify(value) + ' to number.'); + } else if (this.type.kind === 'formatted') { + return Formatted.fromString(toString$1(this.args[0].evaluate(ctx))); + } else if (this.type.kind === 'resolvedImage') { + return ResolvedImage.fromString(toString$1(this.args[0].evaluate(ctx))); + } else { + return toString$1(this.args[0].evaluate(ctx)); + } +}; +Coercion.prototype.eachChild = function eachChild(fn) { + this.args.forEach(fn); +}; +Coercion.prototype.outputDefined = function outputDefined() { + return this.args.every(function (arg) { + return arg.outputDefined(); + }); +}; +Coercion.prototype.serialize = function serialize() { + if (this.type.kind === 'formatted') { + return new FormatExpression([{ + content: this.args[0], + scale: null, + font: null, + textColor: null + }]).serialize(); + } + if (this.type.kind === 'resolvedImage') { + return new ImageExpression(this.args[0]).serialize(); + } + var serialized = ['to-' + this.type.kind]; + this.eachChild(function (child) { + serialized.push(child.serialize()); + }); + return serialized; +}; + +var geometryTypes = [ + 'Unknown', + 'Point', + 'LineString', + 'Polygon' +]; +var EvaluationContext = function EvaluationContext() { + this.globals = null; + this.feature = null; + this.featureState = null; + this.formattedSection = null; + this._parseColorCache = {}; + this.availableImages = null; + this.canonical = null; +}; +EvaluationContext.prototype.id = function id() { + return this.feature && 'id' in this.feature ? this.feature.id : null; +}; +EvaluationContext.prototype.geometryType = function geometryType() { + return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null; +}; +EvaluationContext.prototype.geometry = function geometry() { + return this.feature && 'geometry' in this.feature ? this.feature.geometry : null; +}; +EvaluationContext.prototype.canonicalID = function canonicalID() { + return this.canonical; +}; +EvaluationContext.prototype.properties = function properties() { + return this.feature && this.feature.properties || {}; +}; +EvaluationContext.prototype.parseColor = function parseColor(input) { + var cached = this._parseColorCache[input]; + if (!cached) { + cached = this._parseColorCache[input] = Color.parse(input); + } + return cached; +}; + +var CompoundExpression = function CompoundExpression(name, type, evaluate, args) { + this.name = name; + this.type = type; + this._evaluate = evaluate; + this.args = args; +}; +CompoundExpression.prototype.evaluate = function evaluate(ctx) { + return this._evaluate(ctx, this.args); +}; +CompoundExpression.prototype.eachChild = function eachChild(fn) { + this.args.forEach(fn); +}; +CompoundExpression.prototype.outputDefined = function outputDefined() { + return false; +}; +CompoundExpression.prototype.serialize = function serialize() { + return [this.name].concat(this.args.map(function (arg) { + return arg.serialize(); + })); +}; +CompoundExpression.parse = function parse(args, context) { + var ref$1; + var op = args[0]; + var definition = CompoundExpression.definitions[op]; + if (!definition) { + return context.error('Unknown expression "' + op + '". If you wanted a literal array, use ["literal", [...]].', 0); + } + var type = Array.isArray(definition) ? definition[0] : definition.type; + var availableOverloads = Array.isArray(definition) ? [[ + definition[1], + definition[2] + ]] : definition.overloads; + var overloads = availableOverloads.filter(function (ref) { + var signature = ref[0]; + return !Array.isArray(signature) || signature.length === args.length - 1; + }); + var signatureContext = null; + for (var i$3 = 0, list = overloads; i$3 < list.length; i$3 += 1) { + var ref = list[i$3]; + var params = ref[0]; + var evaluate = ref[1]; + signatureContext = new ParsingContext(context.registry, context.path, null, context.scope); + var parsedArgs = []; + var argParseFailed = false; + for (var i = 1; i < args.length; i++) { + var arg = args[i]; + var expectedType = Array.isArray(params) ? params[i - 1] : params.type; + var parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType); + if (!parsed) { + argParseFailed = true; + break; + } + parsedArgs.push(parsed); + } + if (argParseFailed) { + continue; + } + if (Array.isArray(params)) { + if (params.length !== parsedArgs.length) { + signatureContext.error('Expected ' + params.length + ' arguments, but found ' + parsedArgs.length + ' instead.'); + continue; + } + } + for (var i$1 = 0; i$1 < parsedArgs.length; i$1++) { + var expected = Array.isArray(params) ? params[i$1] : params.type; + var arg$1 = parsedArgs[i$1]; + signatureContext.concat(i$1 + 1).checkSubtype(expected, arg$1.type); + } + if (signatureContext.errors.length === 0) { + return new CompoundExpression(op, type, evaluate, parsedArgs); + } + } + if (overloads.length === 1) { + (ref$1 = context.errors).push.apply(ref$1, signatureContext.errors); + } else { + var expected$1 = overloads.length ? overloads : availableOverloads; + var signatures = expected$1.map(function (ref) { + var params = ref[0]; + return stringifySignature(params); + }).join(' | '); + var actualTypes = []; + for (var i$2 = 1; i$2 < args.length; i$2++) { + var parsed$1 = context.parse(args[i$2], 1 + actualTypes.length); + if (!parsed$1) { + return null; + } + actualTypes.push(toString(parsed$1.type)); + } + context.error('Expected arguments of type ' + signatures + ', but found (' + actualTypes.join(', ') + ') instead.'); + } + return null; +}; +CompoundExpression.register = function register(registry, definitions) { + CompoundExpression.definitions = definitions; + for (var name in definitions) { + registry[name] = CompoundExpression; + } +}; +function stringifySignature(signature) { + if (Array.isArray(signature)) { + return '(' + signature.map(toString).join(', ') + ')'; + } else { + return '(' + toString(signature.type) + '...)'; + } +} + +var CollatorExpression = function CollatorExpression(caseSensitive, diacriticSensitive, locale) { + this.type = CollatorType; + this.locale = locale; + this.caseSensitive = caseSensitive; + this.diacriticSensitive = diacriticSensitive; +}; +CollatorExpression.parse = function parse(args, context) { + if (args.length !== 2) { + return context.error('Expected one argument.'); + } + var options = args[1]; + if (typeof options !== 'object' || Array.isArray(options)) { + return context.error('Collator options argument must be an object.'); + } + var caseSensitive = context.parse(options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType); + if (!caseSensitive) { + return null; + } + var diacriticSensitive = context.parse(options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType); + if (!diacriticSensitive) { + return null; + } + var locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) { + return null; + } + } + return new CollatorExpression(caseSensitive, diacriticSensitive, locale); +}; +CollatorExpression.prototype.evaluate = function evaluate(ctx) { + return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null); +}; +CollatorExpression.prototype.eachChild = function eachChild(fn) { + fn(this.caseSensitive); + fn(this.diacriticSensitive); + if (this.locale) { + fn(this.locale); + } +}; +CollatorExpression.prototype.outputDefined = function outputDefined() { + return false; +}; +CollatorExpression.prototype.serialize = function serialize() { + var options = {}; + options['case-sensitive'] = this.caseSensitive.serialize(); + options['diacritic-sensitive'] = this.diacriticSensitive.serialize(); + if (this.locale) { + options['locale'] = this.locale.serialize(); + } + return [ + 'collator', + options + ]; +}; + +var EXTENT = 8192; +function updateBBox(bbox, coord) { + bbox[0] = Math.min(bbox[0], coord[0]); + bbox[1] = Math.min(bbox[1], coord[1]); + bbox[2] = Math.max(bbox[2], coord[0]); + bbox[3] = Math.max(bbox[3], coord[1]); +} +function mercatorXfromLng(lng) { + return (180 + lng) / 360; +} +function mercatorYfromLat(lat) { + return (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360))) / 360; +} +function boxWithinBox(bbox1, bbox2) { + if (bbox1[0] <= bbox2[0]) { + return false; + } + if (bbox1[2] >= bbox2[2]) { + return false; + } + if (bbox1[1] <= bbox2[1]) { + return false; + } + if (bbox1[3] >= bbox2[3]) { + return false; + } + return true; +} +function getTileCoordinates(p, canonical) { + var x = mercatorXfromLng(p[0]); + var y = mercatorYfromLat(p[1]); + var tilesAtZoom = Math.pow(2, canonical.z); + return [ + Math.round(x * tilesAtZoom * EXTENT), + Math.round(y * tilesAtZoom * EXTENT) + ]; +} +function onBoundary(p, p1, p2) { + var x1 = p[0] - p1[0]; + var y1 = p[1] - p1[1]; + var x2 = p[0] - p2[0]; + var y2 = p[1] - p2[1]; + return x1 * y2 - x2 * y1 === 0 && x1 * x2 <= 0 && y1 * y2 <= 0; +} +function rayIntersect(p, p1, p2) { + return p1[1] > p[1] !== p2[1] > p[1] && p[0] < (p2[0] - p1[0]) * (p[1] - p1[1]) / (p2[1] - p1[1]) + p1[0]; +} +function pointWithinPolygon(point, rings) { + var inside = false; + for (var i = 0, len = rings.length; i < len; i++) { + var ring = rings[i]; + for (var j = 0, len2 = ring.length; j < len2 - 1; j++) { + if (onBoundary(point, ring[j], ring[j + 1])) { + return false; + } + if (rayIntersect(point, ring[j], ring[j + 1])) { + inside = !inside; + } + } + } + return inside; +} +function pointWithinPolygons(point, polygons) { + for (var i = 0; i < polygons.length; i++) { + if (pointWithinPolygon(point, polygons[i])) { + return true; + } + } + return false; +} +function perp(v1, v2) { + return v1[0] * v2[1] - v1[1] * v2[0]; +} +function twoSided(p1, p2, q1, q2) { + var x1 = p1[0] - q1[0]; + var y1 = p1[1] - q1[1]; + var x2 = p2[0] - q1[0]; + var y2 = p2[1] - q1[1]; + var x3 = q2[0] - q1[0]; + var y3 = q2[1] - q1[1]; + var det1 = x1 * y3 - x3 * y1; + var det2 = x2 * y3 - x3 * y2; + if (det1 > 0 && det2 < 0 || det1 < 0 && det2 > 0) { + return true; + } + return false; +} +function lineIntersectLine(a, b, c, d) { + var vectorP = [ + b[0] - a[0], + b[1] - a[1] + ]; + var vectorQ = [ + d[0] - c[0], + d[1] - c[1] + ]; + if (perp(vectorQ, vectorP) === 0) { + return false; + } + if (twoSided(a, b, c, d) && twoSided(c, d, a, b)) { + return true; + } + return false; +} +function lineIntersectPolygon(p1, p2, polygon) { + for (var i = 0, list = polygon; i < list.length; i += 1) { + var ring = list[i]; + for (var j = 0; j < ring.length - 1; ++j) { + if (lineIntersectLine(p1, p2, ring[j], ring[j + 1])) { + return true; + } + } + } + return false; +} +function lineStringWithinPolygon(line, polygon) { + for (var i = 0; i < line.length; ++i) { + if (!pointWithinPolygon(line[i], polygon)) { + return false; + } + } + for (var i$1 = 0; i$1 < line.length - 1; ++i$1) { + if (lineIntersectPolygon(line[i$1], line[i$1 + 1], polygon)) { + return false; + } + } + return true; +} +function lineStringWithinPolygons(line, polygons) { + for (var i = 0; i < polygons.length; i++) { + if (lineStringWithinPolygon(line, polygons[i])) { + return true; + } + } + return false; +} +function getTilePolygon(coordinates, bbox, canonical) { + var polygon = []; + for (var i = 0; i < coordinates.length; i++) { + var ring = []; + for (var j = 0; j < coordinates[i].length; j++) { + var coord = getTileCoordinates(coordinates[i][j], canonical); + updateBBox(bbox, coord); + ring.push(coord); + } + polygon.push(ring); + } + return polygon; +} +function getTilePolygons(coordinates, bbox, canonical) { + var polygons = []; + for (var i = 0; i < coordinates.length; i++) { + var polygon = getTilePolygon(coordinates[i], bbox, canonical); + polygons.push(polygon); + } + return polygons; +} +function updatePoint(p, bbox, polyBBox, worldSize) { + if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) { + var halfWorldSize = worldSize * 0.5; + var shift = p[0] - polyBBox[0] > halfWorldSize ? -worldSize : polyBBox[0] - p[0] > halfWorldSize ? worldSize : 0; + if (shift === 0) { + shift = p[0] - polyBBox[2] > halfWorldSize ? -worldSize : polyBBox[2] - p[0] > halfWorldSize ? worldSize : 0; + } + p[0] += shift; + } + updateBBox(bbox, p); +} +function resetBBox(bbox) { + bbox[0] = bbox[1] = Infinity; + bbox[2] = bbox[3] = -Infinity; +} +function getTilePoints(geometry, pointBBox, polyBBox, canonical) { + var worldSize = Math.pow(2, canonical.z) * EXTENT; + var shifts = [ + canonical.x * EXTENT, + canonical.y * EXTENT + ]; + var tilePoints = []; + for (var i$1 = 0, list$1 = geometry; i$1 < list$1.length; i$1 += 1) { + var points = list$1[i$1]; + for (var i = 0, list = points; i < list.length; i += 1) { + var point = list[i]; + var p = [ + point.x + shifts[0], + point.y + shifts[1] + ]; + updatePoint(p, pointBBox, polyBBox, worldSize); + tilePoints.push(p); + } + } + return tilePoints; +} +function getTileLines(geometry, lineBBox, polyBBox, canonical) { + var worldSize = Math.pow(2, canonical.z) * EXTENT; + var shifts = [ + canonical.x * EXTENT, + canonical.y * EXTENT + ]; + var tileLines = []; + for (var i$1 = 0, list$1 = geometry; i$1 < list$1.length; i$1 += 1) { + var line = list$1[i$1]; + var tileLine = []; + for (var i = 0, list = line; i < list.length; i += 1) { + var point = list[i]; + var p = [ + point.x + shifts[0], + point.y + shifts[1] + ]; + updateBBox(lineBBox, p); + tileLine.push(p); + } + tileLines.push(tileLine); + } + if (lineBBox[2] - lineBBox[0] <= worldSize / 2) { + resetBBox(lineBBox); + for (var i$3 = 0, list$3 = tileLines; i$3 < list$3.length; i$3 += 1) { + var line$1 = list$3[i$3]; + for (var i$2 = 0, list$2 = line$1; i$2 < list$2.length; i$2 += 1) { + var p$1 = list$2[i$2]; + updatePoint(p$1, lineBBox, polyBBox, worldSize); + } + } + } + return tileLines; +} +function pointsWithinPolygons(ctx, polygonGeometry) { + var pointBBox = [ + Infinity, + Infinity, + -Infinity, + -Infinity + ]; + var polyBBox = [ + Infinity, + Infinity, + -Infinity, + -Infinity + ]; + var canonical = ctx.canonicalID(); + if (polygonGeometry.type === 'Polygon') { + var tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + var tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) { + return false; + } + for (var i = 0, list = tilePoints; i < list.length; i += 1) { + var point = list[i]; + if (!pointWithinPolygon(point, tilePolygon)) { + return false; + } + } + } + if (polygonGeometry.type === 'MultiPolygon') { + var tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + var tilePoints$1 = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) { + return false; + } + for (var i$1 = 0, list$1 = tilePoints$1; i$1 < list$1.length; i$1 += 1) { + var point$1 = list$1[i$1]; + if (!pointWithinPolygons(point$1, tilePolygons)) { + return false; + } + } + } + return true; +} +function linesWithinPolygons(ctx, polygonGeometry) { + var lineBBox = [ + Infinity, + Infinity, + -Infinity, + -Infinity + ]; + var polyBBox = [ + Infinity, + Infinity, + -Infinity, + -Infinity + ]; + var canonical = ctx.canonicalID(); + if (polygonGeometry.type === 'Polygon') { + var tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + var tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) { + return false; + } + for (var i = 0, list = tileLines; i < list.length; i += 1) { + var line = list[i]; + if (!lineStringWithinPolygon(line, tilePolygon)) { + return false; + } + } + } + if (polygonGeometry.type === 'MultiPolygon') { + var tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + var tileLines$1 = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) { + return false; + } + for (var i$1 = 0, list$1 = tileLines$1; i$1 < list$1.length; i$1 += 1) { + var line$1 = list$1[i$1]; + if (!lineStringWithinPolygons(line$1, tilePolygons)) { + return false; + } + } + } + return true; +} +var Within = function Within(geojson, geometries) { + this.type = BooleanType; + this.geojson = geojson; + this.geometries = geometries; +}; +Within.parse = function parse(args, context) { + if (args.length !== 2) { + return context.error('\'within\' expression requires exactly one argument, but found ' + (args.length - 1) + ' instead.'); + } + if (isValue(args[1])) { + var geojson = args[1]; + if (geojson.type === 'FeatureCollection') { + for (var i = 0; i < geojson.features.length; ++i) { + var type = geojson.features[i].geometry.type; + if (type === 'Polygon' || type === 'MultiPolygon') { + return new Within(geojson, geojson.features[i].geometry); + } + } + } else if (geojson.type === 'Feature') { + var type$1 = geojson.geometry.type; + if (type$1 === 'Polygon' || type$1 === 'MultiPolygon') { + return new Within(geojson, geojson.geometry); + } + } else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') { + return new Within(geojson, geojson); + } + } + return context.error('\'within\' expression requires valid geojson object that contains polygon geometry type.'); +}; +Within.prototype.evaluate = function evaluate(ctx) { + if (ctx.geometry() != null && ctx.canonicalID() != null) { + if (ctx.geometryType() === 'Point') { + return pointsWithinPolygons(ctx, this.geometries); + } else if (ctx.geometryType() === 'LineString') { + return linesWithinPolygons(ctx, this.geometries); + } + } + return false; +}; +Within.prototype.eachChild = function eachChild() { +}; +Within.prototype.outputDefined = function outputDefined() { + return true; +}; +Within.prototype.serialize = function serialize() { + return [ + 'within', + this.geojson + ]; +}; + +function isFeatureConstant(e) { + if (e instanceof CompoundExpression) { + if (e.name === 'get' && e.args.length === 1) { + return false; + } else if (e.name === 'feature-state') { + return false; + } else if (e.name === 'has' && e.args.length === 1) { + return false; + } else if (e.name === 'properties' || e.name === 'geometry-type' || e.name === 'id') { + return false; + } else if (/^filter-/.test(e.name)) { + return false; + } + } + if (e instanceof Within) { + return false; + } + var result = true; + e.eachChild(function (arg) { + if (result && !isFeatureConstant(arg)) { + result = false; + } + }); + return result; +} +function isStateConstant(e) { + if (e instanceof CompoundExpression) { + if (e.name === 'feature-state') { + return false; + } + } + var result = true; + e.eachChild(function (arg) { + if (result && !isStateConstant(arg)) { + result = false; + } + }); + return result; +} +function isGlobalPropertyConstant(e, properties) { + if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) { + return false; + } + var result = true; + e.eachChild(function (arg) { + if (result && !isGlobalPropertyConstant(arg, properties)) { + result = false; + } + }); + return result; +} + +var Var = function Var(name, boundExpression) { + this.type = boundExpression.type; + this.name = name; + this.boundExpression = boundExpression; +}; +Var.parse = function parse(args, context) { + if (args.length !== 2 || typeof args[1] !== 'string') { + return context.error('\'var\' expression requires exactly one string literal argument.'); + } + var name = args[1]; + if (!context.scope.has(name)) { + return context.error('Unknown variable "' + name + '". Make sure "' + name + '" has been bound in an enclosing "let" expression before using it.', 1); + } + return new Var(name, context.scope.get(name)); +}; +Var.prototype.evaluate = function evaluate(ctx) { + return this.boundExpression.evaluate(ctx); +}; +Var.prototype.eachChild = function eachChild() { +}; +Var.prototype.outputDefined = function outputDefined() { + return false; +}; +Var.prototype.serialize = function serialize() { + return [ + 'var', + this.name + ]; +}; + +var ParsingContext = function ParsingContext(registry, path, expectedType, scope, errors) { + if (path === void 0) + path = []; + if (scope === void 0) + scope = new Scope(); + if (errors === void 0) + errors = []; + this.registry = registry; + this.path = path; + this.key = path.map(function (part) { + return '[' + part + ']'; + }).join(''); + this.scope = scope; + this.errors = errors; + this.expectedType = expectedType; +}; +ParsingContext.prototype.parse = function parse(expr, index, expectedType, bindings, options) { + if (options === void 0) + options = {}; + if (index) { + return this.concat(index, expectedType, bindings)._parse(expr, options); + } + return this._parse(expr, options); +}; +ParsingContext.prototype._parse = function _parse(expr, options) { + if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') { + expr = [ + 'literal', + expr + ]; + } + function annotate(parsed, type, typeAnnotation) { + if (typeAnnotation === 'assert') { + return new Assertion(type, [parsed]); + } else if (typeAnnotation === 'coerce') { + return new Coercion(type, [parsed]); + } else { + return parsed; + } + } + if (Array.isArray(expr)) { + if (expr.length === 0) { + return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].'); + } + var op = expr[0]; + if (typeof op !== 'string') { + this.error('Expression name must be a string, but found ' + typeof op + ' instead. If you wanted a literal array, use ["literal", [...]].', 0); + return null; + } + var Expr = this.registry[op]; + if (Expr) { + var parsed = Expr.parse(expr, this); + if (!parsed) { + return null; + } + if (this.expectedType) { + var expected = this.expectedType; + var actual = parsed.type; + if ((expected.kind === 'string' || expected.kind === 'number' || expected.kind === 'boolean' || expected.kind === 'object' || expected.kind === 'array') && actual.kind === 'value') { + parsed = annotate(parsed, expected, options.typeAnnotation || 'assert'); + } else if ((expected.kind === 'color' || expected.kind === 'formatted' || expected.kind === 'resolvedImage') && (actual.kind === 'value' || actual.kind === 'string')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } else if (this.checkSubtype(expected, actual)) { + return null; + } + } + if (!(parsed instanceof Literal) && parsed.type.kind !== 'resolvedImage' && isConstant(parsed)) { + var ec = new EvaluationContext(); + try { + parsed = new Literal(parsed.type, parsed.evaluate(ec)); + } catch (e) { + this.error(e.message); + return null; + } + } + return parsed; + } + return this.error('Unknown expression "' + op + '". If you wanted a literal array, use ["literal", [...]].', 0); + } else if (typeof expr === 'undefined') { + return this.error('\'undefined\' value invalid. Use null instead.'); + } else if (typeof expr === 'object') { + return this.error('Bare objects invalid. Use ["literal", {...}] instead.'); + } else { + return this.error('Expected an array, but found ' + typeof expr + ' instead.'); + } +}; +ParsingContext.prototype.concat = function concat(index, expectedType, bindings) { + var path = typeof index === 'number' ? this.path.concat(index) : this.path; + var scope = bindings ? this.scope.concat(bindings) : this.scope; + return new ParsingContext(this.registry, path, expectedType || null, scope, this.errors); +}; +ParsingContext.prototype.error = function error(error$1) { + var keys = [], len = arguments.length - 1; + while (len-- > 0) + keys[len] = arguments[len + 1]; + var key = '' + this.key + keys.map(function (k) { + return '[' + k + ']'; + }).join(''); + this.errors.push(new ParsingError(key, error$1)); +}; +ParsingContext.prototype.checkSubtype = function checkSubtype$1(expected, t) { + var error = checkSubtype(expected, t); + if (error) { + this.error(error); + } + return error; +}; +function isConstant(expression) { + if (expression instanceof Var) { + return isConstant(expression.boundExpression); + } else if (expression instanceof CompoundExpression && expression.name === 'error') { + return false; + } else if (expression instanceof CollatorExpression) { + return false; + } else if (expression instanceof Within) { + return false; + } + var isTypeAnnotation = expression instanceof Coercion || expression instanceof Assertion; + var childrenConstant = true; + expression.eachChild(function (child) { + if (isTypeAnnotation) { + childrenConstant = childrenConstant && isConstant(child); + } else { + childrenConstant = childrenConstant && child instanceof Literal; + } + }); + if (!childrenConstant) { + return false; + } + return isFeatureConstant(expression) && isGlobalPropertyConstant(expression, [ + 'zoom', + 'heatmap-density', + 'line-progress', + 'accumulated', + 'is-supported-script' + ]); +} + +function findStopLessThanOrEqualTo(stops, input) { + var lastIndex = stops.length - 1; + var lowerIndex = 0; + var upperIndex = lastIndex; + var currentIndex = 0; + var currentValue, nextValue; + while (lowerIndex <= upperIndex) { + currentIndex = Math.floor((lowerIndex + upperIndex) / 2); + currentValue = stops[currentIndex]; + nextValue = stops[currentIndex + 1]; + if (currentValue <= input) { + if (currentIndex === lastIndex || input < nextValue) { + return currentIndex; + } + lowerIndex = currentIndex + 1; + } else if (currentValue > input) { + upperIndex = currentIndex - 1; + } else { + throw new RuntimeError('Input is not a number.'); + } + } + return 0; +} + +var Step = function Step(type, input, stops) { + this.type = type; + this.input = input; + this.labels = []; + this.outputs = []; + for (var i = 0, list = stops; i < list.length; i += 1) { + var ref = list[i]; + var label = ref[0]; + var expression = ref[1]; + this.labels.push(label); + this.outputs.push(expression); + } +}; +Step.parse = function parse(args, context) { + if (args.length - 1 < 4) { + return context.error('Expected at least 4 arguments, but found only ' + (args.length - 1) + '.'); + } + if ((args.length - 1) % 2 !== 0) { + return context.error('Expected an even number of arguments.'); + } + var input = context.parse(args[1], 1, NumberType); + if (!input) { + return null; + } + var stops = []; + var outputType = null; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + for (var i = 1; i < args.length; i += 2) { + var label = i === 1 ? -Infinity : args[i]; + var value = args[i + 1]; + var labelKey = i; + var valueKey = i + 1; + if (typeof label !== 'number') { + return context.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + var parsed = context.parse(value, valueKey, outputType); + if (!parsed) { + return null; + } + outputType = outputType || parsed.type; + stops.push([ + label, + parsed + ]); + } + return new Step(outputType, input, stops); +}; +Step.prototype.evaluate = function evaluate(ctx) { + var labels = this.labels; + var outputs = this.outputs; + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + var value = this.input.evaluate(ctx); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + var stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + var index = findStopLessThanOrEqualTo(labels, value); + return outputs[index].evaluate(ctx); +}; +Step.prototype.eachChild = function eachChild(fn) { + fn(this.input); + for (var i = 0, list = this.outputs; i < list.length; i += 1) { + var expression = list[i]; + fn(expression); + } +}; +Step.prototype.outputDefined = function outputDefined() { + return this.outputs.every(function (out) { + return out.outputDefined(); + }); +}; +Step.prototype.serialize = function serialize() { + var serialized = [ + 'step', + this.input.serialize() + ]; + for (var i = 0; i < this.labels.length; i++) { + if (i > 0) { + serialized.push(this.labels[i]); + } + serialized.push(this.outputs[i].serialize()); + } + return serialized; +}; + +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Ported from Webkit + * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h + */ + +var unitbezier = UnitBezier; + +function UnitBezier(p1x, p1y, p2x, p2y) { + // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). + this.cx = 3.0 * p1x; + this.bx = 3.0 * (p2x - p1x) - this.cx; + this.ax = 1.0 - this.cx - this.bx; + + this.cy = 3.0 * p1y; + this.by = 3.0 * (p2y - p1y) - this.cy; + this.ay = 1.0 - this.cy - this.by; + + this.p1x = p1x; + this.p1y = p2y; + this.p2x = p2x; + this.p2y = p2y; +} + +UnitBezier.prototype.sampleCurveX = function(t) { + // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. + return ((this.ax * t + this.bx) * t + this.cx) * t; +}; + +UnitBezier.prototype.sampleCurveY = function(t) { + return ((this.ay * t + this.by) * t + this.cy) * t; +}; + +UnitBezier.prototype.sampleCurveDerivativeX = function(t) { + return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx; +}; + +UnitBezier.prototype.solveCurveX = function(x, epsilon) { + if (typeof epsilon === 'undefined') { epsilon = 1e-6; } + + var t0, t1, t2, x2, i; + + // First try a few iterations of Newton's method -- normally very fast. + for (t2 = x, i = 0; i < 8; i++) { + + x2 = this.sampleCurveX(t2) - x; + if (Math.abs(x2) < epsilon) { return t2; } + + var d2 = this.sampleCurveDerivativeX(t2); + if (Math.abs(d2) < 1e-6) { break; } + + t2 = t2 - x2 / d2; + } + + // Fall back to the bisection method for reliability. + t0 = 0.0; + t1 = 1.0; + t2 = x; + + if (t2 < t0) { return t0; } + if (t2 > t1) { return t1; } + + while (t0 < t1) { + + x2 = this.sampleCurveX(t2); + if (Math.abs(x2 - x) < epsilon) { return t2; } + + if (x > x2) { + t0 = t2; + } else { + t1 = t2; + } + + t2 = (t1 - t0) * 0.5 + t0; + } + + // Failure. + return t2; +}; + +UnitBezier.prototype.solve = function(x, epsilon) { + return this.sampleCurveY(this.solveCurveX(x, epsilon)); +}; + +function number(a, b, t) { + return a * (1 - t) + b * t; +} +function color(from, to, t) { + return new Color(number(from.r, to.r, t), number(from.g, to.g, t), number(from.b, to.b, t), number(from.a, to.a, t)); +} +function array$1(from, to, t) { + return from.map(function (d, i) { + return number(d, to[i], t); + }); +} + +var interpolate = /*#__PURE__*/Object.freeze({ + __proto__: null, + number: number, + color: color, + array: array$1 +}); + +var Xn = 0.95047, Yn = 1, Zn = 1.08883, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1, deg2rad = Math.PI / 180, rad2deg = 180 / Math.PI; +function xyz2lab(t) { + return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0; +} +function lab2xyz(t) { + return t > t1 ? t * t * t : t2 * (t - t0); +} +function xyz2rgb(x) { + return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); +} +function rgb2xyz(x) { + x /= 255; + return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); +} +function rgbToLab(rgbColor) { + var b = rgb2xyz(rgbColor.r), a = rgb2xyz(rgbColor.g), l = rgb2xyz(rgbColor.b), x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn), y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.072175 * l) / Yn), z = xyz2lab((0.0193339 * b + 0.119192 * a + 0.9503041 * l) / Zn); + return { + l: 116 * y - 16, + a: 500 * (x - y), + b: 200 * (y - z), + alpha: rgbColor.a + }; +} +function labToRgb(labColor) { + var y = (labColor.l + 16) / 116, x = isNaN(labColor.a) ? y : y + labColor.a / 500, z = isNaN(labColor.b) ? y : y - labColor.b / 200; + y = Yn * lab2xyz(y); + x = Xn * lab2xyz(x); + z = Zn * lab2xyz(z); + return new Color(xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z), xyz2rgb(-0.969266 * x + 1.8760108 * y + 0.041556 * z), xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z), labColor.alpha); +} +function interpolateLab(from, to, t) { + return { + l: number(from.l, to.l, t), + a: number(from.a, to.a, t), + b: number(from.b, to.b, t), + alpha: number(from.alpha, to.alpha, t) + }; +} +function rgbToHcl(rgbColor) { + var ref = rgbToLab(rgbColor); + var l = ref.l; + var a = ref.a; + var b = ref.b; + var h = Math.atan2(b, a) * rad2deg; + return { + h: h < 0 ? h + 360 : h, + c: Math.sqrt(a * a + b * b), + l: l, + alpha: rgbColor.a + }; +} +function hclToRgb(hclColor) { + var h = hclColor.h * deg2rad, c = hclColor.c, l = hclColor.l; + return labToRgb({ + l: l, + a: Math.cos(h) * c, + b: Math.sin(h) * c, + alpha: hclColor.alpha + }); +} +function interpolateHue(a, b, t) { + var d = b - a; + return a + t * (d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d); +} +function interpolateHcl(from, to, t) { + return { + h: interpolateHue(from.h, to.h, t), + c: number(from.c, to.c, t), + l: number(from.l, to.l, t), + alpha: number(from.alpha, to.alpha, t) + }; +} +var lab = { + forward: rgbToLab, + reverse: labToRgb, + interpolate: interpolateLab +}; +var hcl = { + forward: rgbToHcl, + reverse: hclToRgb, + interpolate: interpolateHcl +}; + +var colorSpaces = /*#__PURE__*/Object.freeze({ + __proto__: null, + lab: lab, + hcl: hcl +}); + +var Interpolate = function Interpolate(type, operator, interpolation, input, stops) { + this.type = type; + this.operator = operator; + this.interpolation = interpolation; + this.input = input; + this.labels = []; + this.outputs = []; + for (var i = 0, list = stops; i < list.length; i += 1) { + var ref = list[i]; + var label = ref[0]; + var expression = ref[1]; + this.labels.push(label); + this.outputs.push(expression); + } +}; +Interpolate.interpolationFactor = function interpolationFactor(interpolation, input, lower, upper) { + var t = 0; + if (interpolation.name === 'exponential') { + t = exponentialInterpolation(input, interpolation.base, lower, upper); + } else if (interpolation.name === 'linear') { + t = exponentialInterpolation(input, 1, lower, upper); + } else if (interpolation.name === 'cubic-bezier') { + var c = interpolation.controlPoints; + var ub = new unitbezier(c[0], c[1], c[2], c[3]); + t = ub.solve(exponentialInterpolation(input, 1, lower, upper)); + } + return t; +}; +Interpolate.parse = function parse(args, context) { + var operator = args[0]; + var interpolation = args[1]; + var input = args[2]; + var rest = args.slice(3); + if (!Array.isArray(interpolation) || interpolation.length === 0) { + return context.error('Expected an interpolation type expression.', 1); + } + if (interpolation[0] === 'linear') { + interpolation = { name: 'linear' }; + } else if (interpolation[0] === 'exponential') { + var base = interpolation[1]; + if (typeof base !== 'number') { + return context.error('Exponential interpolation requires a numeric base.', 1, 1); + } + interpolation = { + name: 'exponential', + base: base + }; + } else if (interpolation[0] === 'cubic-bezier') { + var controlPoints = interpolation.slice(1); + if (controlPoints.length !== 4 || controlPoints.some(function (t) { + return typeof t !== 'number' || t < 0 || t > 1; + })) { + return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1); + } + interpolation = { + name: 'cubic-bezier', + controlPoints: controlPoints + }; + } else { + return context.error('Unknown interpolation type ' + String(interpolation[0]), 1, 0); + } + if (args.length - 1 < 4) { + return context.error('Expected at least 4 arguments, but found only ' + (args.length - 1) + '.'); + } + if ((args.length - 1) % 2 !== 0) { + return context.error('Expected an even number of arguments.'); + } + input = context.parse(input, 2, NumberType); + if (!input) { + return null; + } + var stops = []; + var outputType = null; + if (operator === 'interpolate-hcl' || operator === 'interpolate-lab') { + outputType = ColorType; + } else if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + for (var i = 0; i < rest.length; i += 2) { + var label = rest[i]; + var value = rest[i + 1]; + var labelKey = i + 3; + var valueKey = i + 4; + if (typeof label !== 'number') { + return context.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + var parsed = context.parse(value, valueKey, outputType); + if (!parsed) { + return null; + } + outputType = outputType || parsed.type; + stops.push([ + label, + parsed + ]); + } + if (outputType.kind !== 'number' && outputType.kind !== 'color' && !(outputType.kind === 'array' && outputType.itemType.kind === 'number' && typeof outputType.N === 'number')) { + return context.error('Type ' + toString(outputType) + ' is not interpolatable.'); + } + return new Interpolate(outputType, operator, interpolation, input, stops); +}; +Interpolate.prototype.evaluate = function evaluate(ctx) { + var labels = this.labels; + var outputs = this.outputs; + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + var value = this.input.evaluate(ctx); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + var stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + var index = findStopLessThanOrEqualTo(labels, value); + var lower = labels[index]; + var upper = labels[index + 1]; + var t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper); + var outputLower = outputs[index].evaluate(ctx); + var outputUpper = outputs[index + 1].evaluate(ctx); + if (this.operator === 'interpolate') { + return interpolate[this.type.kind.toLowerCase()](outputLower, outputUpper, t); + } else if (this.operator === 'interpolate-hcl') { + return hcl.reverse(hcl.interpolate(hcl.forward(outputLower), hcl.forward(outputUpper), t)); + } else { + return lab.reverse(lab.interpolate(lab.forward(outputLower), lab.forward(outputUpper), t)); + } +}; +Interpolate.prototype.eachChild = function eachChild(fn) { + fn(this.input); + for (var i = 0, list = this.outputs; i < list.length; i += 1) { + var expression = list[i]; + fn(expression); + } +}; +Interpolate.prototype.outputDefined = function outputDefined() { + return this.outputs.every(function (out) { + return out.outputDefined(); + }); +}; +Interpolate.prototype.serialize = function serialize() { + var interpolation; + if (this.interpolation.name === 'linear') { + interpolation = ['linear']; + } else if (this.interpolation.name === 'exponential') { + if (this.interpolation.base === 1) { + interpolation = ['linear']; + } else { + interpolation = [ + 'exponential', + this.interpolation.base + ]; + } + } else { + interpolation = ['cubic-bezier'].concat(this.interpolation.controlPoints); + } + var serialized = [ + this.operator, + interpolation, + this.input.serialize() + ]; + for (var i = 0; i < this.labels.length; i++) { + serialized.push(this.labels[i], this.outputs[i].serialize()); + } + return serialized; +}; +function exponentialInterpolation(input, base, lowerValue, upperValue) { + var difference = upperValue - lowerValue; + var progress = input - lowerValue; + if (difference === 0) { + return 0; + } else if (base === 1) { + return progress / difference; + } else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } +} + +var Coalesce = function Coalesce(type, args) { + this.type = type; + this.args = args; +}; +Coalesce.parse = function parse(args, context) { + if (args.length < 2) { + return context.error('Expectected at least one argument.'); + } + var outputType = null; + var expectedType = context.expectedType; + if (expectedType && expectedType.kind !== 'value') { + outputType = expectedType; + } + var parsedArgs = []; + for (var i = 0, list = args.slice(1); i < list.length; i += 1) { + var arg = list[i]; + var parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, { typeAnnotation: 'omit' }); + if (!parsed) { + return null; + } + outputType = outputType || parsed.type; + parsedArgs.push(parsed); + } + var needsAnnotation = expectedType && parsedArgs.some(function (arg) { + return checkSubtype(expectedType, arg.type); + }); + return needsAnnotation ? new Coalesce(ValueType, parsedArgs) : new Coalesce(outputType, parsedArgs); +}; +Coalesce.prototype.evaluate = function evaluate(ctx) { + var result = null; + var argCount = 0; + var requestedImageName; + for (var i = 0, list = this.args; i < list.length; i += 1) { + var arg = list[i]; + argCount++; + result = arg.evaluate(ctx); + if (result && result instanceof ResolvedImage && !result.available) { + if (!requestedImageName) { + requestedImageName = result.name; + } + result = null; + if (argCount === this.args.length) { + result = requestedImageName; + } + } + if (result !== null) { + break; + } + } + return result; +}; +Coalesce.prototype.eachChild = function eachChild(fn) { + this.args.forEach(fn); +}; +Coalesce.prototype.outputDefined = function outputDefined() { + return this.args.every(function (arg) { + return arg.outputDefined(); + }); +}; +Coalesce.prototype.serialize = function serialize() { + var serialized = ['coalesce']; + this.eachChild(function (child) { + serialized.push(child.serialize()); + }); + return serialized; +}; + +var Let = function Let(bindings, result) { + this.type = result.type; + this.bindings = [].concat(bindings); + this.result = result; +}; +Let.prototype.evaluate = function evaluate(ctx) { + return this.result.evaluate(ctx); +}; +Let.prototype.eachChild = function eachChild(fn) { + for (var i = 0, list = this.bindings; i < list.length; i += 1) { + var binding = list[i]; + fn(binding[1]); + } + fn(this.result); +}; +Let.parse = function parse(args, context) { + if (args.length < 4) { + return context.error('Expected at least 3 arguments, but found ' + (args.length - 1) + ' instead.'); + } + var bindings = []; + for (var i = 1; i < args.length - 1; i += 2) { + var name = args[i]; + if (typeof name !== 'string') { + return context.error('Expected string, but found ' + typeof name + ' instead.', i); + } + if (/[^a-zA-Z0-9_]/.test(name)) { + return context.error('Variable names must contain only alphanumeric characters or \'_\'.', i); + } + var value = context.parse(args[i + 1], i + 1); + if (!value) { + return null; + } + bindings.push([ + name, + value + ]); + } + var result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings); + if (!result) { + return null; + } + return new Let(bindings, result); +}; +Let.prototype.outputDefined = function outputDefined() { + return this.result.outputDefined(); +}; +Let.prototype.serialize = function serialize() { + var serialized = ['let']; + for (var i = 0, list = this.bindings; i < list.length; i += 1) { + var ref = list[i]; + var name = ref[0]; + var expr = ref[1]; + serialized.push(name, expr.serialize()); + } + serialized.push(this.result.serialize()); + return serialized; +}; + +var At = function At(type, index, input) { + this.type = type; + this.index = index; + this.input = input; +}; +At.parse = function parse(args, context) { + if (args.length !== 3) { + return context.error('Expected 2 arguments, but found ' + (args.length - 1) + ' instead.'); + } + var index = context.parse(args[1], 1, NumberType); + var input = context.parse(args[2], 2, array(context.expectedType || ValueType)); + if (!index || !input) { + return null; + } + var t = input.type; + return new At(t.itemType, index, input); +}; +At.prototype.evaluate = function evaluate(ctx) { + var index = this.index.evaluate(ctx); + var array = this.input.evaluate(ctx); + if (index < 0) { + throw new RuntimeError('Array index out of bounds: ' + index + ' < 0.'); + } + if (index >= array.length) { + throw new RuntimeError('Array index out of bounds: ' + index + ' > ' + (array.length - 1) + '.'); + } + if (index !== Math.floor(index)) { + throw new RuntimeError('Array index must be an integer, but found ' + index + ' instead.'); + } + return array[index]; +}; +At.prototype.eachChild = function eachChild(fn) { + fn(this.index); + fn(this.input); +}; +At.prototype.outputDefined = function outputDefined() { + return false; +}; +At.prototype.serialize = function serialize() { + return [ + 'at', + this.index.serialize(), + this.input.serialize() + ]; +}; + +var In = function In(needle, haystack) { + this.type = BooleanType; + this.needle = needle; + this.haystack = haystack; +}; +In.parse = function parse(args, context) { + if (args.length !== 3) { + return context.error('Expected 2 arguments, but found ' + (args.length - 1) + ' instead.'); + } + var needle = context.parse(args[1], 1, ValueType); + var haystack = context.parse(args[2], 2, ValueType); + if (!needle || !haystack) { + return null; + } + if (!isValidType(needle.type, [ + BooleanType, + StringType, + NumberType, + NullType, + ValueType + ])) { + return context.error('Expected first argument to be of type boolean, string, number or null, but found ' + toString(needle.type) + ' instead'); + } + return new In(needle, haystack); +}; +In.prototype.evaluate = function evaluate(ctx) { + var needle = this.needle.evaluate(ctx); + var haystack = this.haystack.evaluate(ctx); + if (!haystack) { + return false; + } + if (!isValidNativeType(needle, [ + 'boolean', + 'string', + 'number', + 'null' + ])) { + throw new RuntimeError('Expected first argument to be of type boolean, string, number or null, but found ' + toString(typeOf(needle)) + ' instead.'); + } + if (!isValidNativeType(haystack, [ + 'string', + 'array' + ])) { + throw new RuntimeError('Expected second argument to be of type array or string, but found ' + toString(typeOf(haystack)) + ' instead.'); + } + return haystack.indexOf(needle) >= 0; +}; +In.prototype.eachChild = function eachChild(fn) { + fn(this.needle); + fn(this.haystack); +}; +In.prototype.outputDefined = function outputDefined() { + return true; +}; +In.prototype.serialize = function serialize() { + return [ + 'in', + this.needle.serialize(), + this.haystack.serialize() + ]; +}; + +var IndexOf = function IndexOf(needle, haystack, fromIndex) { + this.type = NumberType; + this.needle = needle; + this.haystack = haystack; + this.fromIndex = fromIndex; +}; +IndexOf.parse = function parse(args, context) { + if (args.length <= 2 || args.length >= 5) { + return context.error('Expected 3 or 4 arguments, but found ' + (args.length - 1) + ' instead.'); + } + var needle = context.parse(args[1], 1, ValueType); + var haystack = context.parse(args[2], 2, ValueType); + if (!needle || !haystack) { + return null; + } + if (!isValidType(needle.type, [ + BooleanType, + StringType, + NumberType, + NullType, + ValueType + ])) { + return context.error('Expected first argument to be of type boolean, string, number or null, but found ' + toString(needle.type) + ' instead'); + } + if (args.length === 4) { + var fromIndex = context.parse(args[3], 3, NumberType); + if (!fromIndex) { + return null; + } + return new IndexOf(needle, haystack, fromIndex); + } else { + return new IndexOf(needle, haystack); + } +}; +IndexOf.prototype.evaluate = function evaluate(ctx) { + var needle = this.needle.evaluate(ctx); + var haystack = this.haystack.evaluate(ctx); + if (!isValidNativeType(needle, [ + 'boolean', + 'string', + 'number', + 'null' + ])) { + throw new RuntimeError('Expected first argument to be of type boolean, string, number or null, but found ' + toString(typeOf(needle)) + ' instead.'); + } + if (!isValidNativeType(haystack, [ + 'string', + 'array' + ])) { + throw new RuntimeError('Expected second argument to be of type array or string, but found ' + toString(typeOf(haystack)) + ' instead.'); + } + if (this.fromIndex) { + var fromIndex = this.fromIndex.evaluate(ctx); + return haystack.indexOf(needle, fromIndex); + } + return haystack.indexOf(needle); +}; +IndexOf.prototype.eachChild = function eachChild(fn) { + fn(this.needle); + fn(this.haystack); + if (this.fromIndex) { + fn(this.fromIndex); + } +}; +IndexOf.prototype.outputDefined = function outputDefined() { + return false; +}; +IndexOf.prototype.serialize = function serialize() { + if (this.fromIndex != null && this.fromIndex !== undefined) { + var fromIndex = this.fromIndex.serialize(); + return [ + 'index-of', + this.needle.serialize(), + this.haystack.serialize(), + fromIndex + ]; + } + return [ + 'index-of', + this.needle.serialize(), + this.haystack.serialize() + ]; +}; + +var Match = function Match(inputType, outputType, input, cases, outputs, otherwise) { + this.inputType = inputType; + this.type = outputType; + this.input = input; + this.cases = cases; + this.outputs = outputs; + this.otherwise = otherwise; +}; +Match.parse = function parse(args, context) { + if (args.length < 5) { + return context.error('Expected at least 4 arguments, but found only ' + (args.length - 1) + '.'); + } + if (args.length % 2 !== 1) { + return context.error('Expected an even number of arguments.'); + } + var inputType; + var outputType; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + var cases = {}; + var outputs = []; + for (var i = 2; i < args.length - 1; i += 2) { + var labels = args[i]; + var value = args[i + 1]; + if (!Array.isArray(labels)) { + labels = [labels]; + } + var labelContext = context.concat(i); + if (labels.length === 0) { + return labelContext.error('Expected at least one branch label.'); + } + for (var i$1 = 0, list = labels; i$1 < list.length; i$1 += 1) { + var label = list[i$1]; + if (typeof label !== 'number' && typeof label !== 'string') { + return labelContext.error('Branch labels must be numbers or strings.'); + } else if (typeof label === 'number' && Math.abs(label) > Number.MAX_SAFE_INTEGER) { + return labelContext.error('Branch labels must be integers no larger than ' + Number.MAX_SAFE_INTEGER + '.'); + } else if (typeof label === 'number' && Math.floor(label) !== label) { + return labelContext.error('Numeric branch labels must be integer values.'); + } else if (!inputType) { + inputType = typeOf(label); + } else if (labelContext.checkSubtype(inputType, typeOf(label))) { + return null; + } + if (typeof cases[String(label)] !== 'undefined') { + return labelContext.error('Branch labels must be unique.'); + } + cases[String(label)] = outputs.length; + } + var result = context.parse(value, i, outputType); + if (!result) { + return null; + } + outputType = outputType || result.type; + outputs.push(result); + } + var input = context.parse(args[1], 1, ValueType); + if (!input) { + return null; + } + var otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) { + return null; + } + if (input.type.kind !== 'value' && context.concat(1).checkSubtype(inputType, input.type)) { + return null; + } + return new Match(inputType, outputType, input, cases, outputs, otherwise); +}; +Match.prototype.evaluate = function evaluate(ctx) { + var input = this.input.evaluate(ctx); + var output = typeOf(input) === this.inputType && this.outputs[this.cases[input]] || this.otherwise; + return output.evaluate(ctx); +}; +Match.prototype.eachChild = function eachChild(fn) { + fn(this.input); + this.outputs.forEach(fn); + fn(this.otherwise); +}; +Match.prototype.outputDefined = function outputDefined() { + return this.outputs.every(function (out) { + return out.outputDefined(); + }) && this.otherwise.outputDefined(); +}; +Match.prototype.serialize = function serialize() { + var this$1 = this; + var serialized = [ + 'match', + this.input.serialize() + ]; + var sortedLabels = Object.keys(this.cases).sort(); + var groupedByOutput = []; + var outputLookup = {}; + for (var i = 0, list = sortedLabels; i < list.length; i += 1) { + var label = list[i]; + var outputIndex = outputLookup[this.cases[label]]; + if (outputIndex === undefined) { + outputLookup[this.cases[label]] = groupedByOutput.length; + groupedByOutput.push([ + this.cases[label], + [label] + ]); + } else { + groupedByOutput[outputIndex][1].push(label); + } + } + var coerceLabel = function (label) { + return this$1.inputType.kind === 'number' ? Number(label) : label; + }; + for (var i$1 = 0, list$1 = groupedByOutput; i$1 < list$1.length; i$1 += 1) { + var ref = list$1[i$1]; + var outputIndex = ref[0]; + var labels = ref[1]; + if (labels.length === 1) { + serialized.push(coerceLabel(labels[0])); + } else { + serialized.push(labels.map(coerceLabel)); + } + serialized.push(this.outputs[outputIndex$1].serialize()); + } + serialized.push(this.otherwise.serialize()); + return serialized; +}; + +var Case = function Case(type, branches, otherwise) { + this.type = type; + this.branches = branches; + this.otherwise = otherwise; +}; +Case.parse = function parse(args, context) { + if (args.length < 4) { + return context.error('Expected at least 3 arguments, but found only ' + (args.length - 1) + '.'); + } + if (args.length % 2 !== 0) { + return context.error('Expected an odd number of arguments.'); + } + var outputType; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + var branches = []; + for (var i = 1; i < args.length - 1; i += 2) { + var test = context.parse(args[i], i, BooleanType); + if (!test) { + return null; + } + var result = context.parse(args[i + 1], i + 1, outputType); + if (!result) { + return null; + } + branches.push([ + test, + result + ]); + outputType = outputType || result.type; + } + var otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) { + return null; + } + return new Case(outputType, branches, otherwise); +}; +Case.prototype.evaluate = function evaluate(ctx) { + for (var i = 0, list = this.branches; i < list.length; i += 1) { + var ref = list[i]; + var test = ref[0]; + var expression = ref[1]; + if (test.evaluate(ctx)) { + return expression.evaluate(ctx); + } + } + return this.otherwise.evaluate(ctx); +}; +Case.prototype.eachChild = function eachChild(fn) { + for (var i = 0, list = this.branches; i < list.length; i += 1) { + var ref = list[i]; + var test = ref[0]; + var expression = ref[1]; + fn(test); + fn(expression); + } + fn(this.otherwise); +}; +Case.prototype.outputDefined = function outputDefined() { + return this.branches.every(function (ref) { + var _ = ref[0]; + var out = ref[1]; + return out.outputDefined(); + }) && this.otherwise.outputDefined(); +}; +Case.prototype.serialize = function serialize() { + var serialized = ['case']; + this.eachChild(function (child) { + serialized.push(child.serialize()); + }); + return serialized; +}; + +var Slice = function Slice(type, input, beginIndex, endIndex) { + this.type = type; + this.input = input; + this.beginIndex = beginIndex; + this.endIndex = endIndex; +}; +Slice.parse = function parse(args, context) { + if (args.length <= 2 || args.length >= 5) { + return context.error('Expected 3 or 4 arguments, but found ' + (args.length - 1) + ' instead.'); + } + var input = context.parse(args[1], 1, ValueType); + var beginIndex = context.parse(args[2], 2, NumberType); + if (!input || !beginIndex) { + return null; + } + if (!isValidType(input.type, [ + array(ValueType), + StringType, + ValueType + ])) { + return context.error('Expected first argument to be of type array or string, but found ' + toString(input.type) + ' instead'); + } + if (args.length === 4) { + var endIndex = context.parse(args[3], 3, NumberType); + if (!endIndex) { + return null; + } + return new Slice(input.type, input, beginIndex, endIndex); + } else { + return new Slice(input.type, input, beginIndex); + } +}; +Slice.prototype.evaluate = function evaluate(ctx) { + var input = this.input.evaluate(ctx); + var beginIndex = this.beginIndex.evaluate(ctx); + if (!isValidNativeType(input, [ + 'string', + 'array' + ])) { + throw new RuntimeError('Expected first argument to be of type array or string, but found ' + toString(typeOf(input)) + ' instead.'); + } + if (this.endIndex) { + var endIndex = this.endIndex.evaluate(ctx); + return input.slice(beginIndex, endIndex); + } + return input.slice(beginIndex); +}; +Slice.prototype.eachChild = function eachChild(fn) { + fn(this.input); + fn(this.beginIndex); + if (this.endIndex) { + fn(this.endIndex); + } +}; +Slice.prototype.outputDefined = function outputDefined() { + return false; +}; +Slice.prototype.serialize = function serialize() { + if (this.endIndex != null && this.endIndex !== undefined) { + var endIndex = this.endIndex.serialize(); + return [ + 'slice', + this.input.serialize(), + this.beginIndex.serialize(), + endIndex + ]; + } + return [ + 'slice', + this.input.serialize(), + this.beginIndex.serialize() + ]; +}; + +function isComparableType(op, type) { + if (op === '==' || op === '!=') { + return type.kind === 'boolean' || type.kind === 'string' || type.kind === 'number' || type.kind === 'null' || type.kind === 'value'; + } else { + return type.kind === 'string' || type.kind === 'number' || type.kind === 'value'; + } +} +function eq(ctx, a, b) { + return a === b; +} +function neq(ctx, a, b) { + return a !== b; +} +function lt(ctx, a, b) { + return a < b; +} +function gt(ctx, a, b) { + return a > b; +} +function lteq(ctx, a, b) { + return a <= b; +} +function gteq(ctx, a, b) { + return a >= b; +} +function eqCollate(ctx, a, b, c) { + return c.compare(a, b) === 0; +} +function neqCollate(ctx, a, b, c) { + return !eqCollate(ctx, a, b, c); +} +function ltCollate(ctx, a, b, c) { + return c.compare(a, b) < 0; +} +function gtCollate(ctx, a, b, c) { + return c.compare(a, b) > 0; +} +function lteqCollate(ctx, a, b, c) { + return c.compare(a, b) <= 0; +} +function gteqCollate(ctx, a, b, c) { + return c.compare(a, b) >= 0; +} +function makeComparison(op, compareBasic, compareWithCollator) { + var isOrderComparison = op !== '==' && op !== '!='; + return function () { + function Comparison(lhs, rhs, collator) { + this.type = BooleanType; + this.lhs = lhs; + this.rhs = rhs; + this.collator = collator; + this.hasUntypedArgument = lhs.type.kind === 'value' || rhs.type.kind === 'value'; + } + Comparison.parse = function parse(args, context) { + if (args.length !== 3 && args.length !== 4) { + return context.error('Expected two or three arguments.'); + } + var op = args[0]; + var lhs = context.parse(args[1], 1, ValueType); + if (!lhs) { + return null; + } + if (!isComparableType(op, lhs.type)) { + return context.concat(1).error('"' + op + '" comparisons are not supported for type \'' + toString(lhs.type) + '\'.'); + } + var rhs = context.parse(args[2], 2, ValueType); + if (!rhs) { + return null; + } + if (!isComparableType(op, rhs.type)) { + return context.concat(2).error('"' + op + '" comparisons are not supported for type \'' + toString(rhs.type) + '\'.'); + } + if (lhs.type.kind !== rhs.type.kind && lhs.type.kind !== 'value' && rhs.type.kind !== 'value') { + return context.error('Cannot compare types \'' + toString(lhs.type) + '\' and \'' + toString(rhs.type) + '\'.'); + } + if (isOrderComparison) { + if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') { + lhs = new Assertion(rhs.type, [lhs]); + } else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') { + rhs = new Assertion(lhs.type, [rhs]); + } + } + var collator = null; + if (args.length === 4) { + if (lhs.type.kind !== 'string' && rhs.type.kind !== 'string' && lhs.type.kind !== 'value' && rhs.type.kind !== 'value') { + return context.error('Cannot use collator to compare non-string types.'); + } + collator = context.parse(args[3], 3, CollatorType); + if (!collator) { + return null; + } + } + return new Comparison(lhs, rhs, collator); + }; + Comparison.prototype.evaluate = function evaluate(ctx) { + var lhs = this.lhs.evaluate(ctx); + var rhs = this.rhs.evaluate(ctx); + if (isOrderComparison && this.hasUntypedArgument) { + var lt = typeOf(lhs); + var rt = typeOf(rhs); + if (lt.kind !== rt.kind || !(lt.kind === 'string' || lt.kind === 'number')) { + throw new RuntimeError('Expected arguments for "' + op + '" to be (string, string) or (number, number), but found (' + lt.kind + ', ' + rt.kind + ') instead.'); + } + } + if (this.collator && !isOrderComparison && this.hasUntypedArgument) { + var lt$1 = typeOf(lhs); + var rt$1 = typeOf(rhs); + if (lt$1.kind !== 'string' || rt$1.kind !== 'string') { + return compareBasic(ctx, lhs, rhs); + } + } + return this.collator ? compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) : compareBasic(ctx, lhs, rhs); + }; + Comparison.prototype.eachChild = function eachChild(fn) { + fn(this.lhs); + fn(this.rhs); + if (this.collator) { + fn(this.collator); + } + }; + Comparison.prototype.outputDefined = function outputDefined() { + return true; + }; + Comparison.prototype.serialize = function serialize() { + var serialized = [op]; + this.eachChild(function (child) { + serialized.push(child.serialize()); + }); + return serialized; + }; + return Comparison; + }(); +} +var Equals = makeComparison('==', eq, eqCollate); +var NotEquals = makeComparison('!=', neq, neqCollate); +var LessThan = makeComparison('<', lt, ltCollate); +var GreaterThan = makeComparison('>', gt, gtCollate); +var LessThanOrEqual = makeComparison('<=', lteq, lteqCollate); +var GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate); + +var NumberFormat = function NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits) { + this.type = StringType; + this.number = number; + this.locale = locale; + this.currency = currency; + this.minFractionDigits = minFractionDigits; + this.maxFractionDigits = maxFractionDigits; +}; +NumberFormat.parse = function parse(args, context) { + if (args.length !== 3) { + return context.error('Expected two arguments.'); + } + var number = context.parse(args[1], 1, NumberType); + if (!number) { + return null; + } + var options = args[2]; + if (typeof options !== 'object' || Array.isArray(options)) { + return context.error('NumberFormat options argument must be an object.'); + } + var locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) { + return null; + } + } + var currency = null; + if (options['currency']) { + currency = context.parse(options['currency'], 1, StringType); + if (!currency) { + return null; + } + } + var minFractionDigits = null; + if (options['min-fraction-digits']) { + minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType); + if (!minFractionDigits) { + return null; + } + } + var maxFractionDigits = null; + if (options['max-fraction-digits']) { + maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType); + if (!maxFractionDigits) { + return null; + } + } + return new NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits); +}; +NumberFormat.prototype.evaluate = function evaluate(ctx) { + return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], { + style: this.currency ? 'currency' : 'decimal', + currency: this.currency ? this.currency.evaluate(ctx) : undefined, + minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : undefined, + maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : undefined + }).format(this.number.evaluate(ctx)); +}; +NumberFormat.prototype.eachChild = function eachChild(fn) { + fn(this.number); + if (this.locale) { + fn(this.locale); + } + if (this.currency) { + fn(this.currency); + } + if (this.minFractionDigits) { + fn(this.minFractionDigits); + } + if (this.maxFractionDigits) { + fn(this.maxFractionDigits); + } +}; +NumberFormat.prototype.outputDefined = function outputDefined() { + return false; +}; +NumberFormat.prototype.serialize = function serialize() { + var options = {}; + if (this.locale) { + options['locale'] = this.locale.serialize(); + } + if (this.currency) { + options['currency'] = this.currency.serialize(); + } + if (this.minFractionDigits) { + options['min-fraction-digits'] = this.minFractionDigits.serialize(); + } + if (this.maxFractionDigits) { + options['max-fraction-digits'] = this.maxFractionDigits.serialize(); + } + return [ + 'number-format', + this.number.serialize(), + options + ]; +}; + +var Length = function Length(input) { + this.type = NumberType; + this.input = input; +}; +Length.parse = function parse(args, context) { + if (args.length !== 2) { + return context.error('Expected 1 argument, but found ' + (args.length - 1) + ' instead.'); + } + var input = context.parse(args[1], 1); + if (!input) { + return null; + } + if (input.type.kind !== 'array' && input.type.kind !== 'string' && input.type.kind !== 'value') { + return context.error('Expected argument of type string or array, but found ' + toString(input.type) + ' instead.'); + } + return new Length(input); +}; +Length.prototype.evaluate = function evaluate(ctx) { + var input = this.input.evaluate(ctx); + if (typeof input === 'string') { + return input.length; + } else if (Array.isArray(input)) { + return input.length; + } else { + throw new RuntimeError('Expected value to be of type string or array, but found ' + toString(typeOf(input)) + ' instead.'); + } +}; +Length.prototype.eachChild = function eachChild(fn) { + fn(this.input); +}; +Length.prototype.outputDefined = function outputDefined() { + return false; +}; +Length.prototype.serialize = function serialize() { + var serialized = ['length']; + this.eachChild(function (child) { + serialized.push(child.serialize()); + }); + return serialized; +}; + +var expressions = { + '==': Equals, + '!=': NotEquals, + '>': GreaterThan, + '<': LessThan, + '>=': GreaterThanOrEqual, + '<=': LessThanOrEqual, + 'array': Assertion, + 'at': At, + 'boolean': Assertion, + 'case': Case, + 'coalesce': Coalesce, + 'collator': CollatorExpression, + 'format': FormatExpression, + 'image': ImageExpression, + 'in': In, + 'index-of': IndexOf, + 'interpolate': Interpolate, + 'interpolate-hcl': Interpolate, + 'interpolate-lab': Interpolate, + 'length': Length, + 'let': Let, + 'literal': Literal, + 'match': Match, + 'number': Assertion, + 'number-format': NumberFormat, + 'object': Assertion, + 'slice': Slice, + 'step': Step, + 'string': Assertion, + 'to-boolean': Coercion, + 'to-color': Coercion, + 'to-number': Coercion, + 'to-string': Coercion, + 'var': Var, + 'within': Within +}; +function rgba(ctx, ref) { + var r = ref[0]; + var g = ref[1]; + var b = ref[2]; + var a = ref[3]; + r = r.evaluate(ctx); + g = g.evaluate(ctx); + b = b.evaluate(ctx); + var alpha = a ? a.evaluate(ctx) : 1; + var error = validateRGBA(r, g, b, alpha); + if (error) { + throw new RuntimeError(error); + } + return new Color(r / 255 * alpha, g / 255 * alpha, b / 255 * alpha, alpha); +} +function has(key, obj) { + return key in obj; +} +function get(key, obj) { + var v = obj[key]; + return typeof v === 'undefined' ? null : v; +} +function binarySearch(v, a, i, j) { + while (i <= j) { + var m = i + j >> 1; + if (a[m] === v) { + return true; + } + if (a[m] > v) { + j = m - 1; + } else { + i = m + 1; + } + } + return false; +} +function varargs(type) { + return { type: type }; +} +CompoundExpression.register(expressions, { + 'error': [ + ErrorType, + [StringType], + function (ctx, ref) { + var v = ref[0]; + throw new RuntimeError(v.evaluate(ctx)); + } + ], + 'typeof': [ + StringType, + [ValueType], + function (ctx, ref) { + var v = ref[0]; + return toString(typeOf(v.evaluate(ctx))); + } + ], + 'to-rgba': [ + array(NumberType, 4), + [ColorType], + function (ctx, ref) { + var v = ref[0]; + return v.evaluate(ctx).toArray(); + } + ], + 'rgb': [ + ColorType, + [ + NumberType, + NumberType, + NumberType + ], + rgba + ], + 'rgba': [ + ColorType, + [ + NumberType, + NumberType, + NumberType, + NumberType + ], + rgba + ], + 'has': { + type: BooleanType, + overloads: [ + [ + [StringType], + function (ctx, ref) { + var key = ref[0]; + return has(key.evaluate(ctx), ctx.properties()); + } + ], + [ + [ + StringType, + ObjectType + ], + function (ctx, ref) { + var key = ref[0]; + var obj = ref[1]; + return has(key.evaluate(ctx), obj.evaluate(ctx)); + } + ] + ] + }, + 'get': { + type: ValueType, + overloads: [ + [ + [StringType], + function (ctx, ref) { + var key = ref[0]; + return get(key.evaluate(ctx), ctx.properties()); + } + ], + [ + [ + StringType, + ObjectType + ], + function (ctx, ref) { + var key = ref[0]; + var obj = ref[1]; + return get(key.evaluate(ctx), obj.evaluate(ctx)); + } + ] + ] + }, + 'feature-state': [ + ValueType, + [StringType], + function (ctx, ref) { + var key = ref[0]; + return get(key.evaluate(ctx), ctx.featureState || {}); + } + ], + 'properties': [ + ObjectType, + [], + function (ctx) { + return ctx.properties(); + } + ], + 'geometry-type': [ + StringType, + [], + function (ctx) { + return ctx.geometryType(); + } + ], + 'id': [ + ValueType, + [], + function (ctx) { + return ctx.id(); + } + ], + 'zoom': [ + NumberType, + [], + function (ctx) { + return ctx.globals.zoom; + } + ], + 'heatmap-density': [ + NumberType, + [], + function (ctx) { + return ctx.globals.heatmapDensity || 0; + } + ], + 'line-progress': [ + NumberType, + [], + function (ctx) { + return ctx.globals.lineProgress || 0; + } + ], + 'accumulated': [ + ValueType, + [], + function (ctx) { + return ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated; + } + ], + '+': [ + NumberType, + varargs(NumberType), + function (ctx, args) { + var result = 0; + for (var i = 0, list = args; i < list.length; i += 1) { + var arg = list[i]; + result += arg.evaluate(ctx); + } + return result; + } + ], + '*': [ + NumberType, + varargs(NumberType), + function (ctx, args) { + var result = 1; + for (var i = 0, list = args; i < list.length; i += 1) { + var arg = list[i]; + result *= arg.evaluate(ctx); + } + return result; + } + ], + '-': { + type: NumberType, + overloads: [ + [ + [ + NumberType, + NumberType + ], + function (ctx, ref) { + var a = ref[0]; + var b = ref[1]; + return a.evaluate(ctx) - b.evaluate(ctx); + } + ], + [ + [NumberType], + function (ctx, ref) { + var a = ref[0]; + return -a.evaluate(ctx); + } + ] + ] + }, + '/': [ + NumberType, + [ + NumberType, + NumberType + ], + function (ctx, ref) { + var a = ref[0]; + var b = ref[1]; + return a.evaluate(ctx) / b.evaluate(ctx); + } + ], + '%': [ + NumberType, + [ + NumberType, + NumberType + ], + function (ctx, ref) { + var a = ref[0]; + var b = ref[1]; + return a.evaluate(ctx) % b.evaluate(ctx); + } + ], + 'ln2': [ + NumberType, + [], + function () { + return Math.LN2; + } + ], + 'pi': [ + NumberType, + [], + function () { + return Math.PI; + } + ], + 'e': [ + NumberType, + [], + function () { + return Math.E; + } + ], + '^': [ + NumberType, + [ + NumberType, + NumberType + ], + function (ctx, ref) { + var b = ref[0]; + var e = ref[1]; + return Math.pow(b.evaluate(ctx), e.evaluate(ctx)); + } + ], + 'sqrt': [ + NumberType, + [NumberType], + function (ctx, ref) { + var x = ref[0]; + return Math.sqrt(x.evaluate(ctx)); + } + ], + 'log10': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.log(n.evaluate(ctx)) / Math.LN10; + } + ], + 'ln': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.log(n.evaluate(ctx)); + } + ], + 'log2': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.log(n.evaluate(ctx)) / Math.LN2; + } + ], + 'sin': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.sin(n.evaluate(ctx)); + } + ], + 'cos': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.cos(n.evaluate(ctx)); + } + ], + 'tan': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.tan(n.evaluate(ctx)); + } + ], + 'asin': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.asin(n.evaluate(ctx)); + } + ], + 'acos': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.acos(n.evaluate(ctx)); + } + ], + 'atan': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.atan(n.evaluate(ctx)); + } + ], + 'min': [ + NumberType, + varargs(NumberType), + function (ctx, args) { + return Math.min.apply(Math, args.map(function (arg) { + return arg.evaluate(ctx); + })); + } + ], + 'max': [ + NumberType, + varargs(NumberType), + function (ctx, args) { + return Math.max.apply(Math, args.map(function (arg) { + return arg.evaluate(ctx); + })); + } + ], + 'abs': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.abs(n.evaluate(ctx)); + } + ], + 'round': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + var v = n.evaluate(ctx); + return v < 0 ? -Math.round(-v) : Math.round(v); + } + ], + 'floor': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.floor(n.evaluate(ctx)); + } + ], + 'ceil': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.ceil(n.evaluate(ctx)); + } + ], + 'filter-==': [ + BooleanType, + [ + StringType, + ValueType + ], + function (ctx, ref) { + var k = ref[0]; + var v = ref[1]; + return ctx.properties()[k.value] === v.value; + } + ], + 'filter-id-==': [ + BooleanType, + [ValueType], + function (ctx, ref) { + var v = ref[0]; + return ctx.id() === v.value; + } + ], + 'filter-type-==': [ + BooleanType, + [StringType], + function (ctx, ref) { + var v = ref[0]; + return ctx.geometryType() === v.value; + } + ], + 'filter-<': [ + BooleanType, + [ + StringType, + ValueType + ], + function (ctx, ref) { + var k = ref[0]; + var v = ref[1]; + var a = ctx.properties()[k.value]; + var b = v.value; + return typeof a === typeof b && a < b; + } + ], + 'filter-id-<': [ + BooleanType, + [ValueType], + function (ctx, ref) { + var v = ref[0]; + var a = ctx.id(); + var b = v.value; + return typeof a === typeof b && a < b; + } + ], + 'filter->': [ + BooleanType, + [ + StringType, + ValueType + ], + function (ctx, ref) { + var k = ref[0]; + var v = ref[1]; + var a = ctx.properties()[k.value]; + var b = v.value; + return typeof a === typeof b && a > b; + } + ], + 'filter-id->': [ + BooleanType, + [ValueType], + function (ctx, ref) { + var v = ref[0]; + var a = ctx.id(); + var b = v.value; + return typeof a === typeof b && a > b; + } + ], + 'filter-<=': [ + BooleanType, + [ + StringType, + ValueType + ], + function (ctx, ref) { + var k = ref[0]; + var v = ref[1]; + var a = ctx.properties()[k.value]; + var b = v.value; + return typeof a === typeof b && a <= b; + } + ], + 'filter-id-<=': [ + BooleanType, + [ValueType], + function (ctx, ref) { + var v = ref[0]; + var a = ctx.id(); + var b = v.value; + return typeof a === typeof b && a <= b; + } + ], + 'filter->=': [ + BooleanType, + [ + StringType, + ValueType + ], + function (ctx, ref) { + var k = ref[0]; + var v = ref[1]; + var a = ctx.properties()[k.value]; + var b = v.value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-id->=': [ + BooleanType, + [ValueType], + function (ctx, ref) { + var v = ref[0]; + var a = ctx.id(); + var b = v.value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-has': [ + BooleanType, + [ValueType], + function (ctx, ref) { + var k = ref[0]; + return k.value in ctx.properties(); + } + ], + 'filter-has-id': [ + BooleanType, + [], + function (ctx) { + return ctx.id() !== null && ctx.id() !== undefined; + } + ], + 'filter-type-in': [ + BooleanType, + [array(StringType)], + function (ctx, ref) { + var v = ref[0]; + return v.value.indexOf(ctx.geometryType()) >= 0; + } + ], + 'filter-id-in': [ + BooleanType, + [array(ValueType)], + function (ctx, ref) { + var v = ref[0]; + return v.value.indexOf(ctx.id()) >= 0; + } + ], + 'filter-in-small': [ + BooleanType, + [ + StringType, + array(ValueType) + ], + function (ctx, ref) { + var k = ref[0]; + var v = ref[1]; + return v.value.indexOf(ctx.properties()[k.value]) >= 0; + } + ], + 'filter-in-large': [ + BooleanType, + [ + StringType, + array(ValueType) + ], + function (ctx, ref) { + var k = ref[0]; + var v = ref[1]; + return binarySearch(ctx.properties()[k.value], v.value, 0, v.value.length - 1); + } + ], + 'all': { + type: BooleanType, + overloads: [ + [ + [ + BooleanType, + BooleanType + ], + function (ctx, ref) { + var a = ref[0]; + var b = ref[1]; + return a.evaluate(ctx) && b.evaluate(ctx); + } + ], + [ + varargs(BooleanType), + function (ctx, args) { + for (var i = 0, list = args; i < list.length; i += 1) { + var arg = list[i]; + if (!arg.evaluate(ctx)) { + return false; + } + } + return true; + } + ] + ] + }, + 'any': { + type: BooleanType, + overloads: [ + [ + [ + BooleanType, + BooleanType + ], + function (ctx, ref) { + var a = ref[0]; + var b = ref[1]; + return a.evaluate(ctx) || b.evaluate(ctx); + } + ], + [ + varargs(BooleanType), + function (ctx, args) { + for (var i = 0, list = args; i < list.length; i += 1) { + var arg = list[i]; + if (arg.evaluate(ctx)) { + return true; + } + } + return false; + } + ] + ] + }, + '!': [ + BooleanType, + [BooleanType], + function (ctx, ref) { + var b = ref[0]; + return !b.evaluate(ctx); + } + ], + 'is-supported-script': [ + BooleanType, + [StringType], + function (ctx, ref) { + var s = ref[0]; + var isSupportedScript = ctx.globals && ctx.globals.isSupportedScript; + if (isSupportedScript) { + return isSupportedScript(s.evaluate(ctx)); + } + return true; + } + ], + 'upcase': [ + StringType, + [StringType], + function (ctx, ref) { + var s = ref[0]; + return s.evaluate(ctx).toUpperCase(); + } + ], + 'downcase': [ + StringType, + [StringType], + function (ctx, ref) { + var s = ref[0]; + return s.evaluate(ctx).toLowerCase(); + } + ], + 'concat': [ + StringType, + varargs(ValueType), + function (ctx, args) { + return args.map(function (arg) { + return toString$1(arg.evaluate(ctx)); + }).join(''); + } + ], + 'resolved-locale': [ + StringType, + [CollatorType], + function (ctx, ref) { + var collator = ref[0]; + return collator.evaluate(ctx).resolvedLocale(); + } + ] +}); + +function success(value) { + return { + result: 'success', + value: value + }; +} +function error(value) { + return { + result: 'error', + value: value + }; +} + +function supportsPropertyExpression(spec) { + return spec['property-type'] === 'data-driven' || spec['property-type'] === 'cross-faded-data-driven'; +} +function supportsZoomExpression(spec) { + return !!spec.expression && spec.expression.parameters.indexOf('zoom') > -1; +} +function supportsInterpolation(spec) { + return !!spec.expression && spec.expression.interpolated; +} + +function getType(val) { + if (val instanceof Number) { + return 'number'; + } else if (val instanceof String) { + return 'string'; + } else if (val instanceof Boolean) { + return 'boolean'; + } else if (Array.isArray(val)) { + return 'array'; + } else if (val === null) { + return 'null'; + } else { + return typeof val; + } +} + +function isFunction$1(value) { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} +function identityFunction(x) { + return x; +} +function createFunction(parameters, propertySpec) { + var isColor = propertySpec.type === 'color'; + var zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === 'object'; + var featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + var zoomDependent = zoomAndFeatureDependent || !featureDependent; + var type = parameters.type || (supportsInterpolation(propertySpec) ? 'exponential' : 'interval'); + if (isColor) { + parameters = extend({}, parameters); + if (parameters.stops) { + parameters.stops = parameters.stops.map(function (stop) { + return [ + stop[0], + Color.parse(stop[1]) + ]; + }); + } + if (parameters.default) { + parameters.default = Color.parse(parameters.default); + } else { + parameters.default = Color.parse(propertySpec.default); + } + } + if (parameters.colorSpace && parameters.colorSpace !== 'rgb' && !colorSpaces[parameters.colorSpace]) { + throw new Error('Unknown color space: ' + parameters.colorSpace); + } + var innerFun; + var hashedStops; + var categoricalKeyType; + if (type === 'exponential') { + innerFun = evaluateExponentialFunction; + } else if (type === 'interval') { + innerFun = evaluateIntervalFunction; + } else if (type === 'categorical') { + innerFun = evaluateCategoricalFunction; + hashedStops = Object.create(null); + for (var i = 0, list = parameters.stops; i < list.length; i += 1) { + var stop = list[i]; + hashedStops[stop[0]] = stop[1]; + } + categoricalKeyType = typeof parameters.stops[0][0]; + } else if (type === 'identity') { + innerFun = evaluateIdentityFunction; + } else { + throw new Error('Unknown function type "' + type + '"'); + } + if (zoomAndFeatureDependent) { + var featureFunctions = {}; + var zoomStops = []; + for (var s = 0; s < parameters.stops.length; s++) { + var stop$1 = parameters.stops[s]; + var zoom = stop$1[0].zoom; + if (featureFunctions[zoom] === undefined) { + featureFunctions[zoom] = { + zoom: zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default, + stops: [] + }; + zoomStops.push(zoom); + } + featureFunctions[zoom].stops.push([ + stop$1[0].value, + stop$1[1] + ]); + } + var featureFunctionStops = []; + for (var i$1 = 0, list$1 = zoomStops; i$1 < list$1.length; i$1 += 1) { + var z = list$1[i$1]; + featureFunctionStops.push([ + featureFunctions[z].zoom, + createFunction(featureFunctions[z], propertySpec) + ]); + } + var interpolationType = { name: 'linear' }; + return { + kind: 'composite', + interpolationType: interpolationType, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), + zoomStops: featureFunctionStops.map(function (s) { + return s[0]; + }), + evaluate: function evaluate(ref, properties) { + var zoom = ref.zoom; + return evaluateExponentialFunction({ + stops: featureFunctionStops, + base: parameters.base + }, propertySpec, zoom).evaluate(zoom, properties); + } + }; + } else if (zoomDependent) { + var interpolationType$1 = type === 'exponential' ? { + name: 'exponential', + base: parameters.base !== undefined ? parameters.base : 1 + } : null; + return { + kind: 'camera', + interpolationType: interpolationType$1, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType$1), + zoomStops: parameters.stops.map(function (s) { + return s[0]; + }), + evaluate: function (ref) { + var zoom = ref.zoom; + return innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType); + } + }; + } else { + return { + kind: 'source', + evaluate: function evaluate(_, feature) { + var value = feature && feature.properties ? feature.properties[parameters.property] : undefined; + if (value === undefined) { + return coalesce(parameters.default, propertySpec.default); + } + return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType); + } + }; + } +} +function coalesce(a, b, c) { + if (a !== undefined) { + return a; + } + if (b !== undefined) { + return b; + } + if (c !== undefined) { + return c; + } +} +function evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) { + var evaluated = typeof input === keyType ? hashedStops[input] : undefined; + return coalesce(evaluated, parameters.default, propertySpec.default); +} +function evaluateIntervalFunction(parameters, propertySpec, input) { + if (getType(input) !== 'number') { + return coalesce(parameters.default, propertySpec.default); + } + var n = parameters.stops.length; + if (n === 1) { + return parameters.stops[0][1]; + } + if (input <= parameters.stops[0][0]) { + return parameters.stops[0][1]; + } + if (input >= parameters.stops[n - 1][0]) { + return parameters.stops[n - 1][1]; + } + var index = findStopLessThanOrEqualTo(parameters.stops.map(function (stop) { + return stop[0]; + }), input); + return parameters.stops[index][1]; +} +function evaluateExponentialFunction(parameters, propertySpec, input) { + var base = parameters.base !== undefined ? parameters.base : 1; + if (getType(input) !== 'number') { + return coalesce(parameters.default, propertySpec.default); + } + var n = parameters.stops.length; + if (n === 1) { + return parameters.stops[0][1]; + } + if (input <= parameters.stops[0][0]) { + return parameters.stops[0][1]; + } + if (input >= parameters.stops[n - 1][0]) { + return parameters.stops[n - 1][1]; + } + var index = findStopLessThanOrEqualTo(parameters.stops.map(function (stop) { + return stop[0]; + }), input); + var t = interpolationFactor(input, base, parameters.stops[index][0], parameters.stops[index + 1][0]); + var outputLower = parameters.stops[index][1]; + var outputUpper = parameters.stops[index + 1][1]; + var interp = interpolate[propertySpec.type] || identityFunction; + if (parameters.colorSpace && parameters.colorSpace !== 'rgb') { + var colorspace = colorSpaces[parameters.colorSpace]; + interp = function (a, b) { + return colorspace.reverse(colorspace.interpolate(colorspace.forward(a), colorspace.forward(b), t)); + }; + } + if (typeof outputLower.evaluate === 'function') { + return { + evaluate: function evaluate() { + var args = [], len = arguments.length; + while (len--) + args[len] = arguments[len]; + var evaluatedLower = outputLower.evaluate.apply(undefined, args); + var evaluatedUpper = outputUpper.evaluate.apply(undefined, args); + if (evaluatedLower === undefined || evaluatedUpper === undefined) { + return undefined; + } + return interp(evaluatedLower, evaluatedUpper, t); + } + }; + } + return interp(outputLower, outputUpper, t); +} +function evaluateIdentityFunction(parameters, propertySpec, input) { + if (propertySpec.type === 'color') { + input = Color.parse(input); + } else if (propertySpec.type === 'formatted') { + input = Formatted.fromString(input.toString()); + } else if (propertySpec.type === 'resolvedImage') { + input = ResolvedImage.fromString(input.toString()); + } else if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) { + input = undefined; + } + return coalesce(input, parameters.default, propertySpec.default); +} +function interpolationFactor(input, base, lowerValue, upperValue) { + var difference = upperValue - lowerValue; + var progress = input - lowerValue; + if (difference === 0) { + return 0; + } else if (base === 1) { + return progress / difference; + } else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } +} + +var StyleExpression = function StyleExpression(expression, propertySpec) { + this.expression = expression; + this._warningHistory = {}; + this._evaluator = new EvaluationContext(); + this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null; + this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null; +}; +StyleExpression.prototype.evaluateWithoutErrorHandling = function evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + this._evaluator.globals = globals; + this._evaluator.feature = feature; + this._evaluator.featureState = featureState; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection; + return this.expression.evaluate(this._evaluator); +}; +StyleExpression.prototype.evaluate = function evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + this._evaluator.globals = globals; + this._evaluator.feature = feature || null; + this._evaluator.featureState = featureState || null; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection || null; + try { + var val = this.expression.evaluate(this._evaluator); + if (val === null || val === undefined || typeof val === 'number' && val !== val) { + return this._defaultValue; + } + if (this._enumValues && !(val in this._enumValues)) { + throw new RuntimeError('Expected value to be one of ' + Object.keys(this._enumValues).map(function (v) { + return JSON.stringify(v); + }).join(', ') + ', but found ' + JSON.stringify(val) + ' instead.'); + } + return val; + } catch (e) { + if (!this._warningHistory[e.message]) { + this._warningHistory[e.message] = true; + if (typeof console !== 'undefined') { + console.warn(e.message); + } + } + return this._defaultValue; + } +}; +function isExpression(expression) { + return Array.isArray(expression) && expression.length > 0 && typeof expression[0] === 'string' && expression[0] in expressions; +} +function createExpression(expression, propertySpec) { + var parser = new ParsingContext(expressions, [], propertySpec ? getExpectedType(propertySpec) : undefined); + var parsed = parser.parse(expression, undefined, undefined, undefined, propertySpec && propertySpec.type === 'string' ? { typeAnnotation: 'coerce' } : undefined); + if (!parsed) { + return error(parser.errors); + } + return success(new StyleExpression(parsed, propertySpec)); +} +var ZoomConstantExpression = function ZoomConstantExpression(kind, expression) { + this.kind = kind; + this._styleExpression = expression; + this.isStateDependent = kind !== 'constant' && !isStateConstant(expression.expression); +}; +ZoomConstantExpression.prototype.evaluateWithoutErrorHandling = function evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); +}; +ZoomConstantExpression.prototype.evaluate = function evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); +}; +var ZoomDependentExpression = function ZoomDependentExpression(kind, expression, zoomStops, interpolationType) { + this.kind = kind; + this.zoomStops = zoomStops; + this._styleExpression = expression; + this.isStateDependent = kind !== 'camera' && !isStateConstant(expression.expression); + this.interpolationType = interpolationType; +}; +ZoomDependentExpression.prototype.evaluateWithoutErrorHandling = function evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); +}; +ZoomDependentExpression.prototype.evaluate = function evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); +}; +ZoomDependentExpression.prototype.interpolationFactor = function interpolationFactor(input, lower, upper) { + if (this.interpolationType) { + return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper); + } else { + return 0; + } +}; +function createPropertyExpression(expression, propertySpec) { + expression = createExpression(expression, propertySpec); + if (expression.result === 'error') { + return expression; + } + var parsed = expression.value.expression; + var isFeatureConstant$1 = isFeatureConstant(parsed); + if (!isFeatureConstant$1 && !supportsPropertyExpression(propertySpec)) { + return error([new ParsingError('', 'data expressions not supported')]); + } + var isZoomConstant = isGlobalPropertyConstant(parsed, ['zoom']); + if (!isZoomConstant && !supportsZoomExpression(propertySpec)) { + return error([new ParsingError('', 'zoom expressions not supported')]); + } + var zoomCurve = findZoomCurve(parsed); + if (!zoomCurve && !isZoomConstant) { + return error([new ParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]); + } else if (zoomCurve instanceof ParsingError) { + return error([zoomCurve]); + } else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) { + return error([new ParsingError('', '"interpolate" expressions cannot be used with this property')]); + } + if (!zoomCurve) { + return success(isFeatureConstant$1 ? new ZoomConstantExpression('constant', expression.value) : new ZoomConstantExpression('source', expression.value)); + } + var interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined; + return success(isFeatureConstant$1 ? new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType) : new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType)); +} +var StylePropertyFunction = function StylePropertyFunction(parameters, specification) { + this._parameters = parameters; + this._specification = specification; + extend(this, createFunction(this._parameters, this._specification)); +}; +StylePropertyFunction.deserialize = function deserialize(serialized) { + return new StylePropertyFunction(serialized._parameters, serialized._specification); +}; +StylePropertyFunction.serialize = function serialize(input) { + return { + _parameters: input._parameters, + _specification: input._specification + }; +}; +function normalizePropertyExpression(value, specification) { + if (isFunction$1(value)) { + return new StylePropertyFunction(value, specification); + } else if (isExpression(value)) { + var expression = createPropertyExpression(value, specification); + if (expression.result === 'error') { + throw new Error(expression.value.map(function (err) { + return err.key + ': ' + err.message; + }).join(', ')); + } + return expression.value; + } else { + var constant = value; + if (typeof value === 'string' && specification.type === 'color') { + constant = Color.parse(value); + } + return { + kind: 'constant', + evaluate: function () { + return constant; + } + }; + } +} +function findZoomCurve(expression) { + var result = null; + if (expression instanceof Let) { + result = findZoomCurve(expression.result); + } else if (expression instanceof Coalesce) { + for (var i = 0, list = expression.args; i < list.length; i += 1) { + var arg = list[i]; + result = findZoomCurve(arg); + if (result) { + break; + } + } + } else if ((expression instanceof Step || expression instanceof Interpolate) && expression.input instanceof CompoundExpression && expression.input.name === 'zoom') { + result = expression; + } + if (result instanceof ParsingError) { + return result; + } + expression.eachChild(function (child) { + var childResult = findZoomCurve(child); + if (childResult instanceof ParsingError) { + result = childResult; + } else if (!result && childResult) { + result = new ParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'); + } else if (result && childResult && result !== childResult) { + result = new ParsingError('', 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'); + } + }); + return result; +} +function getExpectedType(spec) { + var types = { + color: ColorType, + string: StringType, + number: NumberType, + enum: StringType, + boolean: BooleanType, + formatted: FormattedType, + resolvedImage: ResolvedImageType + }; + if (spec.type === 'array') { + return array(types[spec.value] || ValueType, spec.length); + } + return types[spec.type]; +} +function getDefaultValue(spec) { + if (spec.type === 'color' && isFunction$1(spec.default)) { + return new Color(0, 0, 0, 0); + } else if (spec.type === 'color') { + return Color.parse(spec.default) || null; + } else if (spec.default === undefined) { + return null; + } else { + return spec.default; + } +} + +function convertLiteral(value) { + return typeof value === 'object' ? [ + 'literal', + value + ] : value; +} +function convertFunction(parameters, propertySpec) { + var stops = parameters.stops; + if (!stops) { + return convertIdentityFunction(parameters, propertySpec); + } + var zoomAndFeatureDependent = stops && typeof stops[0][0] === 'object'; + var featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + var zoomDependent = zoomAndFeatureDependent || !featureDependent; + stops = stops.map(function (stop) { + if (!featureDependent && propertySpec.tokens && typeof stop[1] === 'string') { + return [ + stop[0], + convertTokenString(stop[1]) + ]; + } + return [ + stop[0], + convertLiteral(stop[1]) + ]; + }); + if (zoomAndFeatureDependent) { + return convertZoomAndPropertyFunction(parameters, propertySpec, stops); + } else if (zoomDependent) { + return convertZoomFunction(parameters, propertySpec, stops); + } else { + return convertPropertyFunction(parameters, propertySpec, stops); + } +} +function convertIdentityFunction(parameters, propertySpec) { + var get = [ + 'get', + parameters.property + ]; + if (parameters.default === undefined) { + return propertySpec.type === 'string' ? [ + 'string', + get + ] : get; + } else if (propertySpec.type === 'enum') { + return [ + 'match', + get, + Object.keys(propertySpec.values), + get, + parameters.default + ]; + } else { + var expression = [ + propertySpec.type === 'color' ? 'to-color' : propertySpec.type, + get, + convertLiteral(parameters.default) + ]; + if (propertySpec.type === 'array') { + expression.splice(1, 0, propertySpec.value, propertySpec.length || null); + } + return expression; + } +} +function getInterpolateOperator(parameters) { + switch (parameters.colorSpace) { + case 'hcl': + return 'interpolate-hcl'; + case 'lab': + return 'interpolate-lab'; + default: + return 'interpolate'; + } +} +function convertZoomAndPropertyFunction(parameters, propertySpec, stops) { + var featureFunctionParameters = {}; + var featureFunctionStops = {}; + var zoomStops = []; + for (var s = 0; s < stops.length; s++) { + var stop = stops[s]; + var zoom = stop[0].zoom; + if (featureFunctionParameters[zoom] === undefined) { + featureFunctionParameters[zoom] = { + zoom: zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default + }; + featureFunctionStops[zoom] = []; + zoomStops.push(zoom); + } + featureFunctionStops[zoom].push([ + stop[0].value, + stop[1] + ]); + } + var functionType = getFunctionType({}, propertySpec); + if (functionType === 'exponential') { + var expression = [ + getInterpolateOperator(parameters), + ['linear'], + ['zoom'] + ]; + for (var i = 0, list = zoomStops; i < list.length; i += 1) { + var z = list[i]; + var output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]); + appendStopPair(expression, z, output, false); + } + return expression; + } else { + var expression$1 = [ + 'step', + ['zoom'] + ]; + for (var i$1 = 0, list$1 = zoomStops; i$1 < list$1.length; i$1 += 1) { + var z$1 = list$1[i$1]; + var output$1 = convertPropertyFunction(featureFunctionParameters[z$1], propertySpec, featureFunctionStops[z$1]); + appendStopPair(expression$1, z$1, output$1, true); + } + fixupDegenerateStepCurve(expression$1); + return expression$1; + } +} +function coalesce$1(a, b) { + if (a !== undefined) { + return a; + } + if (b !== undefined) { + return b; + } +} +function getFallback(parameters, propertySpec) { + var defaultValue = convertLiteral(coalesce$1(parameters.default, propertySpec.default)); + if (defaultValue === undefined && propertySpec.type === 'resolvedImage') { + return ''; + } + return defaultValue; +} +function convertPropertyFunction(parameters, propertySpec, stops) { + var type = getFunctionType(parameters, propertySpec); + var get = [ + 'get', + parameters.property + ]; + if (type === 'categorical' && typeof stops[0][0] === 'boolean') { + var expression = ['case']; + for (var i = 0, list = stops; i < list.length; i += 1) { + var stop = list[i]; + expression.push([ + '==', + get, + stop[0] + ], stop[1]); + } + expression.push(getFallback(parameters, propertySpec)); + return expression; + } else if (type === 'categorical') { + var expression$1 = [ + 'match', + get + ]; + for (var i$1 = 0, list$1 = stops; i$1 < list$1.length; i$1 += 1) { + var stop$1 = list$1[i$1]; + appendStopPair(expression$1, stop$1[0], stop$1[1], false); + } + expression$1.push(getFallback(parameters, propertySpec)); + return expression$1; + } else if (type === 'interval') { + var expression$2 = [ + 'step', + [ + 'number', + get + ] + ]; + for (var i$2 = 0, list$2 = stops; i$2 < list$2.length; i$2 += 1) { + var stop$2 = list$2[i$2]; + appendStopPair(expression$2, stop$2[0], stop$2[1], true); + } + fixupDegenerateStepCurve(expression$2); + return parameters.default === undefined ? expression$2 : [ + 'case', + [ + '==', + [ + 'typeof', + get + ], + 'number' + ], + expression$2, + convertLiteral(parameters.default) + ]; + } else if (type === 'exponential') { + var base = parameters.base !== undefined ? parameters.base : 1; + var expression$3 = [ + getInterpolateOperator(parameters), + base === 1 ? ['linear'] : [ + 'exponential', + base + ], + [ + 'number', + get + ] + ]; + for (var i$3 = 0, list$3 = stops; i$3 < list$3.length; i$3 += 1) { + var stop$3 = list$3[i$3]; + appendStopPair(expression$3, stop$3[0], stop$3[1], false); + } + return parameters.default === undefined ? expression$3 : [ + 'case', + [ + '==', + [ + 'typeof', + get + ], + 'number' + ], + expression$3, + convertLiteral(parameters.default) + ]; + } else { + throw new Error('Unknown property function type ' + type); + } +} +function convertZoomFunction(parameters, propertySpec, stops, input) { + if (input === void 0) + input = ['zoom']; + var type = getFunctionType(parameters, propertySpec); + var expression; + var isStep = false; + if (type === 'interval') { + expression = [ + 'step', + input + ]; + isStep = true; + } else if (type === 'exponential') { + var base = parameters.base !== undefined ? parameters.base : 1; + expression = [ + getInterpolateOperator(parameters), + base === 1 ? ['linear'] : [ + 'exponential', + base + ], + input + ]; + } else { + throw new Error('Unknown zoom function type "' + type + '"'); + } + for (var i = 0, list = stops; i < list.length; i += 1) { + var stop = list[i]; + appendStopPair(expression, stop[0], stop[1], isStep); + } + fixupDegenerateStepCurve(expression); + return expression; +} +function fixupDegenerateStepCurve(expression) { + if (expression[0] === 'step' && expression.length === 3) { + expression.push(0); + expression.push(expression[3]); + } +} +function appendStopPair(curve, input, output, isStep) { + if (curve.length > 3 && input === curve[curve.length - 2]) { + return; + } + if (!(isStep && curve.length === 2)) { + curve.push(input); + } + curve.push(output); +} +function getFunctionType(parameters, propertySpec) { + if (parameters.type) { + return parameters.type; + } else { + return propertySpec.expression.interpolated ? 'exponential' : 'interval'; + } +} +function convertTokenString(s) { + var result = ['concat']; + var re = /{([^{}]+)}/g; + var pos = 0; + for (var match = re.exec(s); match !== null; match = re.exec(s)) { + var literal = s.slice(pos, re.lastIndex - match[0].length); + pos = re.lastIndex; + if (literal.length > 0) { + result.push(literal); + } + result.push([ + 'get', + match[1] + ]); + } + if (result.length === 1) { + return s; + } + if (pos < s.length) { + result.push(s.slice(pos)); + } else if (result.length === 2) { + return [ + 'to-string', + result[1] + ]; + } + return result; +} + +function isExpressionFilter(filter) { + if (filter === true || filter === false) { + return true; + } + if (!Array.isArray(filter) || filter.length === 0) { + return false; + } + switch (filter[0]) { + case 'has': + return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type'; + case 'in': + return filter.length >= 3 && (typeof filter[1] !== 'string' || Array.isArray(filter[2])); + case '!in': + case '!has': + case 'none': + return false; + case '==': + case '!=': + case '>': + case '>=': + case '<': + case '<=': + return filter.length !== 3 || (Array.isArray(filter[1]) || Array.isArray(filter[2])); + case 'any': + case 'all': + for (var i = 0, list = filter.slice(1); i < list.length; i += 1) { + var f = list[i]; + if (!isExpressionFilter(f) && typeof f !== 'boolean') { + return false; + } + } + return true; + default: + return true; + } +} +var filterSpec = { + 'type': 'boolean', + 'default': false, + 'transition': false, + 'property-type': 'data-driven', + 'expression': { + 'interpolated': false, + 'parameters': [ + 'zoom', + 'feature' + ] + } +}; +function createFilter(filter) { + if (filter === null || filter === undefined) { + return { + filter: function () { + return true; + }, + needGeometry: false + }; + } + if (!isExpressionFilter(filter)) { + filter = convertFilter(filter); + } + var compiled = createExpression(filter, filterSpec); + if (compiled.result === 'error') { + throw new Error(compiled.value.map(function (err) { + return err.key + ': ' + err.message; + }).join(', ')); + } else { + var needGeometry = geometryNeeded(filter); + return { + filter: function (globalProperties, feature, canonical) { + return compiled.value.evaluate(globalProperties, feature, {}, canonical); + }, + needGeometry: needGeometry + }; + } +} +function compare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} +function geometryNeeded(filter) { + if (!Array.isArray(filter)) { + return false; + } + if (filter[0] === 'within') { + return true; + } + for (var index = 1; index < filter.length; index++) { + if (geometryNeeded(filter[index])) { + return true; + } + } + return false; +} +function convertFilter(filter) { + if (!filter) { + return true; + } + var op = filter[0]; + if (filter.length <= 1) { + return op !== 'any'; + } + var converted = op === '==' ? convertComparisonOp(filter[1], filter[2], '==') : op === '!=' ? convertNegation(convertComparisonOp(filter[1], filter[2], '==')) : op === '<' || op === '>' || op === '<=' || op === '>=' ? convertComparisonOp(filter[1], filter[2], op) : op === 'any' ? convertDisjunctionOp(filter.slice(1)) : op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter)) : op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter).map(convertNegation)) : op === 'in' ? convertInOp(filter[1], filter.slice(2)) : op === '!in' ? convertNegation(convertInOp(filter[1], filter.slice(2))) : op === 'has' ? convertHasOp(filter[1]) : op === '!has' ? convertNegation(convertHasOp(filter[1])) : op === 'within' ? filter : true; + return converted; +} +function convertComparisonOp(property, value, op) { + switch (property) { + case '$type': + return [ + 'filter-type-' + op, + value + ]; + case '$id': + return [ + 'filter-id-' + op, + value + ]; + default: + return [ + 'filter-' + op, + property, + value + ]; + } +} +function convertDisjunctionOp(filters) { + return ['any'].concat(filters.map(convertFilter)); +} +function convertInOp(property, values) { + if (values.length === 0) { + return false; + } + switch (property) { + case '$type': + return [ + 'filter-type-in', + [ + 'literal', + values + ] + ]; + case '$id': + return [ + 'filter-id-in', + [ + 'literal', + values + ] + ]; + default: + if (values.length > 200 && !values.some(function (v) { + return typeof v !== typeof values[0]; + })) { + return [ + 'filter-in-large', + property, + [ + 'literal', + values.sort(compare) + ] + ]; + } else { + return [ + 'filter-in-small', + property, + [ + 'literal', + values + ] + ]; + } + } +} +function convertHasOp(property) { + switch (property) { + case '$type': + return true; + case '$id': + return ['filter-has-id']; + default: + return [ + 'filter-has', + property + ]; + } +} +function convertNegation(filter) { + return [ + '!', + filter + ]; +} + +function convertFilter$1(filter) { + return _convertFilter(filter, {}); +} +function _convertFilter(filter, expectedTypes) { + var ref$1; + if (isExpressionFilter(filter)) { + return filter; + } + if (!filter) { + return true; + } + var op = filter[0]; + if (filter.length <= 1) { + return op !== 'any'; + } + var converted; + if (op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=') { + var ref = filter; + var property = ref[1]; + var value = ref[2]; + converted = convertComparisonOp$1(property, value, op, expectedTypes); + } else if (op === 'any') { + var children = filter.slice(1).map(function (f) { + var types = {}; + var child = _convertFilter(f, types); + var typechecks = runtimeTypeChecks(types); + return typechecks === true ? child : [ + 'case', + typechecks, + child, + false + ]; + }); + return ['any'].concat(children); + } else if (op === 'all') { + var children$1 = filter.slice(1).map(function (f) { + return _convertFilter(f, expectedTypes); + }); + return children$1.length > 1 ? ['all'].concat(children$1) : (ref$1 = []).concat.apply(ref$1, children$1); + } else if (op === 'none') { + return [ + '!', + _convertFilter(['any'].concat(filter.slice(1)), {}) + ]; + } else if (op === 'in') { + converted = convertInOp$1(filter[1], filter.slice(2)); + } else if (op === '!in') { + converted = convertInOp$1(filter[1], filter.slice(2), true); + } else if (op === 'has') { + converted = convertHasOp$1(filter[1]); + } else if (op === '!has') { + converted = [ + '!', + convertHasOp$1(filter[1]) + ]; + } else { + converted = true; + } + return converted; +} +function runtimeTypeChecks(expectedTypes) { + var conditions = []; + for (var property in expectedTypes) { + var get = property === '$id' ? ['id'] : [ + 'get', + property + ]; + conditions.push([ + '==', + [ + 'typeof', + get + ], + expectedTypes[property] + ]); + } + if (conditions.length === 0) { + return true; + } + if (conditions.length === 1) { + return conditions[0]; + } + return ['all'].concat(conditions); +} +function convertComparisonOp$1(property, value, op, expectedTypes) { + var get; + if (property === '$type') { + return [ + op, + ['geometry-type'], + value + ]; + } else if (property === '$id') { + get = ['id']; + } else { + get = [ + 'get', + property + ]; + } + if (expectedTypes && value !== null) { + var type = typeof value; + expectedTypes[property] = type; + } + if (op === '==' && property !== '$id' && value === null) { + return [ + 'all', + [ + 'has', + property + ], + [ + '==', + get, + null + ] + ]; + } else if (op === '!=' && property !== '$id' && value === null) { + return [ + 'any', + [ + '!', + [ + 'has', + property + ] + ], + [ + '!=', + get, + null + ] + ]; + } + return [ + op, + get, + value + ]; +} +function convertInOp$1(property, values, negate) { + if (negate === void 0) + negate = false; + if (values.length === 0) { + return negate; + } + var get; + if (property === '$type') { + get = ['geometry-type']; + } else if (property === '$id') { + get = ['id']; + } else { + get = [ + 'get', + property + ]; + } + var uniformTypes = true; + var type = typeof values[0]; + for (var i = 0, list = values; i < list.length; i += 1) { + var value = list[i]; + if (typeof value !== type) { + uniformTypes = false; + break; + } + } + if (uniformTypes && (type === 'string' || type === 'number')) { + var uniqueValues = values.sort().filter(function (v, i) { + return i === 0 || values[i - 1] !== v; + }); + return [ + 'match', + get, + uniqueValues, + !negate, + negate + ]; + } + return [negate ? 'all' : 'any'].concat(values.map(function (v) { + return [ + negate ? '!=' : '==', + get, + v + ]; + })); +} +function convertHasOp$1(property) { + if (property === '$type') { + return true; + } else if (property === '$id') { + return [ + '!=', + ['id'], + null + ]; + } else { + return [ + 'has', + property + ]; + } +} + +function migrateToExpressions (style) { + var converted = []; + eachLayer(style, function (layer) { + if (layer.filter) { + layer.filter = convertFilter$1(layer.filter); + } + }); + eachProperty(style, { + paint: true, + layout: true + }, function (ref) { + var path = ref.path; + var value = ref.value; + var reference = ref.reference; + var set = ref.set; + if (isExpression(value)) { + return; + } + if (typeof value === 'object' && !Array.isArray(value)) { + set(convertFunction(value, reference)); + converted.push(path.join('.')); + } else if (reference.tokens && typeof value === 'string') { + set(convertTokenString(value)); + } + }); + return style; +} + +function migrate (style) { + var migrated = false; + if (style.version === 7) { + style = migrateToV8(style); + migrated = true; + } + if (style.version === 8) { + migrated = migrateToExpressions(style); + migrated = true; + } + if (!migrated) { + throw new Error('cannot migrate from', style.version); + } + return style; +} + +function composite (style) { + var styleIDs = []; + var sourceIDs = []; + var compositedSourceLayers = []; + for (var id in style.sources) { + var source = style.sources[id]; + if (source.type !== 'vector') { + continue; + } + var match = /^mapbox:\/\/(.*)/.exec(source.url); + if (!match) { + continue; + } + styleIDs.push(id); + sourceIDs.push(match[1]); + } + if (styleIDs.length < 2) { + return style; + } + styleIDs.forEach(function (id) { + delete style.sources[id]; + }); + var compositeID = sourceIDs.join(','); + style.sources[compositeID] = { + 'type': 'vector', + 'url': 'mapbox://' + compositeID + }; + style.layers.forEach(function (layer) { + if (styleIDs.indexOf(layer.source) >= 0) { + layer.source = compositeID; + if ('source-layer' in layer) { + if (compositedSourceLayers.indexOf(layer['source-layer']) >= 0) { + throw new Error('Conflicting source layer names'); + } else { + compositedSourceLayers.push(layer['source-layer']); + } + } + } + }); + return style; +} + +var refProperties = [ + 'type', + 'source', + 'source-layer', + 'minzoom', + 'maxzoom', + 'filter', + 'layout' +]; + +function deref(layer, parent) { + var result = {}; + for (var k in layer) { + if (k !== 'ref') { + result[k] = layer[k]; + } + } + refProperties.forEach(function (k) { + if (k in parent) { + result[k] = parent[k]; + } + }); + return result; +} +function derefLayers(layers) { + layers = layers.slice(); + var map = Object.create(null); + for (var i = 0; i < layers.length; i++) { + map[layers[i].id] = layers[i]; + } + for (var i$1 = 0; i$1 < layers.length; i$1++) { + if ('ref' in layers[i$1]) { + layers[i$1] = deref(layers[i$1], map[layers[i$1].ref]); + } + } + return layers; +} + +function deepEqual(a, b) { + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) { + return false; + } + for (var i = 0; i < a.length; i++) { + if (!deepEqual(a[i], b[i])) { + return false; + } + } + return true; + } + if (typeof a === 'object' && a !== null && b !== null) { + if (!(typeof b === 'object')) { + return false; + } + var keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) { + return false; + } + for (var key in a) { + if (!deepEqual(a[key], b[key])) { + return false; + } + } + return true; + } + return a === b; +} + +var operations = { + setStyle: 'setStyle', + addLayer: 'addLayer', + removeLayer: 'removeLayer', + setPaintProperty: 'setPaintProperty', + setLayoutProperty: 'setLayoutProperty', + setFilter: 'setFilter', + addSource: 'addSource', + removeSource: 'removeSource', + setGeoJSONSourceData: 'setGeoJSONSourceData', + setLayerZoomRange: 'setLayerZoomRange', + setLayerProperty: 'setLayerProperty', + setCenter: 'setCenter', + setZoom: 'setZoom', + setBearing: 'setBearing', + setPitch: 'setPitch', + setSprite: 'setSprite', + setGlyphs: 'setGlyphs', + setTransition: 'setTransition', + setLight: 'setLight' +}; +function addSource(sourceId, after, commands) { + commands.push({ + command: operations.addSource, + args: [ + sourceId, + after[sourceId] + ] + }); +} +function removeSource(sourceId, commands, sourcesRemoved) { + commands.push({ + command: operations.removeSource, + args: [sourceId] + }); + sourcesRemoved[sourceId] = true; +} +function updateSource(sourceId, after, commands, sourcesRemoved) { + removeSource(sourceId, commands, sourcesRemoved); + addSource(sourceId, after, commands); +} +function canUpdateGeoJSON(before, after, sourceId) { + var prop; + for (prop in before[sourceId]) { + if (!before[sourceId].hasOwnProperty(prop)) { + continue; + } + if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + for (prop in after[sourceId]) { + if (!after[sourceId].hasOwnProperty(prop)) { + continue; + } + if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + return true; +} +function diffSources(before, after, commands, sourcesRemoved) { + before = before || {}; + after = after || {}; + var sourceId; + for (sourceId in before) { + if (!before.hasOwnProperty(sourceId)) { + continue; + } + if (!after.hasOwnProperty(sourceId)) { + removeSource(sourceId, commands, sourcesRemoved); + } + } + for (sourceId in after) { + if (!after.hasOwnProperty(sourceId)) { + continue; + } + if (!before.hasOwnProperty(sourceId)) { + addSource(sourceId, after, commands); + } else if (!deepEqual(before[sourceId], after[sourceId])) { + if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) { + commands.push({ + command: operations.setGeoJSONSourceData, + args: [ + sourceId, + after[sourceId].data + ] + }); + } else { + updateSource(sourceId, after, commands, sourcesRemoved); + } + } + } +} +function diffLayerPropertyChanges(before, after, commands, layerId, klass, command) { + before = before || {}; + after = after || {}; + var prop; + for (prop in before) { + if (!before.hasOwnProperty(prop)) { + continue; + } + if (!deepEqual(before[prop], after[prop])) { + commands.push({ + command: command, + args: [ + layerId, + prop, + after[prop], + klass + ] + }); + } + } + for (prop in after) { + if (!after.hasOwnProperty(prop) || before.hasOwnProperty(prop)) { + continue; + } + if (!deepEqual(before[prop], after[prop])) { + commands.push({ + command: command, + args: [ + layerId, + prop, + after[prop], + klass + ] + }); + } + } +} +function pluckId(layer) { + return layer.id; +} +function indexById(group, layer) { + group[layer.id] = layer; + return group; +} +function diffLayers(before, after, commands) { + before = before || []; + after = after || []; + var beforeOrder = before.map(pluckId); + var afterOrder = after.map(pluckId); + var beforeIndex = before.reduce(indexById, {}); + var afterIndex = after.reduce(indexById, {}); + var tracker = beforeOrder.slice(); + var clean = Object.create(null); + var i, d, layerId, beforeLayer, afterLayer, insertBeforeLayerId, prop; + for (i = 0, d = 0; i < beforeOrder.length; i++) { + layerId = beforeOrder[i]; + if (!afterIndex.hasOwnProperty(layerId)) { + commands.push({ + command: operations.removeLayer, + args: [layerId] + }); + tracker.splice(tracker.indexOf(layerId, d), 1); + } else { + d++; + } + } + for (i = 0, d = 0; i < afterOrder.length; i++) { + layerId = afterOrder[afterOrder.length - 1 - i]; + if (tracker[tracker.length - 1 - i] === layerId) { + continue; + } + if (beforeIndex.hasOwnProperty(layerId)) { + commands.push({ + command: operations.removeLayer, + args: [layerId] + }); + tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1); + } else { + d++; + } + insertBeforeLayerId = tracker[tracker.length - i]; + commands.push({ + command: operations.addLayer, + args: [ + afterIndex[layerId], + insertBeforeLayerId + ] + }); + tracker.splice(tracker.length - i, 0, layerId); + clean[layerId] = true; + } + for (i = 0; i < afterOrder.length; i++) { + layerId = afterOrder[i]; + beforeLayer = beforeIndex[layerId]; + afterLayer = afterIndex[layerId]; + if (clean[layerId] || deepEqual(beforeLayer, afterLayer)) { + continue; + } + if (!deepEqual(beforeLayer.source, afterLayer.source) || !deepEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !deepEqual(beforeLayer.type, afterLayer.type)) { + commands.push({ + command: operations.removeLayer, + args: [layerId] + }); + insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1]; + commands.push({ + command: operations.addLayer, + args: [ + afterLayer, + insertBeforeLayerId + ] + }); + continue; + } + diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, operations.setLayoutProperty); + diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, operations.setPaintProperty); + if (!deepEqual(beforeLayer.filter, afterLayer.filter)) { + commands.push({ + command: operations.setFilter, + args: [ + layerId, + afterLayer.filter + ] + }); + } + if (!deepEqual(beforeLayer.minzoom, afterLayer.minzoom) || !deepEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) { + commands.push({ + command: operations.setLayerZoomRange, + args: [ + layerId, + afterLayer.minzoom, + afterLayer.maxzoom + ] + }); + } + for (prop in beforeLayer) { + if (!beforeLayer.hasOwnProperty(prop)) { + continue; + } + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') { + continue; + } + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty); + } else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) { + commands.push({ + command: operations.setLayerProperty, + args: [ + layerId, + prop, + afterLayer[prop] + ] + }); + } + } + for (prop in afterLayer) { + if (!afterLayer.hasOwnProperty(prop) || beforeLayer.hasOwnProperty(prop)) { + continue; + } + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') { + continue; + } + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty); + } else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) { + commands.push({ + command: operations.setLayerProperty, + args: [ + layerId, + prop, + afterLayer[prop] + ] + }); + } + } + } +} +function diffStyles(before, after) { + if (!before) { + return [{ + command: operations.setStyle, + args: [after] + }]; + } + var commands = []; + try { + if (!deepEqual(before.version, after.version)) { + return [{ + command: operations.setStyle, + args: [after] + }]; + } + if (!deepEqual(before.center, after.center)) { + commands.push({ + command: operations.setCenter, + args: [after.center] + }); + } + if (!deepEqual(before.zoom, after.zoom)) { + commands.push({ + command: operations.setZoom, + args: [after.zoom] + }); + } + if (!deepEqual(before.bearing, after.bearing)) { + commands.push({ + command: operations.setBearing, + args: [after.bearing] + }); + } + if (!deepEqual(before.pitch, after.pitch)) { + commands.push({ + command: operations.setPitch, + args: [after.pitch] + }); + } + if (!deepEqual(before.sprite, after.sprite)) { + commands.push({ + command: operations.setSprite, + args: [after.sprite] + }); + } + if (!deepEqual(before.glyphs, after.glyphs)) { + commands.push({ + command: operations.setGlyphs, + args: [after.glyphs] + }); + } + if (!deepEqual(before.transition, after.transition)) { + commands.push({ + command: operations.setTransition, + args: [after.transition] + }); + } + if (!deepEqual(before.light, after.light)) { + commands.push({ + command: operations.setLight, + args: [after.light] + }); + } + var sourcesRemoved = {}; + var removeOrAddSourceCommands = []; + diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved); + var beforeLayers = []; + if (before.layers) { + before.layers.forEach(function (layer) { + if (sourcesRemoved[layer.source]) { + commands.push({ + command: operations.removeLayer, + args: [layer.id] + }); + } else { + beforeLayers.push(layer); + } + }); + } + commands = commands.concat(removeOrAddSourceCommands); + diffLayers(beforeLayers, after.layers, commands); + } catch (e) { + console.warn('Unable to compute style diff:', e); + commands = [{ + command: operations.setStyle, + args: [after] + }]; + } + return commands; +} + +var ValidationError = function ValidationError(key, value, message, identifier) { + this.message = (key ? key + ': ' : '') + message; + if (identifier) { + this.identifier = identifier; + } + if (value !== null && value !== undefined && value.__line__) { + this.line = value.__line__; + } +}; + +var ParsingError$1 = function ParsingError(error) { + this.error = error; + this.message = error.message; + var match = error.message.match(/line (\d+)/); + this.line = match ? parseInt(match[1], 10) : 0; +}; + +function validateConstants(options) { + var key = options.key; + var constants = options.value; + if (constants) { + return [new ValidationError(key, constants, 'constants have been deprecated as of v8')]; + } else { + return []; + } +} + +function unbundle(value) { + if (value instanceof Number || value instanceof String || value instanceof Boolean) { + return value.valueOf(); + } else { + return value; + } +} +function deepUnbundle(value) { + if (Array.isArray(value)) { + return value.map(deepUnbundle); + } else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) { + var unbundledValue = {}; + for (var key in value) { + unbundledValue[key] = deepUnbundle(value[key]); + } + return unbundledValue; + } + return unbundle(value); +} + +function validateObject(options) { + var key = options.key; + var object = options.value; + var elementSpecs = options.valueSpec || {}; + var elementValidators = options.objectElementValidators || {}; + var style = options.style; + var styleSpec = options.styleSpec; + var errors = []; + var type = getType(object); + if (type !== 'object') { + return [new ValidationError(key, object, 'object expected, ' + type + ' found')]; + } + for (var objectKey in object) { + var elementSpecKey = objectKey.split('.')[0]; + var elementSpec = elementSpecs[elementSpecKey] || elementSpecs['*']; + var validateElement = void 0; + if (elementValidators[elementSpecKey]) { + validateElement = elementValidators[elementSpecKey]; + } else if (elementSpecs[elementSpecKey]) { + validateElement = validate; + } else if (elementValidators['*']) { + validateElement = elementValidators['*']; + } else if (elementSpecs['*']) { + validateElement = validate; + } else { + errors.push(new ValidationError(key, object[objectKey], 'unknown property "' + objectKey + '"')); + continue; + } + errors = errors.concat(validateElement({ + key: (key ? key + '.' : key) + objectKey, + value: object[objectKey], + valueSpec: elementSpec, + style: style, + styleSpec: styleSpec, + object: object, + objectKey: objectKey + }, object)); + } + for (var elementSpecKey$1 in elementSpecs) { + if (elementValidators[elementSpecKey$1]) { + continue; + } + if (elementSpecs[elementSpecKey$1].required && elementSpecs[elementSpecKey$1]['default'] === undefined && object[elementSpecKey$1] === undefined) { + errors.push(new ValidationError(key, object, 'missing required property "' + elementSpecKey$1 + '"')); + } + } + return errors; +} + +function validateArray(options) { + var array = options.value; + var arraySpec = options.valueSpec; + var style = options.style; + var styleSpec = options.styleSpec; + var key = options.key; + var validateArrayElement = options.arrayElementValidator || validate; + if (getType(array) !== 'array') { + return [new ValidationError(key, array, 'array expected, ' + getType(array) + ' found')]; + } + if (arraySpec.length && array.length !== arraySpec.length) { + return [new ValidationError(key, array, 'array length ' + arraySpec.length + ' expected, length ' + array.length + ' found')]; + } + if (arraySpec['min-length'] && array.length < arraySpec['min-length']) { + return [new ValidationError(key, array, 'array length at least ' + arraySpec['min-length'] + ' expected, length ' + array.length + ' found')]; + } + var arrayElementSpec = { + 'type': arraySpec.value, + 'values': arraySpec.values + }; + if (styleSpec.$version < 7) { + arrayElementSpec.function = arraySpec.function; + } + if (getType(arraySpec.value) === 'object') { + arrayElementSpec = arraySpec.value; + } + var errors = []; + for (var i = 0; i < array.length; i++) { + errors = errors.concat(validateArrayElement({ + array: array, + arrayIndex: i, + value: array[i], + valueSpec: arrayElementSpec, + style: style, + styleSpec: styleSpec, + key: key + '[' + i + ']' + })); + } + return errors; +} + +function validateNumber(options) { + var key = options.key; + var value = options.value; + var valueSpec = options.valueSpec; + var type = getType(value); + if (type === 'number' && value !== value) { + type = 'NaN'; + } + if (type !== 'number') { + return [new ValidationError(key, value, 'number expected, ' + type + ' found')]; + } + if ('minimum' in valueSpec && value < valueSpec.minimum) { + return [new ValidationError(key, value, value + ' is less than the minimum value ' + valueSpec.minimum)]; + } + if ('maximum' in valueSpec && value > valueSpec.maximum) { + return [new ValidationError(key, value, value + ' is greater than the maximum value ' + valueSpec.maximum)]; + } + return []; +} + +function validateFunction(options) { + var functionValueSpec = options.valueSpec; + var functionType = unbundle(options.value.type); + var stopKeyType; + var stopDomainValues = {}; + var previousStopDomainValue; + var previousStopDomainZoom; + var isZoomFunction = functionType !== 'categorical' && options.value.property === undefined; + var isPropertyFunction = !isZoomFunction; + var isZoomAndPropertyFunction = getType(options.value.stops) === 'array' && getType(options.value.stops[0]) === 'array' && getType(options.value.stops[0][0]) === 'object'; + var errors = validateObject({ + key: options.key, + value: options.value, + valueSpec: options.styleSpec.function, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + stops: validateFunctionStops, + default: validateFunctionDefault + } + }); + if (functionType === 'identity' && isZoomFunction) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "property"')); + } + if (functionType !== 'identity' && !options.value.stops) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "stops"')); + } + if (functionType === 'exponential' && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'exponential functions not supported')); + } + if (options.styleSpec.$version >= 8) { + if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'property functions not supported')); + } else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'zoom functions not supported')); + } + } + if ((functionType === 'categorical' || isZoomAndPropertyFunction) && options.value.property === undefined) { + errors.push(new ValidationError(options.key, options.value, '"property" property is required')); + } + return errors; + function validateFunctionStops(options) { + if (functionType === 'identity') { + return [new ValidationError(options.key, options.value, 'identity function may not have a "stops" property')]; + } + var errors = []; + var value = options.value; + errors = errors.concat(validateArray({ + key: options.key, + value: value, + valueSpec: options.valueSpec, + style: options.style, + styleSpec: options.styleSpec, + arrayElementValidator: validateFunctionStop + })); + if (getType(value) === 'array' && value.length === 0) { + errors.push(new ValidationError(options.key, value, 'array must have at least one stop')); + } + return errors; + } + function validateFunctionStop(options) { + var errors = []; + var value = options.value; + var key = options.key; + if (getType(value) !== 'array') { + return [new ValidationError(key, value, 'array expected, ' + getType(value) + ' found')]; + } + if (value.length !== 2) { + return [new ValidationError(key, value, 'array length 2 expected, length ' + value.length + ' found')]; + } + if (isZoomAndPropertyFunction) { + if (getType(value[0]) !== 'object') { + return [new ValidationError(key, value, 'object expected, ' + getType(value[0]) + ' found')]; + } + if (value[0].zoom === undefined) { + return [new ValidationError(key, value, 'object stop key must have zoom')]; + } + if (value[0].value === undefined) { + return [new ValidationError(key, value, 'object stop key must have value')]; + } + if (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) { + return [new ValidationError(key, value[0].zoom, 'stop zoom values must appear in ascending order')]; + } + if (unbundle(value[0].zoom) !== previousStopDomainZoom) { + previousStopDomainZoom = unbundle(value[0].zoom); + previousStopDomainValue = undefined; + stopDomainValues = {}; + } + errors = errors.concat(validateObject({ + key: key + '[0]', + value: value[0], + valueSpec: { zoom: {} }, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + zoom: validateNumber, + value: validateStopDomainValue + } + })); + } else { + errors = errors.concat(validateStopDomainValue({ + key: key + '[0]', + value: value[0], + valueSpec: {}, + style: options.style, + styleSpec: options.styleSpec + }, value)); + } + if (isExpression(deepUnbundle(value[1]))) { + return errors.concat([new ValidationError(key + '[1]', value[1], 'expressions are not allowed in function stops.')]); + } + return errors.concat(validate({ + key: key + '[1]', + value: value[1], + valueSpec: functionValueSpec, + style: options.style, + styleSpec: options.styleSpec + })); + } + function validateStopDomainValue(options, stop) { + var type = getType(options.value); + var value = unbundle(options.value); + var reportValue = options.value !== null ? options.value : stop; + if (!stopKeyType) { + stopKeyType = type; + } else if (type !== stopKeyType) { + return [new ValidationError(options.key, reportValue, type + ' stop domain type must match previous stop domain type ' + stopKeyType)]; + } + if (type !== 'number' && type !== 'string' && type !== 'boolean') { + return [new ValidationError(options.key, reportValue, 'stop domain value must be a number, string, or boolean')]; + } + if (type !== 'number' && functionType !== 'categorical') { + var message = 'number expected, ' + type + ' found'; + if (supportsPropertyExpression(functionValueSpec) && functionType === undefined) { + message += '\nIf you intended to use a categorical function, specify `"type": "categorical"`.'; + } + return [new ValidationError(options.key, reportValue, message)]; + } + if (functionType === 'categorical' && type === 'number' && (!isFinite(value) || Math.floor(value) !== value)) { + return [new ValidationError(options.key, reportValue, 'integer expected, found ' + value)]; + } + if (functionType !== 'categorical' && type === 'number' && previousStopDomainValue !== undefined && value < previousStopDomainValue) { + return [new ValidationError(options.key, reportValue, 'stop domain values must appear in ascending order')]; + } else { + previousStopDomainValue = value; + } + if (functionType === 'categorical' && value in stopDomainValues) { + return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')]; + } else { + stopDomainValues[value] = true; + } + return []; + } + function validateFunctionDefault(options) { + return validate({ + key: options.key, + value: options.value, + valueSpec: functionValueSpec, + style: options.style, + styleSpec: options.styleSpec + }); + } +} + +function validateExpression(options) { + var expression = (options.expressionContext === 'property' ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec); + if (expression.result === 'error') { + return expression.value.map(function (error) { + return new ValidationError('' + options.key + error.key, options.value, error.message); + }); + } + var expressionObj = expression.value.expression || expression.value._styleExpression.expression; + if (options.expressionContext === 'property' && options.propertyKey === 'text-font' && !expressionObj.outputDefined()) { + return [new ValidationError(options.key, options.value, 'Invalid data expression for "' + options.propertyKey + '". Output values must be contained as literals within the expression.')]; + } + if (options.expressionContext === 'property' && options.propertyType === 'layout' && !isStateConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with layout properties.')]; + } + if (options.expressionContext === 'filter' && !isStateConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with filters.')]; + } + if (options.expressionContext && options.expressionContext.indexOf('cluster') === 0) { + if (!isGlobalPropertyConstant(expressionObj, [ + 'zoom', + 'feature-state' + ])) { + return [new ValidationError(options.key, options.value, '"zoom" and "feature-state" expressions are not supported with cluster properties.')]; + } + if (options.expressionContext === 'cluster-initial' && !isFeatureConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, 'Feature data expressions are not supported with initial expression part of cluster properties.')]; + } + } + return []; +} + +function validateBoolean(options) { + var value = options.value; + var key = options.key; + var type = getType(value); + if (type !== 'boolean') { + return [new ValidationError(key, value, 'boolean expected, ' + type + ' found')]; + } + return []; +} + +function validateColor(options) { + var key = options.key; + var value = options.value; + var type = getType(value); + if (type !== 'string') { + return [new ValidationError(key, value, 'color expected, ' + type + ' found')]; + } + if (csscolorparser_1(value) === null) { + return [new ValidationError(key, value, 'color expected, "' + value + '" found')]; + } + return []; +} + +function validateEnum(options) { + var key = options.key; + var value = options.value; + var valueSpec = options.valueSpec; + var errors = []; + if (Array.isArray(valueSpec.values)) { + if (valueSpec.values.indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, 'expected one of [' + valueSpec.values.join(', ') + '], ' + JSON.stringify(value) + ' found')); + } + } else { + if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, 'expected one of [' + Object.keys(valueSpec.values).join(', ') + '], ' + JSON.stringify(value) + ' found')); + } + } + return errors; +} + +function validateFilter(options) { + if (isExpressionFilter(deepUnbundle(options.value))) { + return validateExpression(extend({}, options, { + expressionContext: 'filter', + valueSpec: { value: 'boolean' } + })); + } else { + return validateNonExpressionFilter(options); + } +} +function validateNonExpressionFilter(options) { + var value = options.value; + var key = options.key; + if (getType(value) !== 'array') { + return [new ValidationError(key, value, 'array expected, ' + getType(value) + ' found')]; + } + var styleSpec = options.styleSpec; + var type; + var errors = []; + if (value.length < 1) { + return [new ValidationError(key, value, 'filter array must have at least 1 element')]; + } + errors = errors.concat(validateEnum({ + key: key + '[0]', + value: value[0], + valueSpec: styleSpec.filter_operator, + style: options.style, + styleSpec: options.styleSpec + })); + switch (unbundle(value[0])) { + case '<': + case '<=': + case '>': + case '>=': + if (value.length >= 2 && unbundle(value[1]) === '$type') { + errors.push(new ValidationError(key, value, '"$type" cannot be use with operator "' + value[0] + '"')); + } + case '==': + case '!=': + if (value.length !== 3) { + errors.push(new ValidationError(key, value, 'filter array for operator "' + value[0] + '" must have 3 elements')); + } + case 'in': + case '!in': + if (value.length >= 2) { + type = getType(value[1]); + if (type !== 'string') { + errors.push(new ValidationError(key + '[1]', value[1], 'string expected, ' + type + ' found')); + } + } + for (var i = 2; i < value.length; i++) { + type = getType(value[i]); + if (unbundle(value[1]) === '$type') { + errors = errors.concat(validateEnum({ + key: key + '[' + i + ']', + value: value[i], + valueSpec: styleSpec.geometry_type, + style: options.style, + styleSpec: options.styleSpec + })); + } else if (type !== 'string' && type !== 'number' && type !== 'boolean') { + errors.push(new ValidationError(key + '[' + i + ']', value[i], 'string, number, or boolean expected, ' + type + ' found')); + } + } + break; + case 'any': + case 'all': + case 'none': + for (var i$1 = 1; i$1 < value.length; i$1++) { + errors = errors.concat(validateNonExpressionFilter({ + key: key + '[' + i$1 + ']', + value: value[i$1], + style: options.style, + styleSpec: options.styleSpec + })); + } + break; + case 'has': + case '!has': + type = getType(value[1]); + if (value.length !== 2) { + errors.push(new ValidationError(key, value, 'filter array for "' + value[0] + '" operator must have 2 elements')); + } else if (type !== 'string') { + errors.push(new ValidationError(key + '[1]', value[1], 'string expected, ' + type + ' found')); + } + break; + case 'within': + type = getType(value[1]); + if (value.length !== 2) { + errors.push(new ValidationError(key, value, 'filter array for "' + value[0] + '" operator must have 2 elements')); + } else if (type !== 'object') { + errors.push(new ValidationError(key + '[1]', value[1], 'object expected, ' + type + ' found')); + } + break; + } + return errors; +} + +function validateProperty(options, propertyType) { + var key = options.key; + var style = options.style; + var styleSpec = options.styleSpec; + var value = options.value; + var propertyKey = options.objectKey; + var layerSpec = styleSpec[propertyType + '_' + options.layerType]; + if (!layerSpec) { + return []; + } + var transitionMatch = propertyKey.match(/^(.*)-transition$/); + if (propertyType === 'paint' && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) { + return validate({ + key: key, + value: value, + valueSpec: styleSpec.transition, + style: style, + styleSpec: styleSpec + }); + } + var valueSpec = options.valueSpec || layerSpec[propertyKey]; + if (!valueSpec) { + return [new ValidationError(key, value, 'unknown property "' + propertyKey + '"')]; + } + var tokenMatch; + if (getType(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) { + return [new ValidationError(key, value, '"' + propertyKey + '" does not support interpolation syntax\n' + 'Use an identity property function instead: `{ "type": "identity", "property": ' + JSON.stringify(tokenMatch[1]) + ' }`.')]; + } + var errors = []; + if (options.layerType === 'symbol') { + if (propertyKey === 'text-field' && style && !style.glyphs) { + errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property')); + } + if (propertyKey === 'text-font' && isFunction$1(deepUnbundle(value)) && unbundle(value.type) === 'identity') { + errors.push(new ValidationError(key, value, '"text-font" does not support identity functions')); + } + } + return errors.concat(validate({ + key: options.key, + value: value, + valueSpec: valueSpec, + style: style, + styleSpec: styleSpec, + expressionContext: 'property', + propertyType: propertyType, + propertyKey: propertyKey + })); +} + +function validatePaintProperty(options) { + return validateProperty(options, 'paint'); +} + +function validateLayoutProperty(options) { + return validateProperty(options, 'layout'); +} + +function validateLayer(options) { + var errors = []; + var layer = options.value; + var key = options.key; + var style = options.style; + var styleSpec = options.styleSpec; + if (!layer.type && !layer.ref) { + errors.push(new ValidationError(key, layer, 'either "type" or "ref" is required')); + } + var type = unbundle(layer.type); + var ref = unbundle(layer.ref); + if (layer.id) { + var layerId = unbundle(layer.id); + for (var i = 0; i < options.arrayIndex; i++) { + var otherLayer = style.layers[i]; + if (unbundle(otherLayer.id) === layerId) { + errors.push(new ValidationError(key, layer.id, 'duplicate layer id "' + layer.id + '", previously used at line ' + otherLayer.id.__line__)); + } + } + } + if ('ref' in layer) { + [ + 'type', + 'source', + 'source-layer', + 'filter', + 'layout' + ].forEach(function (p) { + if (p in layer) { + errors.push(new ValidationError(key, layer[p], '"' + p + '" is prohibited for ref layers')); + } + }); + var parent; + style.layers.forEach(function (layer) { + if (unbundle(layer.id) === ref) { + parent = layer; + } + }); + if (!parent) { + errors.push(new ValidationError(key, layer.ref, 'ref layer "' + ref + '" not found')); + } else if (parent.ref) { + errors.push(new ValidationError(key, layer.ref, 'ref cannot reference another ref layer')); + } else { + type = unbundle(parent.type); + } + } else if (type !== 'background') { + if (!layer.source) { + errors.push(new ValidationError(key, layer, 'missing required property "source"')); + } else { + var source = style.sources && style.sources[layer.source]; + var sourceType = source && unbundle(source.type); + if (!source) { + errors.push(new ValidationError(key, layer.source, 'source "' + layer.source + '" not found')); + } else if (sourceType === 'vector' && type === 'raster') { + errors.push(new ValidationError(key, layer.source, 'layer "' + layer.id + '" requires a raster source')); + } else if (sourceType === 'raster' && type !== 'raster') { + errors.push(new ValidationError(key, layer.source, 'layer "' + layer.id + '" requires a vector source')); + } else if (sourceType === 'vector' && !layer['source-layer']) { + errors.push(new ValidationError(key, layer, 'layer "' + layer.id + '" must specify a "source-layer"')); + } else if (sourceType === 'raster-dem' && type !== 'hillshade') { + errors.push(new ValidationError(key, layer.source, 'raster-dem source can only be used with layer type \'hillshade\'.')); + } else if (type === 'line' && layer.paint && layer.paint['line-gradient'] && (sourceType !== 'geojson' || !source.lineMetrics)) { + errors.push(new ValidationError(key, layer, 'layer "' + layer.id + '" specifies a line-gradient, which requires a GeoJSON source with `lineMetrics` enabled.')); + } + } + } + errors = errors.concat(validateObject({ + key: key, + value: layer, + valueSpec: styleSpec.layer, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + '*': function _() { + return []; + }, + type: function type() { + return validate({ + key: key + '.type', + value: layer.type, + valueSpec: styleSpec.layer.type, + style: options.style, + styleSpec: options.styleSpec, + object: layer, + objectKey: 'type' + }); + }, + filter: validateFilter, + layout: function layout(options) { + return validateObject({ + layer: layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + '*': function _(options) { + return validateLayoutProperty(extend({ layerType: type }, options)); + } + } + }); + }, + paint: function paint(options) { + return validateObject({ + layer: layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + '*': function _(options) { + return validatePaintProperty(extend({ layerType: type }, options)); + } + } + }); + } + } + })); + return errors; +} + +function validateString(options) { + var value = options.value; + var key = options.key; + var type = getType(value); + if (type !== 'string') { + return [new ValidationError(key, value, 'string expected, ' + type + ' found')]; + } + return []; +} + +var objectElementValidators = { promoteId: validatePromoteId }; +function validateSource(options) { + var value = options.value; + var key = options.key; + var styleSpec = options.styleSpec; + var style = options.style; + if (!value.type) { + return [new ValidationError(key, value, '"type" is required')]; + } + var type = unbundle(value.type); + var errors; + switch (type) { + case 'vector': + case 'raster': + case 'raster-dem': + errors = validateObject({ + key: key, + value: value, + valueSpec: styleSpec['source_' + type.replace('-', '_')], + style: options.style, + styleSpec: styleSpec, + objectElementValidators: objectElementValidators + }); + return errors; + case 'geojson': + errors = validateObject({ + key: key, + value: value, + valueSpec: styleSpec.source_geojson, + style: style, + styleSpec: styleSpec, + objectElementValidators: objectElementValidators + }); + if (value.cluster) { + for (var prop in value.clusterProperties) { + var ref = value.clusterProperties[prop]; + var operator = ref[0]; + var mapExpr = ref[1]; + var reduceExpr = typeof operator === 'string' ? [ + operator, + ['accumulated'], + [ + 'get', + prop + ] + ] : operator; + errors.push.apply(errors, validateExpression({ + key: key + '.' + prop + '.map', + value: mapExpr, + expressionContext: 'cluster-map' + })); + errors.push.apply(errors, validateExpression({ + key: key + '.' + prop + '.reduce', + value: reduceExpr, + expressionContext: 'cluster-reduce' + })); + } + } + return errors; + case 'video': + return validateObject({ + key: key, + value: value, + valueSpec: styleSpec.source_video, + style: style, + styleSpec: styleSpec + }); + case 'image': + return validateObject({ + key: key, + value: value, + valueSpec: styleSpec.source_image, + style: style, + styleSpec: styleSpec + }); + case 'canvas': + return [new ValidationError(key, null, 'Please use runtime APIs to add canvas sources, rather than including them in stylesheets.', 'source.canvas')]; + default: + return validateEnum({ + key: key + '.type', + value: value.type, + valueSpec: { + values: [ + 'vector', + 'raster', + 'raster-dem', + 'geojson', + 'video', + 'image' + ] + }, + style: style, + styleSpec: styleSpec + }); + } +} +function validatePromoteId(ref) { + var key = ref.key; + var value = ref.value; + if (getType(value) === 'string') { + return validateString({ + key: key, + value: value + }); + } else { + var errors = []; + for (var prop in value) { + errors.push.apply(errors, validateString({ + key: key + '.' + prop, + value: value[prop] + })); + } + return errors; + } +} + +function validateLight(options) { + var light = options.value; + var styleSpec = options.styleSpec; + var lightSpec = styleSpec.light; + var style = options.style; + var errors = []; + var rootType = getType(light); + if (light === undefined) { + return errors; + } else if (rootType !== 'object') { + errors = errors.concat([new ValidationError('light', light, 'object expected, ' + rootType + ' found')]); + return errors; + } + for (var key in light) { + var transitionMatch = key.match(/^(.*)-transition$/); + if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) { + errors = errors.concat(validate({ + key: key, + value: light[key], + valueSpec: styleSpec.transition, + style: style, + styleSpec: styleSpec + })); + } else if (lightSpec[key]) { + errors = errors.concat(validate({ + key: key, + value: light[key], + valueSpec: lightSpec[key], + style: style, + styleSpec: styleSpec + })); + } else { + errors = errors.concat([new ValidationError(key, light[key], 'unknown property "' + key + '"')]); + } + } + return errors; +} + +function validateFormatted(options) { + if (validateString(options).length === 0) { + return []; + } + return validateExpression(options); +} + +function validateImage(options) { + if (validateString(options).length === 0) { + return []; + } + return validateExpression(options); +} + +var VALIDATORS = { + '*': function _() { + return []; + }, + 'array': validateArray, + 'boolean': validateBoolean, + 'number': validateNumber, + 'color': validateColor, + 'constants': validateConstants, + 'enum': validateEnum, + 'filter': validateFilter, + 'function': validateFunction, + 'layer': validateLayer, + 'object': validateObject, + 'source': validateSource, + 'light': validateLight, + 'string': validateString, + 'formatted': validateFormatted, + 'resolvedImage': validateImage +}; +function validate(options) { + var value = options.value; + var valueSpec = options.valueSpec; + var styleSpec = options.styleSpec; + if (valueSpec.expression && isFunction$1(unbundle(value))) { + return validateFunction(options); + } else if (valueSpec.expression && isExpression(deepUnbundle(value))) { + return validateExpression(options); + } else if (valueSpec.type && VALIDATORS[valueSpec.type]) { + return VALIDATORS[valueSpec.type](options); + } else { + var valid = validateObject(extend({}, options, { valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec })); + return valid; + } +} + +function validateGlyphsURL (options) { + var value = options.value; + var key = options.key; + var errors = validateString(options); + if (errors.length) { + return errors; + } + if (value.indexOf('{fontstack}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{fontstack}" token')); + } + if (value.indexOf('{range}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{range}" token')); + } + return errors; +} + +function validateStyleMin(style, styleSpec) { + if (styleSpec === void 0) + styleSpec = v8; + var errors = []; + errors = errors.concat(validate({ + key: '', + value: style, + valueSpec: styleSpec.$root, + styleSpec: styleSpec, + style: style, + objectElementValidators: { + glyphs: validateGlyphsURL, + '*': function _() { + return []; + } + } + })); + if (style.constants) { + errors = errors.concat(validateConstants({ + key: 'constants', + value: style.constants, + style: style, + styleSpec: styleSpec + })); + } + return sortErrors(errors); +} +validateStyleMin.source = wrapCleanErrors(validateSource); +validateStyleMin.light = wrapCleanErrors(validateLight); +validateStyleMin.layer = wrapCleanErrors(validateLayer); +validateStyleMin.filter = wrapCleanErrors(validateFilter); +validateStyleMin.paintProperty = wrapCleanErrors(validatePaintProperty); +validateStyleMin.layoutProperty = wrapCleanErrors(validateLayoutProperty); +function sortErrors(errors) { + return [].concat(errors).sort(function (a, b) { + return a.line - b.line; + }); +} +function wrapCleanErrors(inner) { + return function () { + var args = [], len = arguments.length; + while (len--) + args[len] = arguments[len]; + return sortErrors(inner.apply(this, args)); + }; +} + +var jsonlint = createCommonjsModule(function (module, exports) { +/* parser generated by jison 0.4.15 */ +/* + Returns a Parser object of the following structure: + + Parser: { + yy: {} + } + + Parser.prototype: { + yy: {}, + trace: function(), + symbols_: {associative list: name ==> number}, + terminals_: {associative list: number ==> name}, + productions_: [...], + performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$), + table: [...], + defaultActions: {...}, + parseError: function(str, hash), + parse: function(input), + + lexer: { + EOF: 1, + parseError: function(str, hash), + setInput: function(input), + input: function(), + unput: function(str), + more: function(), + less: function(n), + pastInput: function(), + upcomingInput: function(), + showPosition: function(), + test_match: function(regex_match_array, rule_index), + next: function(), + lex: function(), + begin: function(condition), + popState: function(), + _currentRules: function(), + topState: function(), + pushState: function(condition), + + options: { + ranges: boolean (optional: true ==> token location info will include a .range[] member) + flex: boolean (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match) + backtrack_lexer: boolean (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code) + }, + + performAction: function(yy, yy_, $avoiding_name_collisions, YY_START), + rules: [...], + conditions: {associative list: name ==> set}, + } + } + + + token location info (@$, _$, etc.): { + first_line: n, + last_line: n, + first_column: n, + last_column: n, + range: [start_number, end_number] (where the numbers are indexes into the input string, regular zero-based) + } + + + the parseError function receives a 'hash' object with these members for lexer and parser errors: { + text: (matched text) + token: (the produced terminal token, if any) + line: (yylineno) + } + while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: { + loc: (yylloc) + expected: (string describing the set of expected tokens) + recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error) + } +*/ +var parser = (function(){ +var o=function(k,v,o,l){for(o=o||{},l=k.length;l--;o[k[l]]=v){ }return o},$V0=[1,12],$V1=[1,13],$V2=[1,9],$V3=[1,10],$V4=[1,11],$V5=[1,14],$V6=[1,15],$V7=[14,18,22,24],$V8=[18,22],$V9=[22,24]; +var parser = {trace: function trace() { }, +yy: {}, +symbols_: {"error":2,"JSONString":3,"STRING":4,"JSONNumber":5,"NUMBER":6,"JSONNullLiteral":7,"NULL":8,"JSONBooleanLiteral":9,"TRUE":10,"FALSE":11,"JSONText":12,"JSONValue":13,"EOF":14,"JSONObject":15,"JSONArray":16,"{":17,"}":18,"JSONMemberList":19,"JSONMember":20,":":21,",":22,"[":23,"]":24,"JSONElementList":25,"$accept":0,"$end":1}, +terminals_: {2:"error",4:"STRING",6:"NUMBER",8:"NULL",10:"TRUE",11:"FALSE",14:"EOF",17:"{",18:"}",21:":",22:",",23:"[",24:"]"}, +productions_: [0,[3,1],[5,1],[7,1],[9,1],[9,1],[12,2],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[15,2],[15,3],[20,3],[19,1],[19,3],[16,2],[16,3],[25,1],[25,3]], +performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */) { +/* this == yyval */ + +var $0 = $$.length - 1; +switch (yystate) { +case 1: + // replace escaped characters with actual character + this.$ = new String(yytext.replace(/\\(\\|")/g, "$"+"1") + .replace(/\\n/g,'\n') + .replace(/\\r/g,'\r') + .replace(/\\t/g,'\t') + .replace(/\\v/g,'\v') + .replace(/\\f/g,'\f') + .replace(/\\b/g,'\b')); + this.$.__line__ = this._$.first_line; + +break; +case 2: + + this.$ = new Number(yytext); + this.$.__line__ = this._$.first_line; + +break; +case 3: + + this.$ = null; + +break; +case 4: + + this.$ = new Boolean(true); + this.$.__line__ = this._$.first_line; + +break; +case 5: + + this.$ = new Boolean(false); + this.$.__line__ = this._$.first_line; + +break; +case 6: +return this.$ = $$[$0-1]; +case 13: +this.$ = {}; Object.defineProperty(this.$, '__line__', { + value: this._$.first_line, + enumerable: false + }); +break; +case 14: case 19: +this.$ = $$[$0-1]; Object.defineProperty(this.$, '__line__', { + value: this._$.first_line, + enumerable: false + }); +break; +case 15: +this.$ = [$$[$0-2], $$[$0]]; +break; +case 16: +this.$ = {}; this.$[$$[$0][0]] = $$[$0][1]; +break; +case 17: +this.$ = $$[$0-2]; $$[$0-2][$$[$0][0]] = $$[$0][1]; +break; +case 18: +this.$ = []; Object.defineProperty(this.$, '__line__', { + value: this._$.first_line, + enumerable: false + }); +break; +case 20: +this.$ = [$$[$0]]; +break; +case 21: +this.$ = $$[$0-2]; $$[$0-2].push($$[$0]); +break; +} +}, +table: [{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,12:1,13:2,15:7,16:8,17:$V5,23:$V6},{1:[3]},{14:[1,16]},o($V7,[2,7]),o($V7,[2,8]),o($V7,[2,9]),o($V7,[2,10]),o($V7,[2,11]),o($V7,[2,12]),o($V7,[2,3]),o($V7,[2,4]),o($V7,[2,5]),o([14,18,21,22,24],[2,1]),o($V7,[2,2]),{3:20,4:$V0,18:[1,17],19:18,20:19},{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,13:23,15:7,16:8,17:$V5,23:$V6,24:[1,21],25:22},{1:[2,6]},o($V7,[2,13]),{18:[1,24],22:[1,25]},o($V8,[2,16]),{21:[1,26]},o($V7,[2,18]),{22:[1,28],24:[1,27]},o($V9,[2,20]),o($V7,[2,14]),{3:20,4:$V0,20:29},{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,13:30,15:7,16:8,17:$V5,23:$V6},o($V7,[2,19]),{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,13:31,15:7,16:8,17:$V5,23:$V6},o($V8,[2,17]),o($V8,[2,15]),o($V9,[2,21])], +defaultActions: {16:[2,6]}, +parseError: function parseError(str, hash) { + if (hash.recoverable) { + this.trace(str); + } else { + throw new Error(str); + } +}, +parse: function parse(input) { + var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = '', yylineno = 0, yyleng = 0, TERROR = 2, EOF = 1; + var args = lstack.slice.call(arguments, 1); + var lexer = Object.create(this.lexer); + var sharedState = { yy: {} }; + for (var k in this.yy) { + if (Object.prototype.hasOwnProperty.call(this.yy, k)) { + sharedState.yy[k] = this.yy[k]; + } + } + lexer.setInput(input, sharedState.yy); + sharedState.yy.lexer = lexer; + sharedState.yy.parser = this; + if (typeof lexer.yylloc == 'undefined') { + lexer.yylloc = {}; + } + var yyloc = lexer.yylloc; + lstack.push(yyloc); + var ranges = lexer.options && lexer.options.ranges; + if (typeof sharedState.yy.parseError === 'function') { + this.parseError = sharedState.yy.parseError; + } else { + this.parseError = Object.getPrototypeOf(this).parseError; + } + + function lex() { + var token; + token = lexer.lex() || EOF; + if (typeof token !== 'number') { + token = self.symbols_[token] || token; + } + return token; + } + var symbol, state, action, r, yyval = {}, p, len, newState, expected; + while (true) { + state = stack[stack.length - 1]; + if (this.defaultActions[state]) { + action = this.defaultActions[state]; + } else { + if (symbol === null || typeof symbol == 'undefined') { + symbol = lex(); + } + action = table[state] && table[state][symbol]; + } + if (typeof action === 'undefined' || !action.length || !action[0]) { + var errStr = ''; + expected = []; + for (p in table[state]) { + if (this.terminals_[p] && p > TERROR) { + expected.push('\'' + this.terminals_[p] + '\''); + } + } + if (lexer.showPosition) { + errStr = 'Parse error on line ' + (yylineno + 1) + ':\n' + lexer.showPosition() + '\nExpecting ' + expected.join(', ') + ', got \'' + (this.terminals_[symbol] || symbol) + '\''; + } else { + errStr = 'Parse error on line ' + (yylineno + 1) + ': Unexpected ' + (symbol == EOF ? 'end of input' : '\'' + (this.terminals_[symbol] || symbol) + '\''); + } + this.parseError(errStr, { + text: lexer.match, + token: this.terminals_[symbol] || symbol, + line: lexer.yylineno, + loc: yyloc, + expected: expected + }); + } + if (action[0] instanceof Array && action.length > 1) { + throw new Error('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol); + } + switch (action[0]) { + case 1: + stack.push(symbol); + vstack.push(lexer.yytext); + lstack.push(lexer.yylloc); + stack.push(action[1]); + symbol = null; + { + yyleng = lexer.yyleng; + yytext = lexer.yytext; + yylineno = lexer.yylineno; + yyloc = lexer.yylloc; + } + break; + case 2: + len = this.productions_[action[1]][1]; + yyval.$ = vstack[vstack.length - len]; + yyval._$ = { + first_line: lstack[lstack.length - (len || 1)].first_line, + last_line: lstack[lstack.length - 1].last_line, + first_column: lstack[lstack.length - (len || 1)].first_column, + last_column: lstack[lstack.length - 1].last_column + }; + if (ranges) { + yyval._$.range = [ + lstack[lstack.length - (len || 1)].range[0], + lstack[lstack.length - 1].range[1] + ]; + } + r = this.performAction.apply(yyval, [ + yytext, + yyleng, + yylineno, + sharedState.yy, + action[1], + vstack, + lstack + ].concat(args)); + if (typeof r !== 'undefined') { + return r; + } + if (len) { + stack = stack.slice(0, -1 * len * 2); + vstack = vstack.slice(0, -1 * len); + lstack = lstack.slice(0, -1 * len); + } + stack.push(this.productions_[action[1]][0]); + vstack.push(yyval.$); + lstack.push(yyval._$); + newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; + stack.push(newState); + break; + case 3: + return true; + } + } + return true; +}}; +/* generated by jison-lex 0.3.4 */ +var lexer = (function(){ +var lexer = ({ + +EOF:1, + +parseError:function parseError(str, hash) { + if (this.yy.parser) { + this.yy.parser.parseError(str, hash); + } else { + throw new Error(str); + } + }, + +// resets the lexer, sets new input +setInput:function (input, yy) { + this.yy = yy || this.yy || {}; + this._input = input; + this._more = this._backtrack = this.done = false; + this.yylineno = this.yyleng = 0; + this.yytext = this.matched = this.match = ''; + this.conditionStack = ['INITIAL']; + this.yylloc = { + first_line: 1, + first_column: 0, + last_line: 1, + last_column: 0 + }; + if (this.options.ranges) { + this.yylloc.range = [0,0]; + } + this.offset = 0; + return this; + }, + +// consumes and returns one char from the input +input:function () { + var ch = this._input[0]; + this.yytext += ch; + this.yyleng++; + this.offset++; + this.match += ch; + this.matched += ch; + var lines = ch.match(/(?:\r\n?|\n).*/g); + if (lines) { + this.yylineno++; + this.yylloc.last_line++; + } else { + this.yylloc.last_column++; + } + if (this.options.ranges) { + this.yylloc.range[1]++; + } + + this._input = this._input.slice(1); + return ch; + }, + +// unshifts one char (or a string) into the input +unput:function (ch) { + var len = ch.length; + var lines = ch.split(/(?:\r\n?|\n)/g); + + this._input = ch + this._input; + this.yytext = this.yytext.substr(0, this.yytext.length - len); + //this.yyleng -= len; + this.offset -= len; + var oldLines = this.match.split(/(?:\r\n?|\n)/g); + this.match = this.match.substr(0, this.match.length - 1); + this.matched = this.matched.substr(0, this.matched.length - 1); + + if (lines.length - 1) { + this.yylineno -= lines.length - 1; + } + var r = this.yylloc.range; + + this.yylloc = { + first_line: this.yylloc.first_line, + last_line: this.yylineno + 1, + first_column: this.yylloc.first_column, + last_column: lines ? + (lines.length === oldLines.length ? this.yylloc.first_column : 0) + + oldLines[oldLines.length - lines.length].length - lines[0].length : + this.yylloc.first_column - len + }; + + if (this.options.ranges) { + this.yylloc.range = [r[0], r[0] + this.yyleng - len]; + } + this.yyleng = this.yytext.length; + return this; + }, + +// When called from action, caches matched text and appends it on next action +more:function () { + this._more = true; + return this; + }, + +// When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead. +reject:function () { + if (this.options.backtrack_lexer) { + this._backtrack = true; + } else { + return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n' + this.showPosition(), { + text: "", + token: null, + line: this.yylineno + }); + + } + return this; + }, + +// retain first n characters of the match +less:function (n) { + this.unput(this.match.slice(n)); + }, + +// displays already matched input, i.e. for error messages +pastInput:function () { + var past = this.matched.substr(0, this.matched.length - this.match.length); + return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); + }, + +// displays upcoming input, i.e. for error messages +upcomingInput:function () { + var next = this.match; + if (next.length < 20) { + next += this._input.substr(0, 20-next.length); + } + return (next.substr(0,20) + (next.length > 20 ? '...' : '')).replace(/\n/g, ""); + }, + +// displays the character position where the lexing error occurred, i.e. for error messages +showPosition:function () { + var pre = this.pastInput(); + var c = new Array(pre.length + 1).join("-"); + return pre + this.upcomingInput() + "\n" + c + "^"; + }, + +// test the lexed token: return FALSE when not a match, otherwise return token +test_match:function (match, indexed_rule) { + var token, + lines, + backup; + + if (this.options.backtrack_lexer) { + // save context + backup = { + yylineno: this.yylineno, + yylloc: { + first_line: this.yylloc.first_line, + last_line: this.last_line, + first_column: this.yylloc.first_column, + last_column: this.yylloc.last_column + }, + yytext: this.yytext, + match: this.match, + matches: this.matches, + matched: this.matched, + yyleng: this.yyleng, + offset: this.offset, + _more: this._more, + _input: this._input, + yy: this.yy, + conditionStack: this.conditionStack.slice(0), + done: this.done + }; + if (this.options.ranges) { + backup.yylloc.range = this.yylloc.range.slice(0); + } + } + + lines = match[0].match(/(?:\r\n?|\n).*/g); + if (lines) { + this.yylineno += lines.length; + } + this.yylloc = { + first_line: this.yylloc.last_line, + last_line: this.yylineno + 1, + first_column: this.yylloc.last_column, + last_column: lines ? + lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : + this.yylloc.last_column + match[0].length + }; + this.yytext += match[0]; + this.match += match[0]; + this.matches = match; + this.yyleng = this.yytext.length; + if (this.options.ranges) { + this.yylloc.range = [this.offset, this.offset += this.yyleng]; + } + this._more = false; + this._backtrack = false; + this._input = this._input.slice(match[0].length); + this.matched += match[0]; + token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]); + if (this.done && this._input) { + this.done = false; + } + if (token) { + return token; + } else if (this._backtrack) { + // recover context + for (var k in backup) { + this[k] = backup[k]; + } + return false; // rule action called reject() implying the next rule should be tested instead. + } + return false; + }, + +// return next match in input +next:function () { + if (this.done) { + return this.EOF; + } + if (!this._input) { + this.done = true; + } + + var token, + match, + tempMatch, + index; + if (!this._more) { + this.yytext = ''; + this.match = ''; + } + var rules = this._currentRules(); + for (var i = 0; i < rules.length; i++) { + tempMatch = this._input.match(this.rules[rules[i]]); + if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { + match = tempMatch; + index = i; + if (this.options.backtrack_lexer) { + token = this.test_match(tempMatch, rules[i]); + if (token !== false) { + return token; + } else if (this._backtrack) { + match = false; + continue; // rule action called reject() implying a rule MISmatch. + } else { + // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) + return false; + } + } else if (!this.options.flex) { + break; + } + } + } + if (match) { + token = this.test_match(match, rules[index]); + if (token !== false) { + return token; + } + // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) + return false; + } + if (this._input === "") { + return this.EOF; + } else { + return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { + text: "", + token: null, + line: this.yylineno + }); + } + }, + +// return next match that has a token +lex:function lex() { + var r = this.next(); + if (r) { + return r; + } else { + return this.lex(); + } + }, + +// activates a new lexer condition state (pushes the new lexer condition state onto the condition stack) +begin:function begin(condition) { + this.conditionStack.push(condition); + }, + +// pop the previously active lexer condition state off the condition stack +popState:function popState() { + var n = this.conditionStack.length - 1; + if (n > 0) { + return this.conditionStack.pop(); + } else { + return this.conditionStack[0]; + } + }, + +// produce the lexer rule set which is active for the currently active lexer condition state +_currentRules:function _currentRules() { + if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) { + return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules; + } else { + return this.conditions["INITIAL"].rules; + } + }, + +// return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available +topState:function topState(n) { + n = this.conditionStack.length - 1 - Math.abs(n || 0); + if (n >= 0) { + return this.conditionStack[n]; + } else { + return "INITIAL"; + } + }, + +// alias for begin(condition) +pushState:function pushState(condition) { + this.begin(condition); + }, + +// return the number of states currently on the stack +stateStackSize:function stateStackSize() { + return this.conditionStack.length; + }, +options: {}, +performAction: function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { +switch($avoiding_name_collisions) { +case 0:/* skip whitespace */ +break; +case 1:return 6 +case 2:yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2); return 4 +case 3:return 17 +case 4:return 18 +case 5:return 23 +case 6:return 24 +case 7:return 22 +case 8:return 21 +case 9:return 10 +case 10:return 11 +case 11:return 8 +case 12:return 14 +case 13:return 'INVALID' +} +}, +rules: [/^(?:\s+)/,/^(?:(-?([0-9]|[1-9][0-9]+))(\.[0-9]+)?([eE][-+]?[0-9]+)?\b)/,/^(?:"(?:\\[\\"bfnrt/]|\\u[a-fA-F0-9]{4}|[^\\\0-\x09\x0a-\x1f"])*")/,/^(?:\{)/,/^(?:\})/,/^(?:\[)/,/^(?:\])/,/^(?:,)/,/^(?::)/,/^(?:true\b)/,/^(?:false\b)/,/^(?:null\b)/,/^(?:$)/,/^(?:.)/], +conditions: {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13],"inclusive":true}} +}); +return lexer; +})(); +parser.lexer = lexer; +function Parser () { + this.yy = {}; +} +Parser.prototype = parser;parser.Parser = Parser; +return new Parser; +})(); + + +if (typeof commonjsRequire !== 'undefined' && 'object' !== 'undefined') { +exports.parser = parser; +exports.Parser = parser.Parser; +exports.parse = function () { return parser.parse.apply(parser, arguments); }; +} +}); +var jsonlint_1 = jsonlint.parser; +var jsonlint_2 = jsonlint.Parser; +var jsonlint_3 = jsonlint.parse; + +function readStyle(style) { + if (style instanceof String || typeof style === 'string' || style instanceof Buffer) { + try { + return jsonlint.parse(style.toString()); + } catch (e) { + throw new ParsingError$1(e); + } + } + return style; +} + +function validateStyle(style, styleSpec) { + if (styleSpec === void 0) + styleSpec = v8; + var s = style; + try { + s = readStyle(s); + } catch (e) { + return [e]; + } + return validateStyleMin(s, styleSpec); +} + +var SUPPORTED_SPEC_VERSION = 8; +var MAX_SOURCES_IN_STYLE = 15; +function isValid(value, regex) { + if (!value || getType(value) !== 'string') { + return true; + } + return !!value.match(regex); +} +function getSourceCount(source) { + if (source.url) { + return source.url.split(',').length; + } else { + return 0; + } +} +function getAllowedKeyErrors(obj, keys, path) { + var allowed = new Set(keys); + var errors = []; + Object.keys(obj).forEach(function (k) { + if (!allowed.has(k)) { + var prop = path ? path + '.' + k : null; + errors.push(new ValidationError(prop, obj[k], 'Unsupported property "' + k + '"')); + } + }); + return errors; +} +function getSourceErrors(source, i) { + var errors = []; + var sourceKeys = [ + 'type', + 'url', + 'tileSize' + ]; + errors.push.apply(errors, getAllowedKeyErrors(source, sourceKeys, 'source')); + var sourceUrlPattern = /^mapbox:\/\/([^/]*)$/; + if (!isValid(source.url, sourceUrlPattern)) { + errors.push(new ValidationError('sources[' + i + ']', source.url, 'Source url must be a valid Mapbox tileset url')); + } + return errors; +} +function getSourcesErrors(sources) { + var errors = []; + var count = 0; + Object.keys(sources).forEach(function (s, i) { + var sourceErrors = getSourceErrors(sources[s], i); + if (!sourceErrors.length) { + count = count + getSourceCount(sources[s]); + } + errors.push.apply(errors, sourceErrors); + }); + if (count > MAX_SOURCES_IN_STYLE) { + errors.push(new ValidationError('sources', null, 'Styles must contain ' + MAX_SOURCES_IN_STYLE + ' or fewer sources')); + } + return errors; +} +function getRootErrors(style, specKeys) { + var errors = []; + var optionalRootProperties = [ + 'owner', + 'id', + 'cacheControl', + 'draft', + 'created', + 'modified', + 'visibility' + ]; + var allowedKeyErrors = getAllowedKeyErrors(style, specKeys.concat(optionalRootProperties)); + errors.push.apply(errors, allowedKeyErrors); + if (style.version > SUPPORTED_SPEC_VERSION || style.version < SUPPORTED_SPEC_VERSION) { + errors.push(new ValidationError('version', style.version, 'Style version must be ' + SUPPORTED_SPEC_VERSION)); + } + var glyphUrlPattern = /^mapbox:\/\/fonts\/([^/]*)\/{fontstack}\/{range}.pbf$/; + if (!isValid(style.glyphs, glyphUrlPattern)) { + errors.push(new ValidationError('glyphs', style.glyphs, 'Styles must reference glyphs hosted by Mapbox')); + } + var spriteUrlPattern = /^mapbox:\/\/sprites\/([^/]*)\/([^/]*)\/?([^/]*)?$/; + if (!isValid(style.sprite, spriteUrlPattern)) { + errors.push(new ValidationError('sprite', style.sprite, 'Styles must reference sprites hosted by Mapbox')); + } + var visibilityPattern = /^(public|private)$/; + if (!isValid(style.visibility, visibilityPattern)) { + errors.push(new ValidationError('visibility', style.visibility, 'Style visibility must be public or private')); + } + return errors; +} +function validateMapboxApiSupported(style) { + var s = style; + try { + s = readStyle(s); + } catch (e) { + return [e]; + } + var errors = validateStyleMin(s, v8).concat(getRootErrors(s, Object.keys(v8.$root))); + if (s.sources) { + errors = errors.concat(getSourcesErrors(s.sources)); + } + return errors; +} + +var expression$1 = { + StyleExpression: StyleExpression, + isExpression: isExpression, + isExpressionFilter: isExpressionFilter, + createExpression: createExpression, + createPropertyExpression: createPropertyExpression, + normalizePropertyExpression: normalizePropertyExpression, + ZoomConstantExpression: ZoomConstantExpression, + ZoomDependentExpression: ZoomDependentExpression, + StylePropertyFunction: StylePropertyFunction +}; +var styleFunction = { + convertFunction: convertFunction, + createFunction: createFunction, + isFunction: isFunction$1 +}; +var visit = { + eachSource: eachSource, + eachLayer: eachLayer, + eachProperty: eachProperty +}; +validateStyle.parsed = validateStyle; +validateStyle.latest = validateStyle; + +export { Color, ParsingError$1 as ParsingError, ValidationError, composite, convertFilter$1 as convertFilter, derefLayers, diffStyles as diff, expression$1 as expression, createFilter as featureFilter, format, styleFunction as function, v8 as latest, migrate, v8, validateStyle as validate, validateMapboxApiSupported, visit }; +//# sourceMappingURL=index.es.js.map diff --git a/node_modules/mapbox-gl/src/style-spec/dist/index.es.js.map b/node_modules/mapbox-gl/src/style-spec/dist/index.es.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ea6b6daaae73d6a54328960b709243e3fbd69008 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/dist/index.es.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.es.js","sources":["../../../node_modules/json-stringify-pretty-compact/index.js","../format.js","../../../node_modules/url/node_modules/punycode/punycode.js","../../../node_modules/url/util.js","../../../node_modules/querystring/decode.js","../../../node_modules/querystring/encode.js","../../../node_modules/querystring/index.js","../../../node_modules/url/url.js","../visit.js","../migrate/v8.js","../util/extend.js","../expression/parsing_error.js","../expression/scope.js","../expression/types.js","../../../node_modules/csscolorparser/csscolorparser.js","../util/color.js","../expression/types/collator.js","../expression/types/formatted.js","../expression/types/resolved_image.js","../expression/values.js","../expression/definitions/literal.js","../expression/runtime_error.js","../expression/definitions/assertion.js","../expression/definitions/format.js","../expression/definitions/image.js","../expression/definitions/coercion.js","../expression/evaluation_context.js","../expression/compound_expression.js","../expression/definitions/collator.js","../expression/definitions/within.js","../expression/is_constant.js","../expression/definitions/var.js","../expression/parsing_context.js","../expression/stops.js","../expression/definitions/step.js","../../../node_modules/@mapbox/unitbezier/index.js","../util/interpolate.js","../util/color_spaces.js","../expression/definitions/interpolate.js","../expression/definitions/coalesce.js","../expression/definitions/let.js","../expression/definitions/at.js","../expression/definitions/in.js","../expression/definitions/index_of.js","../expression/definitions/match.js","../expression/definitions/case.js","../expression/definitions/slice.js","../expression/definitions/comparison.js","../expression/definitions/number_format.js","../expression/definitions/length.js","../expression/definitions/index.js","../util/result.js","../util/properties.js","../util/get_type.js","../function/index.js","../expression/index.js","../function/convert.js","../feature_filter/index.js","../feature_filter/convert.js","../migrate/expressions.js","../migrate.js","../composite.js","../util/ref_properties.js","../deref.js","../util/deep_equal.js","../diff.js","../error/validation_error.js","../error/parsing_error.js","../validate/validate_constants.js","../util/unbundle_jsonlint.js","../validate/validate_object.js","../validate/validate_array.js","../validate/validate_number.js","../validate/validate_function.js","../validate/validate_expression.js","../validate/validate_boolean.js","../validate/validate_color.js","../validate/validate_enum.js","../validate/validate_filter.js","../validate/validate_property.js","../validate/validate_paint_property.js","../validate/validate_layout_property.js","../validate/validate_layer.js","../validate/validate_string.js","../validate/validate_source.js","../validate/validate_light.js","../validate/validate_formatted.js","../validate/validate_image.js","../validate/validate.js","../validate/validate_glyphs_url.js","../validate_style.min.js","../../../node_modules/@mapbox/jsonlint-lines-primitives/lib/jsonlint.js","../read_style.js","../validate_style.js","../validate_mapbox_api_supported.js","../style-spec.js"],"sourcesContent":["\"use strict\";\n\n// Note: This regex matches even invalid JSON strings, but since we’re\n// working on the output of `JSON.stringify` we know that only valid strings\n// are present (unless the user supplied a weird `options.indent` but in\n// that case we don’t care since the output would be invalid anyway).\nvar stringOrChar = /(\"(?:[^\\\\\"]|\\\\.)*\")|[:,]/g;\n\nmodule.exports = function stringify(passedObj, options) {\n var indent, maxLength, replacer;\n\n options = options || {};\n indent = JSON.stringify(\n [1],\n undefined,\n options.indent === undefined ? 2 : options.indent\n ).slice(2, -3);\n maxLength =\n indent === \"\"\n ? Infinity\n : options.maxLength === undefined\n ? 80\n : options.maxLength;\n replacer = options.replacer;\n\n return (function _stringify(obj, currentIndent, reserved) {\n // prettier-ignore\n var end, index, items, key, keyPart, keys, length, nextIndent, prettified, start, string, value;\n\n if (obj && typeof obj.toJSON === \"function\") {\n obj = obj.toJSON();\n }\n\n string = JSON.stringify(obj, replacer);\n\n if (string === undefined) {\n return string;\n }\n\n length = maxLength - currentIndent.length - reserved;\n\n if (string.length <= length) {\n prettified = string.replace(stringOrChar, function(match, stringLiteral) {\n return stringLiteral || match + \" \";\n });\n if (prettified.length <= length) {\n return prettified;\n }\n }\n\n if (replacer != null) {\n obj = JSON.parse(string);\n replacer = undefined;\n }\n\n if (typeof obj === \"object\" && obj !== null) {\n nextIndent = currentIndent + indent;\n items = [];\n index = 0;\n\n if (Array.isArray(obj)) {\n start = \"[\";\n end = \"]\";\n length = obj.length;\n for (; index < length; index++) {\n items.push(\n _stringify(obj[index], nextIndent, index === length - 1 ? 0 : 1) ||\n \"null\"\n );\n }\n } else {\n start = \"{\";\n end = \"}\";\n keys = Object.keys(obj);\n length = keys.length;\n for (; index < length; index++) {\n key = keys[index];\n keyPart = JSON.stringify(key) + \": \";\n value = _stringify(\n obj[key],\n nextIndent,\n keyPart.length + (index === length - 1 ? 0 : 1)\n );\n if (value !== undefined) {\n items.push(keyPart + value);\n }\n }\n }\n\n if (items.length > 0) {\n return [start, indent + items.join(\",\\n\" + nextIndent), end].join(\n \"\\n\" + currentIndent\n );\n }\n }\n\n return string;\n })(passedObj, \"\", 0);\n};\n","\nimport reference from './reference/latest.js';\nimport stringifyPretty from 'json-stringify-pretty-compact';\n\nfunction sortKeysBy(obj, reference) {\n const result = {};\n for (const key in reference) {\n if (obj[key] !== undefined) {\n result[key] = obj[key];\n }\n }\n for (const key in obj) {\n if (result[key] === undefined) {\n result[key] = obj[key];\n }\n }\n return result;\n}\n\n/**\n * Format a Mapbox GL Style. Returns a stringified style with its keys\n * sorted in the same order as the reference style.\n *\n * The optional `space` argument is passed to\n * [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)\n * to generate formatted output.\n *\n * If `space` is unspecified, a default of `2` spaces will be used.\n *\n * @private\n * @param {Object} style a Mapbox GL Style\n * @param {number} [space] space argument to pass to `JSON.stringify`\n * @returns {string} stringified formatted JSON\n * @example\n * var fs = require('fs');\n * var format = require('mapbox-gl-style-spec').format;\n * var style = fs.readFileSync('./source.json', 'utf8');\n * fs.writeFileSync('./dest.json', format(style));\n * fs.writeFileSync('./dest.min.json', format(style, 0));\n */\nfunction format(style, space = 2) {\n style = sortKeysBy(style, reference.$root);\n\n if (style.layers) {\n style.layers = style.layers.map((layer) => sortKeysBy(layer, reference.layer));\n }\n\n return stringifyPretty(style, {indent: space});\n}\n\nexport default format;\n","/*! https://mths.be/punycode v1.3.2 by @mathias */\n;(function(root) {\n\n\t/** Detect free variables */\n\tvar freeExports = typeof exports == 'object' && exports &&\n\t\t!exports.nodeType && exports;\n\tvar freeModule = typeof module == 'object' && module &&\n\t\t!module.nodeType && module;\n\tvar freeGlobal = typeof global == 'object' && global;\n\tif (\n\t\tfreeGlobal.global === freeGlobal ||\n\t\tfreeGlobal.window === freeGlobal ||\n\t\tfreeGlobal.self === freeGlobal\n\t) {\n\t\troot = freeGlobal;\n\t}\n\n\t/**\n\t * The `punycode` object.\n\t * @name punycode\n\t * @type Object\n\t */\n\tvar punycode,\n\n\t/** Highest positive signed 32-bit float value */\n\tmaxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1\n\n\t/** Bootstring parameters */\n\tbase = 36,\n\ttMin = 1,\n\ttMax = 26,\n\tskew = 38,\n\tdamp = 700,\n\tinitialBias = 72,\n\tinitialN = 128, // 0x80\n\tdelimiter = '-', // '\\x2D'\n\n\t/** Regular expressions */\n\tregexPunycode = /^xn--/,\n\tregexNonASCII = /[^\\x20-\\x7E]/, // unprintable ASCII chars + non-ASCII chars\n\tregexSeparators = /[\\x2E\\u3002\\uFF0E\\uFF61]/g, // RFC 3490 separators\n\n\t/** Error messages */\n\terrors = {\n\t\t'overflow': 'Overflow: input needs wider integers to process',\n\t\t'not-basic': 'Illegal input >= 0x80 (not a basic code point)',\n\t\t'invalid-input': 'Invalid input'\n\t},\n\n\t/** Convenience shortcuts */\n\tbaseMinusTMin = base - tMin,\n\tfloor = Math.floor,\n\tstringFromCharCode = String.fromCharCode,\n\n\t/** Temporary variable */\n\tkey;\n\n\t/*--------------------------------------------------------------------------*/\n\n\t/**\n\t * A generic error utility function.\n\t * @private\n\t * @param {String} type The error type.\n\t * @returns {Error} Throws a `RangeError` with the applicable error message.\n\t */\n\tfunction error(type) {\n\t\tthrow RangeError(errors[type]);\n\t}\n\n\t/**\n\t * A generic `Array#map` utility function.\n\t * @private\n\t * @param {Array} array The array to iterate over.\n\t * @param {Function} callback The function that gets called for every array\n\t * item.\n\t * @returns {Array} A new array of values returned by the callback function.\n\t */\n\tfunction map(array, fn) {\n\t\tvar length = array.length;\n\t\tvar result = [];\n\t\twhile (length--) {\n\t\t\tresult[length] = fn(array[length]);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * A simple `Array#map`-like wrapper to work with domain name strings or email\n\t * addresses.\n\t * @private\n\t * @param {String} domain The domain name or email address.\n\t * @param {Function} callback The function that gets called for every\n\t * character.\n\t * @returns {Array} A new string of characters returned by the callback\n\t * function.\n\t */\n\tfunction mapDomain(string, fn) {\n\t\tvar parts = string.split('@');\n\t\tvar result = '';\n\t\tif (parts.length > 1) {\n\t\t\t// In email addresses, only the domain name should be punycoded. Leave\n\t\t\t// the local part (i.e. everything up to `@`) intact.\n\t\t\tresult = parts[0] + '@';\n\t\t\tstring = parts[1];\n\t\t}\n\t\t// Avoid `split(regex)` for IE8 compatibility. See #17.\n\t\tstring = string.replace(regexSeparators, '\\x2E');\n\t\tvar labels = string.split('.');\n\t\tvar encoded = map(labels, fn).join('.');\n\t\treturn result + encoded;\n\t}\n\n\t/**\n\t * Creates an array containing the numeric code points of each Unicode\n\t * character in the string. While JavaScript uses UCS-2 internally,\n\t * this function will convert a pair of surrogate halves (each of which\n\t * UCS-2 exposes as separate characters) into a single code point,\n\t * matching UTF-16.\n\t * @see `punycode.ucs2.encode`\n\t * @see \n\t * @memberOf punycode.ucs2\n\t * @name decode\n\t * @param {String} string The Unicode input string (UCS-2).\n\t * @returns {Array} The new array of code points.\n\t */\n\tfunction ucs2decode(string) {\n\t\tvar output = [],\n\t\t counter = 0,\n\t\t length = string.length,\n\t\t value,\n\t\t extra;\n\t\twhile (counter < length) {\n\t\t\tvalue = string.charCodeAt(counter++);\n\t\t\tif (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n\t\t\t\t// high surrogate, and there is a next character\n\t\t\t\textra = string.charCodeAt(counter++);\n\t\t\t\tif ((extra & 0xFC00) == 0xDC00) { // low surrogate\n\t\t\t\t\toutput.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n\t\t\t\t} else {\n\t\t\t\t\t// unmatched surrogate; only append this code unit, in case the next\n\t\t\t\t\t// code unit is the high surrogate of a surrogate pair\n\t\t\t\t\toutput.push(value);\n\t\t\t\t\tcounter--;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toutput.push(value);\n\t\t\t}\n\t\t}\n\t\treturn output;\n\t}\n\n\t/**\n\t * Creates a string based on an array of numeric code points.\n\t * @see `punycode.ucs2.decode`\n\t * @memberOf punycode.ucs2\n\t * @name encode\n\t * @param {Array} codePoints The array of numeric code points.\n\t * @returns {String} The new Unicode string (UCS-2).\n\t */\n\tfunction ucs2encode(array) {\n\t\treturn map(array, function(value) {\n\t\t\tvar output = '';\n\t\t\tif (value > 0xFFFF) {\n\t\t\t\tvalue -= 0x10000;\n\t\t\t\toutput += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);\n\t\t\t\tvalue = 0xDC00 | value & 0x3FF;\n\t\t\t}\n\t\t\toutput += stringFromCharCode(value);\n\t\t\treturn output;\n\t\t}).join('');\n\t}\n\n\t/**\n\t * Converts a basic code point into a digit/integer.\n\t * @see `digitToBasic()`\n\t * @private\n\t * @param {Number} codePoint The basic numeric code point value.\n\t * @returns {Number} The numeric value of a basic code point (for use in\n\t * representing integers) in the range `0` to `base - 1`, or `base` if\n\t * the code point does not represent a value.\n\t */\n\tfunction basicToDigit(codePoint) {\n\t\tif (codePoint - 48 < 10) {\n\t\t\treturn codePoint - 22;\n\t\t}\n\t\tif (codePoint - 65 < 26) {\n\t\t\treturn codePoint - 65;\n\t\t}\n\t\tif (codePoint - 97 < 26) {\n\t\t\treturn codePoint - 97;\n\t\t}\n\t\treturn base;\n\t}\n\n\t/**\n\t * Converts a digit/integer into a basic code point.\n\t * @see `basicToDigit()`\n\t * @private\n\t * @param {Number} digit The numeric value of a basic code point.\n\t * @returns {Number} The basic code point whose value (when used for\n\t * representing integers) is `digit`, which needs to be in the range\n\t * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is\n\t * used; else, the lowercase form is used. The behavior is undefined\n\t * if `flag` is non-zero and `digit` has no uppercase form.\n\t */\n\tfunction digitToBasic(digit, flag) {\n\t\t// 0..25 map to ASCII a..z or A..Z\n\t\t// 26..35 map to ASCII 0..9\n\t\treturn digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);\n\t}\n\n\t/**\n\t * Bias adaptation function as per section 3.4 of RFC 3492.\n\t * http://tools.ietf.org/html/rfc3492#section-3.4\n\t * @private\n\t */\n\tfunction adapt(delta, numPoints, firstTime) {\n\t\tvar k = 0;\n\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\tdelta += floor(delta / numPoints);\n\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t}\n\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t}\n\n\t/**\n\t * Converts a Punycode string of ASCII-only symbols to a string of Unicode\n\t * symbols.\n\t * @memberOf punycode\n\t * @param {String} input The Punycode string of ASCII-only symbols.\n\t * @returns {String} The resulting string of Unicode symbols.\n\t */\n\tfunction decode(input) {\n\t\t// Don't use UCS-2\n\t\tvar output = [],\n\t\t inputLength = input.length,\n\t\t out,\n\t\t i = 0,\n\t\t n = initialN,\n\t\t bias = initialBias,\n\t\t basic,\n\t\t j,\n\t\t index,\n\t\t oldi,\n\t\t w,\n\t\t k,\n\t\t digit,\n\t\t t,\n\t\t /** Cached calculation results */\n\t\t baseMinusT;\n\n\t\t// Handle the basic code points: let `basic` be the number of input code\n\t\t// points before the last delimiter, or `0` if there is none, then copy\n\t\t// the first basic code points to the output.\n\n\t\tbasic = input.lastIndexOf(delimiter);\n\t\tif (basic < 0) {\n\t\t\tbasic = 0;\n\t\t}\n\n\t\tfor (j = 0; j < basic; ++j) {\n\t\t\t// if it's not a basic code point\n\t\t\tif (input.charCodeAt(j) >= 0x80) {\n\t\t\t\terror('not-basic');\n\t\t\t}\n\t\t\toutput.push(input.charCodeAt(j));\n\t\t}\n\n\t\t// Main decoding loop: start just after the last delimiter if any basic code\n\t\t// points were copied; start at the beginning otherwise.\n\n\t\tfor (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {\n\n\t\t\t// `index` is the index of the next character to be consumed.\n\t\t\t// Decode a generalized variable-length integer into `delta`,\n\t\t\t// which gets added to `i`. The overflow checking is easier\n\t\t\t// if we increase `i` as we go, then subtract off its starting\n\t\t\t// value at the end to obtain `delta`.\n\t\t\tfor (oldi = i, w = 1, k = base; /* no condition */; k += base) {\n\n\t\t\t\tif (index >= inputLength) {\n\t\t\t\t\terror('invalid-input');\n\t\t\t\t}\n\n\t\t\t\tdigit = basicToDigit(input.charCodeAt(index++));\n\n\t\t\t\tif (digit >= base || digit > floor((maxInt - i) / w)) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\ti += digit * w;\n\t\t\t\tt = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\n\t\t\t\tif (digit < t) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tbaseMinusT = base - t;\n\t\t\t\tif (w > floor(maxInt / baseMinusT)) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\tw *= baseMinusT;\n\n\t\t\t}\n\n\t\t\tout = output.length + 1;\n\t\t\tbias = adapt(i - oldi, out, oldi == 0);\n\n\t\t\t// `i` was supposed to wrap around from `out` to `0`,\n\t\t\t// incrementing `n` each time, so we'll fix that now:\n\t\t\tif (floor(i / out) > maxInt - n) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tn += floor(i / out);\n\t\t\ti %= out;\n\n\t\t\t// Insert `n` at position `i` of the output\n\t\t\toutput.splice(i++, 0, n);\n\n\t\t}\n\n\t\treturn ucs2encode(output);\n\t}\n\n\t/**\n\t * Converts a string of Unicode symbols (e.g. a domain name label) to a\n\t * Punycode string of ASCII-only symbols.\n\t * @memberOf punycode\n\t * @param {String} input The string of Unicode symbols.\n\t * @returns {String} The resulting Punycode string of ASCII-only symbols.\n\t */\n\tfunction encode(input) {\n\t\tvar n,\n\t\t delta,\n\t\t handledCPCount,\n\t\t basicLength,\n\t\t bias,\n\t\t j,\n\t\t m,\n\t\t q,\n\t\t k,\n\t\t t,\n\t\t currentValue,\n\t\t output = [],\n\t\t /** `inputLength` will hold the number of code points in `input`. */\n\t\t inputLength,\n\t\t /** Cached calculation results */\n\t\t handledCPCountPlusOne,\n\t\t baseMinusT,\n\t\t qMinusT;\n\n\t\t// Convert the input in UCS-2 to Unicode\n\t\tinput = ucs2decode(input);\n\n\t\t// Cache the length\n\t\tinputLength = input.length;\n\n\t\t// Initialize the state\n\t\tn = initialN;\n\t\tdelta = 0;\n\t\tbias = initialBias;\n\n\t\t// Handle the basic code points\n\t\tfor (j = 0; j < inputLength; ++j) {\n\t\t\tcurrentValue = input[j];\n\t\t\tif (currentValue < 0x80) {\n\t\t\t\toutput.push(stringFromCharCode(currentValue));\n\t\t\t}\n\t\t}\n\n\t\thandledCPCount = basicLength = output.length;\n\n\t\t// `handledCPCount` is the number of code points that have been handled;\n\t\t// `basicLength` is the number of basic code points.\n\n\t\t// Finish the basic string - if it is not empty - with a delimiter\n\t\tif (basicLength) {\n\t\t\toutput.push(delimiter);\n\t\t}\n\n\t\t// Main encoding loop:\n\t\twhile (handledCPCount < inputLength) {\n\n\t\t\t// All non-basic code points < n have been handled already. Find the next\n\t\t\t// larger one:\n\t\t\tfor (m = maxInt, j = 0; j < inputLength; ++j) {\n\t\t\t\tcurrentValue = input[j];\n\t\t\t\tif (currentValue >= n && currentValue < m) {\n\t\t\t\t\tm = currentValue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Increase `delta` enough to advance the decoder's state to ,\n\t\t\t// but guard against overflow\n\t\t\thandledCPCountPlusOne = handledCPCount + 1;\n\t\t\tif (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tdelta += (m - n) * handledCPCountPlusOne;\n\t\t\tn = m;\n\n\t\t\tfor (j = 0; j < inputLength; ++j) {\n\t\t\t\tcurrentValue = input[j];\n\n\t\t\t\tif (currentValue < n && ++delta > maxInt) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\tif (currentValue == n) {\n\t\t\t\t\t// Represent delta as a generalized variable-length integer\n\t\t\t\t\tfor (q = delta, k = base; /* no condition */; k += base) {\n\t\t\t\t\t\tt = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\t\t\t\t\t\tif (q < t) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tqMinusT = q - t;\n\t\t\t\t\t\tbaseMinusT = base - t;\n\t\t\t\t\t\toutput.push(\n\t\t\t\t\t\t\tstringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))\n\t\t\t\t\t\t);\n\t\t\t\t\t\tq = floor(qMinusT / baseMinusT);\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(stringFromCharCode(digitToBasic(q, 0)));\n\t\t\t\t\tbias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);\n\t\t\t\t\tdelta = 0;\n\t\t\t\t\t++handledCPCount;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t++delta;\n\t\t\t++n;\n\n\t\t}\n\t\treturn output.join('');\n\t}\n\n\t/**\n\t * Converts a Punycode string representing a domain name or an email address\n\t * to Unicode. Only the Punycoded parts of the input will be converted, i.e.\n\t * it doesn't matter if you call it on a string that has already been\n\t * converted to Unicode.\n\t * @memberOf punycode\n\t * @param {String} input The Punycoded domain name or email address to\n\t * convert to Unicode.\n\t * @returns {String} The Unicode representation of the given Punycode\n\t * string.\n\t */\n\tfunction toUnicode(input) {\n\t\treturn mapDomain(input, function(string) {\n\t\t\treturn regexPunycode.test(string)\n\t\t\t\t? decode(string.slice(4).toLowerCase())\n\t\t\t\t: string;\n\t\t});\n\t}\n\n\t/**\n\t * Converts a Unicode string representing a domain name or an email address to\n\t * Punycode. Only the non-ASCII parts of the domain name will be converted,\n\t * i.e. it doesn't matter if you call it with a domain that's already in\n\t * ASCII.\n\t * @memberOf punycode\n\t * @param {String} input The domain name or email address to convert, as a\n\t * Unicode string.\n\t * @returns {String} The Punycode representation of the given domain name or\n\t * email address.\n\t */\n\tfunction toASCII(input) {\n\t\treturn mapDomain(input, function(string) {\n\t\t\treturn regexNonASCII.test(string)\n\t\t\t\t? 'xn--' + encode(string)\n\t\t\t\t: string;\n\t\t});\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\t/** Define the public API */\n\tpunycode = {\n\t\t/**\n\t\t * A string representing the current Punycode.js version number.\n\t\t * @memberOf punycode\n\t\t * @type String\n\t\t */\n\t\t'version': '1.3.2',\n\t\t/**\n\t\t * An object of methods to convert from JavaScript's internal character\n\t\t * representation (UCS-2) to Unicode code points, and back.\n\t\t * @see \n\t\t * @memberOf punycode\n\t\t * @type Object\n\t\t */\n\t\t'ucs2': {\n\t\t\t'decode': ucs2decode,\n\t\t\t'encode': ucs2encode\n\t\t},\n\t\t'decode': decode,\n\t\t'encode': encode,\n\t\t'toASCII': toASCII,\n\t\t'toUnicode': toUnicode\n\t};\n\n\t/** Expose `punycode` */\n\t// Some AMD build optimizers, like r.js, check for specific condition patterns\n\t// like the following:\n\tif (\n\t\ttypeof define == 'function' &&\n\t\ttypeof define.amd == 'object' &&\n\t\tdefine.amd\n\t) {\n\t\tdefine('punycode', function() {\n\t\t\treturn punycode;\n\t\t});\n\t} else if (freeExports && freeModule) {\n\t\tif (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+\n\t\t\tfreeModule.exports = punycode;\n\t\t} else { // in Narwhal or RingoJS v0.7.0-\n\t\t\tfor (key in punycode) {\n\t\t\t\tpunycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);\n\t\t\t}\n\t\t}\n\t} else { // in Rhino or a web browser\n\t\troot.punycode = punycode;\n\t}\n\n}(this));\n","'use strict';\n\nmodule.exports = {\n isString: function(arg) {\n return typeof(arg) === 'string';\n },\n isObject: function(arg) {\n return typeof(arg) === 'object' && arg !== null;\n },\n isNull: function(arg) {\n return arg === null;\n },\n isNullOrUndefined: function(arg) {\n return arg == null;\n }\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nmodule.exports = function(qs, sep, eq, options) {\n sep = sep || '&';\n eq = eq || '=';\n var obj = {};\n\n if (typeof qs !== 'string' || qs.length === 0) {\n return obj;\n }\n\n var regexp = /\\+/g;\n qs = qs.split(sep);\n\n var maxKeys = 1000;\n if (options && typeof options.maxKeys === 'number') {\n maxKeys = options.maxKeys;\n }\n\n var len = qs.length;\n // maxKeys <= 0 means that we should not limit keys count\n if (maxKeys > 0 && len > maxKeys) {\n len = maxKeys;\n }\n\n for (var i = 0; i < len; ++i) {\n var x = qs[i].replace(regexp, '%20'),\n idx = x.indexOf(eq),\n kstr, vstr, k, v;\n\n if (idx >= 0) {\n kstr = x.substr(0, idx);\n vstr = x.substr(idx + 1);\n } else {\n kstr = x;\n vstr = '';\n }\n\n k = decodeURIComponent(kstr);\n v = decodeURIComponent(vstr);\n\n if (!hasOwnProperty(obj, k)) {\n obj[k] = v;\n } else if (Array.isArray(obj[k])) {\n obj[k].push(v);\n } else {\n obj[k] = [obj[k], v];\n }\n }\n\n return obj;\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar stringifyPrimitive = function(v) {\n switch (typeof v) {\n case 'string':\n return v;\n\n case 'boolean':\n return v ? 'true' : 'false';\n\n case 'number':\n return isFinite(v) ? v : '';\n\n default:\n return '';\n }\n};\n\nmodule.exports = function(obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n\n if (typeof obj === 'object') {\n return Object.keys(obj).map(function(k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (Array.isArray(obj[k])) {\n return obj[k].map(function(v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).join(sep);\n\n }\n\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq +\n encodeURIComponent(stringifyPrimitive(obj));\n};\n","'use strict';\n\nexports.decode = exports.parse = require('./decode');\nexports.encode = exports.stringify = require('./encode');\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar punycode = require('punycode');\nvar util = require('./util');\n\nexports.parse = urlParse;\nexports.resolve = urlResolve;\nexports.resolveObject = urlResolveObject;\nexports.format = urlFormat;\n\nexports.Url = Url;\n\nfunction Url() {\n this.protocol = null;\n this.slashes = null;\n this.auth = null;\n this.host = null;\n this.port = null;\n this.hostname = null;\n this.hash = null;\n this.search = null;\n this.query = null;\n this.pathname = null;\n this.path = null;\n this.href = null;\n}\n\n// Reference: RFC 3986, RFC 1808, RFC 2396\n\n// define these here so at least they only have to be\n// compiled once on the first module load.\nvar protocolPattern = /^([a-z0-9.+-]+:)/i,\n portPattern = /:[0-9]*$/,\n\n // Special case for a simple path URL\n simplePathPattern = /^(\\/\\/?(?!\\/)[^\\?\\s]*)(\\?[^\\s]*)?$/,\n\n // RFC 2396: characters reserved for delimiting URLs.\n // We actually just auto-escape these.\n delims = ['<', '>', '\"', '`', ' ', '\\r', '\\n', '\\t'],\n\n // RFC 2396: characters not allowed for various reasons.\n unwise = ['{', '}', '|', '\\\\', '^', '`'].concat(delims),\n\n // Allowed by RFCs, but cause of XSS attacks. Always escape these.\n autoEscape = ['\\''].concat(unwise),\n // Characters that are never ever allowed in a hostname.\n // Note that any invalid chars are also handled, but these\n // are the ones that are *expected* to be seen, so we fast-path\n // them.\n nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),\n hostEndingChars = ['/', '?', '#'],\n hostnameMaxLen = 255,\n hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,\n hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,\n // protocols that can allow \"unsafe\" and \"unwise\" chars.\n unsafeProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that never have a hostname.\n hostlessProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that always contain a // bit.\n slashedProtocol = {\n 'http': true,\n 'https': true,\n 'ftp': true,\n 'gopher': true,\n 'file': true,\n 'http:': true,\n 'https:': true,\n 'ftp:': true,\n 'gopher:': true,\n 'file:': true\n },\n querystring = require('querystring');\n\nfunction urlParse(url, parseQueryString, slashesDenoteHost) {\n if (url && util.isObject(url) && url instanceof Url) return url;\n\n var u = new Url;\n u.parse(url, parseQueryString, slashesDenoteHost);\n return u;\n}\n\nUrl.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {\n if (!util.isString(url)) {\n throw new TypeError(\"Parameter 'url' must be a string, not \" + typeof url);\n }\n\n // Copy chrome, IE, opera backslash-handling behavior.\n // Back slashes before the query string get converted to forward slashes\n // See: https://code.google.com/p/chromium/issues/detail?id=25916\n var queryIndex = url.indexOf('?'),\n splitter =\n (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',\n uSplit = url.split(splitter),\n slashRegex = /\\\\/g;\n uSplit[0] = uSplit[0].replace(slashRegex, '/');\n url = uSplit.join(splitter);\n\n var rest = url;\n\n // trim before proceeding.\n // This is to support parse stuff like \" http://foo.com \\n\"\n rest = rest.trim();\n\n if (!slashesDenoteHost && url.split('#').length === 1) {\n // Try fast path regexp\n var simplePath = simplePathPattern.exec(rest);\n if (simplePath) {\n this.path = rest;\n this.href = rest;\n this.pathname = simplePath[1];\n if (simplePath[2]) {\n this.search = simplePath[2];\n if (parseQueryString) {\n this.query = querystring.parse(this.search.substr(1));\n } else {\n this.query = this.search.substr(1);\n }\n } else if (parseQueryString) {\n this.search = '';\n this.query = {};\n }\n return this;\n }\n }\n\n var proto = protocolPattern.exec(rest);\n if (proto) {\n proto = proto[0];\n var lowerProto = proto.toLowerCase();\n this.protocol = lowerProto;\n rest = rest.substr(proto.length);\n }\n\n // figure out if it's got a host\n // user@server is *always* interpreted as a hostname, and url\n // resolution will treat //foo/bar as host=foo,path=bar because that's\n // how the browser resolves relative URLs.\n if (slashesDenoteHost || proto || rest.match(/^\\/\\/[^@\\/]+@[^@\\/]+/)) {\n var slashes = rest.substr(0, 2) === '//';\n if (slashes && !(proto && hostlessProtocol[proto])) {\n rest = rest.substr(2);\n this.slashes = true;\n }\n }\n\n if (!hostlessProtocol[proto] &&\n (slashes || (proto && !slashedProtocol[proto]))) {\n\n // there's a hostname.\n // the first instance of /, ?, ;, or # ends the host.\n //\n // If there is an @ in the hostname, then non-host chars *are* allowed\n // to the left of the last @ sign, unless some host-ending character\n // comes *before* the @-sign.\n // URLs are obnoxious.\n //\n // ex:\n // http://a@b@c/ => user:a@b host:c\n // http://a@b?@c => user:a host:c path:/?@c\n\n // v0.12 TODO(isaacs): This is not quite how Chrome does things.\n // Review our test case against browsers more comprehensively.\n\n // find the first instance of any hostEndingChars\n var hostEnd = -1;\n for (var i = 0; i < hostEndingChars.length; i++) {\n var hec = rest.indexOf(hostEndingChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))\n hostEnd = hec;\n }\n\n // at this point, either we have an explicit point where the\n // auth portion cannot go past, or the last @ char is the decider.\n var auth, atSign;\n if (hostEnd === -1) {\n // atSign can be anywhere.\n atSign = rest.lastIndexOf('@');\n } else {\n // atSign must be in auth portion.\n // http://a@b/c@d => host:b auth:a path:/c@d\n atSign = rest.lastIndexOf('@', hostEnd);\n }\n\n // Now we have a portion which is definitely the auth.\n // Pull that off.\n if (atSign !== -1) {\n auth = rest.slice(0, atSign);\n rest = rest.slice(atSign + 1);\n this.auth = decodeURIComponent(auth);\n }\n\n // the host is the remaining to the left of the first non-host char\n hostEnd = -1;\n for (var i = 0; i < nonHostChars.length; i++) {\n var hec = rest.indexOf(nonHostChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))\n hostEnd = hec;\n }\n // if we still have not hit it, then the entire thing is a host.\n if (hostEnd === -1)\n hostEnd = rest.length;\n\n this.host = rest.slice(0, hostEnd);\n rest = rest.slice(hostEnd);\n\n // pull out port.\n this.parseHost();\n\n // we've indicated that there is a hostname,\n // so even if it's empty, it has to be present.\n this.hostname = this.hostname || '';\n\n // if hostname begins with [ and ends with ]\n // assume that it's an IPv6 address.\n var ipv6Hostname = this.hostname[0] === '[' &&\n this.hostname[this.hostname.length - 1] === ']';\n\n // validate a little.\n if (!ipv6Hostname) {\n var hostparts = this.hostname.split(/\\./);\n for (var i = 0, l = hostparts.length; i < l; i++) {\n var part = hostparts[i];\n if (!part) continue;\n if (!part.match(hostnamePartPattern)) {\n var newpart = '';\n for (var j = 0, k = part.length; j < k; j++) {\n if (part.charCodeAt(j) > 127) {\n // we replace non-ASCII char with a temporary placeholder\n // we need this to make sure size of hostname is not\n // broken by replacing non-ASCII by nothing\n newpart += 'x';\n } else {\n newpart += part[j];\n }\n }\n // we test again with ASCII char only\n if (!newpart.match(hostnamePartPattern)) {\n var validParts = hostparts.slice(0, i);\n var notHost = hostparts.slice(i + 1);\n var bit = part.match(hostnamePartStart);\n if (bit) {\n validParts.push(bit[1]);\n notHost.unshift(bit[2]);\n }\n if (notHost.length) {\n rest = '/' + notHost.join('.') + rest;\n }\n this.hostname = validParts.join('.');\n break;\n }\n }\n }\n }\n\n if (this.hostname.length > hostnameMaxLen) {\n this.hostname = '';\n } else {\n // hostnames are always lower case.\n this.hostname = this.hostname.toLowerCase();\n }\n\n if (!ipv6Hostname) {\n // IDNA Support: Returns a punycoded representation of \"domain\".\n // It only converts parts of the domain name that\n // have non-ASCII characters, i.e. it doesn't matter if\n // you call it with a domain that already is ASCII-only.\n this.hostname = punycode.toASCII(this.hostname);\n }\n\n var p = this.port ? ':' + this.port : '';\n var h = this.hostname || '';\n this.host = h + p;\n this.href += this.host;\n\n // strip [ and ] from the hostname\n // the host field still retains them, though\n if (ipv6Hostname) {\n this.hostname = this.hostname.substr(1, this.hostname.length - 2);\n if (rest[0] !== '/') {\n rest = '/' + rest;\n }\n }\n }\n\n // now rest is set to the post-host stuff.\n // chop off any delim chars.\n if (!unsafeProtocol[lowerProto]) {\n\n // First, make 100% sure that any \"autoEscape\" chars get\n // escaped, even if encodeURIComponent doesn't think they\n // need to be.\n for (var i = 0, l = autoEscape.length; i < l; i++) {\n var ae = autoEscape[i];\n if (rest.indexOf(ae) === -1)\n continue;\n var esc = encodeURIComponent(ae);\n if (esc === ae) {\n esc = escape(ae);\n }\n rest = rest.split(ae).join(esc);\n }\n }\n\n\n // chop off from the tail first.\n var hash = rest.indexOf('#');\n if (hash !== -1) {\n // got a fragment string.\n this.hash = rest.substr(hash);\n rest = rest.slice(0, hash);\n }\n var qm = rest.indexOf('?');\n if (qm !== -1) {\n this.search = rest.substr(qm);\n this.query = rest.substr(qm + 1);\n if (parseQueryString) {\n this.query = querystring.parse(this.query);\n }\n rest = rest.slice(0, qm);\n } else if (parseQueryString) {\n // no query string, but parseQueryString still requested\n this.search = '';\n this.query = {};\n }\n if (rest) this.pathname = rest;\n if (slashedProtocol[lowerProto] &&\n this.hostname && !this.pathname) {\n this.pathname = '/';\n }\n\n //to support http.request\n if (this.pathname || this.search) {\n var p = this.pathname || '';\n var s = this.search || '';\n this.path = p + s;\n }\n\n // finally, reconstruct the href based on what has been validated.\n this.href = this.format();\n return this;\n};\n\n// format a parsed object into a url string\nfunction urlFormat(obj) {\n // ensure it's an object, and not a string url.\n // If it's an obj, this is a no-op.\n // this way, you can call url_format() on strings\n // to clean up potentially wonky urls.\n if (util.isString(obj)) obj = urlParse(obj);\n if (!(obj instanceof Url)) return Url.prototype.format.call(obj);\n return obj.format();\n}\n\nUrl.prototype.format = function() {\n var auth = this.auth || '';\n if (auth) {\n auth = encodeURIComponent(auth);\n auth = auth.replace(/%3A/i, ':');\n auth += '@';\n }\n\n var protocol = this.protocol || '',\n pathname = this.pathname || '',\n hash = this.hash || '',\n host = false,\n query = '';\n\n if (this.host) {\n host = auth + this.host;\n } else if (this.hostname) {\n host = auth + (this.hostname.indexOf(':') === -1 ?\n this.hostname :\n '[' + this.hostname + ']');\n if (this.port) {\n host += ':' + this.port;\n }\n }\n\n if (this.query &&\n util.isObject(this.query) &&\n Object.keys(this.query).length) {\n query = querystring.stringify(this.query);\n }\n\n var search = this.search || (query && ('?' + query)) || '';\n\n if (protocol && protocol.substr(-1) !== ':') protocol += ':';\n\n // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.\n // unless they had them to begin with.\n if (this.slashes ||\n (!protocol || slashedProtocol[protocol]) && host !== false) {\n host = '//' + (host || '');\n if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;\n } else if (!host) {\n host = '';\n }\n\n if (hash && hash.charAt(0) !== '#') hash = '#' + hash;\n if (search && search.charAt(0) !== '?') search = '?' + search;\n\n pathname = pathname.replace(/[?#]/g, function(match) {\n return encodeURIComponent(match);\n });\n search = search.replace('#', '%23');\n\n return protocol + host + pathname + search + hash;\n};\n\nfunction urlResolve(source, relative) {\n return urlParse(source, false, true).resolve(relative);\n}\n\nUrl.prototype.resolve = function(relative) {\n return this.resolveObject(urlParse(relative, false, true)).format();\n};\n\nfunction urlResolveObject(source, relative) {\n if (!source) return relative;\n return urlParse(source, false, true).resolveObject(relative);\n}\n\nUrl.prototype.resolveObject = function(relative) {\n if (util.isString(relative)) {\n var rel = new Url();\n rel.parse(relative, false, true);\n relative = rel;\n }\n\n var result = new Url();\n var tkeys = Object.keys(this);\n for (var tk = 0; tk < tkeys.length; tk++) {\n var tkey = tkeys[tk];\n result[tkey] = this[tkey];\n }\n\n // hash is always overridden, no matter what.\n // even href=\"\" will remove it.\n result.hash = relative.hash;\n\n // if the relative url is empty, then there's nothing left to do here.\n if (relative.href === '') {\n result.href = result.format();\n return result;\n }\n\n // hrefs like //foo/bar always cut to the protocol.\n if (relative.slashes && !relative.protocol) {\n // take everything except the protocol from relative\n var rkeys = Object.keys(relative);\n for (var rk = 0; rk < rkeys.length; rk++) {\n var rkey = rkeys[rk];\n if (rkey !== 'protocol')\n result[rkey] = relative[rkey];\n }\n\n //urlParse appends trailing / to urls like http://www.example.com\n if (slashedProtocol[result.protocol] &&\n result.hostname && !result.pathname) {\n result.path = result.pathname = '/';\n }\n\n result.href = result.format();\n return result;\n }\n\n if (relative.protocol && relative.protocol !== result.protocol) {\n // if it's a known url protocol, then changing\n // the protocol does weird things\n // first, if it's not file:, then we MUST have a host,\n // and if there was a path\n // to begin with, then we MUST have a path.\n // if it is file:, then the host is dropped,\n // because that's known to be hostless.\n // anything else is assumed to be absolute.\n if (!slashedProtocol[relative.protocol]) {\n var keys = Object.keys(relative);\n for (var v = 0; v < keys.length; v++) {\n var k = keys[v];\n result[k] = relative[k];\n }\n result.href = result.format();\n return result;\n }\n\n result.protocol = relative.protocol;\n if (!relative.host && !hostlessProtocol[relative.protocol]) {\n var relPath = (relative.pathname || '').split('/');\n while (relPath.length && !(relative.host = relPath.shift()));\n if (!relative.host) relative.host = '';\n if (!relative.hostname) relative.hostname = '';\n if (relPath[0] !== '') relPath.unshift('');\n if (relPath.length < 2) relPath.unshift('');\n result.pathname = relPath.join('/');\n } else {\n result.pathname = relative.pathname;\n }\n result.search = relative.search;\n result.query = relative.query;\n result.host = relative.host || '';\n result.auth = relative.auth;\n result.hostname = relative.hostname || relative.host;\n result.port = relative.port;\n // to support http.request\n if (result.pathname || result.search) {\n var p = result.pathname || '';\n var s = result.search || '';\n result.path = p + s;\n }\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n }\n\n var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),\n isRelAbs = (\n relative.host ||\n relative.pathname && relative.pathname.charAt(0) === '/'\n ),\n mustEndAbs = (isRelAbs || isSourceAbs ||\n (result.host && relative.pathname)),\n removeAllDots = mustEndAbs,\n srcPath = result.pathname && result.pathname.split('/') || [],\n relPath = relative.pathname && relative.pathname.split('/') || [],\n psychotic = result.protocol && !slashedProtocol[result.protocol];\n\n // if the url is a non-slashed url, then relative\n // links like ../.. should be able\n // to crawl up to the hostname, as well. This is strange.\n // result.protocol has already been set by now.\n // Later on, put the first path part into the host field.\n if (psychotic) {\n result.hostname = '';\n result.port = null;\n if (result.host) {\n if (srcPath[0] === '') srcPath[0] = result.host;\n else srcPath.unshift(result.host);\n }\n result.host = '';\n if (relative.protocol) {\n relative.hostname = null;\n relative.port = null;\n if (relative.host) {\n if (relPath[0] === '') relPath[0] = relative.host;\n else relPath.unshift(relative.host);\n }\n relative.host = null;\n }\n mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');\n }\n\n if (isRelAbs) {\n // it's absolute.\n result.host = (relative.host || relative.host === '') ?\n relative.host : result.host;\n result.hostname = (relative.hostname || relative.hostname === '') ?\n relative.hostname : result.hostname;\n result.search = relative.search;\n result.query = relative.query;\n srcPath = relPath;\n // fall through to the dot-handling below.\n } else if (relPath.length) {\n // it's relative\n // throw away the existing file, and take the new path instead.\n if (!srcPath) srcPath = [];\n srcPath.pop();\n srcPath = srcPath.concat(relPath);\n result.search = relative.search;\n result.query = relative.query;\n } else if (!util.isNullOrUndefined(relative.search)) {\n // just pull out the search.\n // like href='?foo'.\n // Put this after the other two cases because it simplifies the booleans\n if (psychotic) {\n result.hostname = result.host = srcPath.shift();\n //occationaly the auth can get stuck only in host\n //this especially happens in cases like\n //url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n var authInHost = result.host && result.host.indexOf('@') > 0 ?\n result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.host = result.hostname = authInHost.shift();\n }\n }\n result.search = relative.search;\n result.query = relative.query;\n //to support http.request\n if (!util.isNull(result.pathname) || !util.isNull(result.search)) {\n result.path = (result.pathname ? result.pathname : '') +\n (result.search ? result.search : '');\n }\n result.href = result.format();\n return result;\n }\n\n if (!srcPath.length) {\n // no path at all. easy.\n // we've already handled the other stuff above.\n result.pathname = null;\n //to support http.request\n if (result.search) {\n result.path = '/' + result.search;\n } else {\n result.path = null;\n }\n result.href = result.format();\n return result;\n }\n\n // if a url ENDs in . or .., then it must get a trailing slash.\n // however, if it ends in anything else non-slashy,\n // then it must NOT get a trailing slash.\n var last = srcPath.slice(-1)[0];\n var hasTrailingSlash = (\n (result.host || relative.host || srcPath.length > 1) &&\n (last === '.' || last === '..') || last === '');\n\n // strip single dots, resolve double dots to parent dir\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = srcPath.length; i >= 0; i--) {\n last = srcPath[i];\n if (last === '.') {\n srcPath.splice(i, 1);\n } else if (last === '..') {\n srcPath.splice(i, 1);\n up++;\n } else if (up) {\n srcPath.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (!mustEndAbs && !removeAllDots) {\n for (; up--; up) {\n srcPath.unshift('..');\n }\n }\n\n if (mustEndAbs && srcPath[0] !== '' &&\n (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {\n srcPath.unshift('');\n }\n\n if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {\n srcPath.push('');\n }\n\n var isAbsolute = srcPath[0] === '' ||\n (srcPath[0] && srcPath[0].charAt(0) === '/');\n\n // put the host back\n if (psychotic) {\n result.hostname = result.host = isAbsolute ? '' :\n srcPath.length ? srcPath.shift() : '';\n //occationaly the auth can get stuck only in host\n //this especially happens in cases like\n //url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n var authInHost = result.host && result.host.indexOf('@') > 0 ?\n result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.host = result.hostname = authInHost.shift();\n }\n }\n\n mustEndAbs = mustEndAbs || (result.host && srcPath.length);\n\n if (mustEndAbs && !isAbsolute) {\n srcPath.unshift('');\n }\n\n if (!srcPath.length) {\n result.pathname = null;\n result.path = null;\n } else {\n result.pathname = srcPath.join('/');\n }\n\n //to support request.http\n if (!util.isNull(result.pathname) || !util.isNull(result.search)) {\n result.path = (result.pathname ? result.pathname : '') +\n (result.search ? result.search : '');\n }\n result.auth = relative.auth || result.auth;\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n};\n\nUrl.prototype.parseHost = function() {\n var host = this.host;\n var port = portPattern.exec(host);\n if (port) {\n port = port[0];\n if (port !== ':') {\n this.port = port.substr(1);\n }\n host = host.substr(0, host.length - port.length);\n }\n if (host) this.hostname = host;\n};\n","// @flow\n\nimport Reference from './reference/v8.json';\nimport type {StylePropertySpecification} from './style-spec';\nimport type {\n StyleSpecification,\n SourceSpecification,\n LayerSpecification,\n PropertyValueSpecification,\n DataDrivenPropertyValueSpecification\n} from './types';\n\nfunction getPropertyReference(propertyName): StylePropertySpecification {\n for (let i = 0; i < Reference.layout.length; i++) {\n for (const key in Reference[Reference.layout[i]]) {\n if (key === propertyName) return (Reference[Reference.layout[i]][key]: any);\n }\n }\n for (let i = 0; i < Reference.paint.length; i++) {\n for (const key in Reference[Reference.paint[i]]) {\n if (key === propertyName) return (Reference[Reference.paint[i]][key]: any);\n }\n }\n\n return (null: any);\n}\n\nexport function eachSource(style: StyleSpecification, callback: (_: SourceSpecification) => void) {\n for (const k in style.sources) {\n callback(style.sources[k]);\n }\n}\n\nexport function eachLayer(style: StyleSpecification, callback: (_: LayerSpecification) => void) {\n for (const layer of style.layers) {\n callback(layer);\n }\n}\n\ntype PropertyCallback = ({\n path: [string, 'paint' | 'layout', string], // [layerid, paint/layout, property key]\n key: string,\n value: PropertyValueSpecification | DataDrivenPropertyValueSpecification,\n reference: StylePropertySpecification,\n set: (PropertyValueSpecification | DataDrivenPropertyValueSpecification) => void\n}) => void;\n\nexport function eachProperty(\n style: StyleSpecification,\n options: {paint?: boolean, layout?: boolean},\n callback: PropertyCallback\n) {\n function inner(layer, propertyType: 'paint' | 'layout') {\n const properties = (layer[propertyType]: any);\n if (!properties) return;\n Object.keys(properties).forEach((key) => {\n callback({\n path: [layer.id, propertyType, key],\n key,\n value: properties[key],\n reference: getPropertyReference(key),\n set(x) {\n properties[key] = x;\n }\n });\n });\n }\n\n eachLayer(style, (layer) => {\n if (options.paint) {\n inner(layer, 'paint');\n }\n if (options.layout) {\n inner(layer, 'layout');\n }\n });\n}\n","\nimport URL from 'url';\nimport {eachSource, eachLayer, eachProperty} from '../visit';\n\nfunction eachLayout(layer, callback) {\n for (const k in layer) {\n if (k.indexOf('layout') === 0) {\n callback(layer[k], k);\n }\n }\n}\n\nfunction eachPaint(layer, callback) {\n for (const k in layer) {\n if (k.indexOf('paint') === 0) {\n callback(layer[k], k);\n }\n }\n}\n\nfunction resolveConstant(style, value) {\n if (typeof value === 'string' && value[0] === '@') {\n return resolveConstant(style, style.constants[value]);\n } else {\n return value;\n }\n}\n\nfunction isFunction(value) {\n return Array.isArray(value.stops);\n}\n\nfunction renameProperty(obj, from, to) {\n obj[to] = obj[from]; delete obj[from];\n}\n\nexport default function(style) {\n style.version = 8;\n\n // Rename properties, reverse coordinates in source and layers\n eachSource(style, (source) => {\n if (source.type === 'video' && source.url !== undefined) {\n renameProperty(source, 'url', 'urls');\n }\n if (source.type === 'video') {\n source.coordinates.forEach((coord) => {\n return coord.reverse();\n });\n }\n });\n\n eachLayer(style, (layer) => {\n eachLayout(layer, (layout) => {\n if (layout['symbol-min-distance'] !== undefined) {\n renameProperty(layout, 'symbol-min-distance', 'symbol-spacing');\n }\n });\n\n eachPaint(layer, (paint) => {\n if (paint['background-image'] !== undefined) {\n renameProperty(paint, 'background-image', 'background-pattern');\n }\n if (paint['line-image'] !== undefined) {\n renameProperty(paint, 'line-image', 'line-pattern');\n }\n if (paint['fill-image'] !== undefined) {\n renameProperty(paint, 'fill-image', 'fill-pattern');\n }\n });\n });\n\n // Inline Constants\n eachProperty(style, {paint: true, layout: true}, (property) => {\n const value = resolveConstant(style, property.value);\n\n if (isFunction(value)) {\n value.stops.forEach((stop) => {\n stop[1] = resolveConstant(style, stop[1]);\n });\n }\n\n property.set(value);\n });\n delete style.constants;\n\n eachLayer(style, (layer) => {\n // get rid of text-max-size, icon-max-size\n // turn text-size, icon-size into layout properties\n // https://github.com/mapbox/mapbox-gl-style-spec/issues/255\n\n eachLayout(layer, (layout) => {\n delete layout['text-max-size'];\n delete layout['icon-max-size'];\n });\n\n eachPaint(layer, (paint) => {\n if (paint['text-size']) {\n if (!layer.layout) layer.layout = {};\n layer.layout['text-size'] = paint['text-size'];\n delete paint['text-size'];\n }\n\n if (paint['icon-size']) {\n if (!layer.layout) layer.layout = {};\n layer.layout['icon-size'] = paint['icon-size'];\n delete paint['icon-size'];\n }\n });\n });\n\n function migrateFontstackURL(input) {\n const inputParsed = URL.parse(input);\n const inputPathnameParts = inputParsed.pathname.split('/');\n\n if (inputParsed.protocol !== 'mapbox:') {\n return input;\n\n } else if (inputParsed.hostname === 'fontstack') {\n assert(decodeURI(inputParsed.pathname) === '/{fontstack}/{range}.pbf');\n return 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf';\n\n } else if (inputParsed.hostname === 'fonts') {\n assert(inputPathnameParts[1] === 'v1');\n assert(decodeURI(inputPathnameParts[3]) === '{fontstack}');\n assert(decodeURI(inputPathnameParts[4]) === '{range}.pbf');\n return `mapbox://fonts/${inputPathnameParts[2]}/{fontstack}/{range}.pbf`;\n\n } else {\n assert(false);\n }\n\n function assert(predicate) {\n if (!predicate) {\n throw new Error(`Invalid font url: \"${input}\"`);\n }\n }\n }\n\n if (style.glyphs) {\n style.glyphs = migrateFontstackURL(style.glyphs);\n }\n\n function migrateFontStack(font) {\n function splitAndTrim(string) {\n return string.split(',').map((s) => {\n return s.trim();\n });\n }\n\n if (Array.isArray(font)) {\n // Assume it's a previously migrated font-array.\n return font;\n\n } else if (typeof font === 'string') {\n return splitAndTrim(font);\n\n } else if (typeof font === 'object') {\n font.stops.forEach((stop) => {\n stop[1] = splitAndTrim(stop[1]);\n });\n return font;\n\n } else {\n throw new Error(\"unexpected font value\");\n }\n }\n\n eachLayer(style, (layer) => {\n eachLayout(layer, (layout) => {\n if (layout['text-font']) {\n layout['text-font'] = migrateFontStack(layout['text-font']);\n }\n });\n });\n\n // Reverse order of symbol layers. This is an imperfect migration.\n //\n // The order of a symbol layer in the layers list affects two things:\n // - how it is drawn relative to other layers (like oneway arrows below bridges)\n // - the placement priority compared to other layers\n //\n // It's impossible to reverse the placement priority without breaking the draw order\n // in some cases. This migration only reverses the order of symbol layers that\n // are above all other types of layers.\n //\n // Symbol layers that are at the top of the map preserve their priority.\n // Symbol layers that are below another type (line, fill) of layer preserve their draw order.\n\n let firstSymbolLayer = 0;\n for (let i = style.layers.length - 1; i >= 0; i--) {\n const layer = style.layers[i];\n if (layer.type !== 'symbol') {\n firstSymbolLayer = i + 1;\n break;\n }\n }\n\n const symbolLayers = style.layers.splice(firstSymbolLayer);\n symbolLayers.reverse();\n style.layers = style.layers.concat(symbolLayers);\n\n return style;\n}\n","// @flow\n\nexport default function (output: any, ...inputs: Array) {\n for (const input of inputs) {\n for (const k in input) {\n output[k] = input[k];\n }\n }\n return output;\n}\n","// @flow\n\nclass ParsingError extends Error {\n key: string;\n message: string;\n constructor(key: string, message: string) {\n super(message);\n this.message = message;\n this.key = key;\n }\n}\n\nexport default ParsingError;\n","// @flow\n\nimport type {Expression} from './expression';\n\n/**\n * Tracks `let` bindings during expression parsing.\n * @private\n */\nclass Scope {\n parent: ?Scope;\n bindings: {[_: string]: Expression};\n constructor(parent?: Scope, bindings: Array<[string, Expression]> = []) {\n this.parent = parent;\n this.bindings = {};\n for (const [name, expression] of bindings) {\n this.bindings[name] = expression;\n }\n }\n\n concat(bindings: Array<[string, Expression]>) {\n return new Scope(this, bindings);\n }\n\n get(name: string): Expression {\n if (this.bindings[name]) { return this.bindings[name]; }\n if (this.parent) { return this.parent.get(name); }\n throw new Error(`${name} not found in scope.`);\n }\n\n has(name: string): boolean {\n if (this.bindings[name]) return true;\n return this.parent ? this.parent.has(name) : false;\n }\n}\n\nexport default Scope;\n","// @flow\n\nexport type NullTypeT = { kind: 'null' };\nexport type NumberTypeT = { kind: 'number' };\nexport type StringTypeT = { kind: 'string' };\nexport type BooleanTypeT = { kind: 'boolean' };\nexport type ColorTypeT = { kind: 'color' };\nexport type ObjectTypeT = { kind: 'object' };\nexport type ValueTypeT = { kind: 'value' };\nexport type ErrorTypeT = { kind: 'error' };\nexport type CollatorTypeT = { kind: 'collator' };\nexport type FormattedTypeT = { kind: 'formatted' };\nexport type ResolvedImageTypeT = { kind: 'resolvedImage' };\n\nexport type EvaluationKind = 'constant' | 'source' | 'camera' | 'composite';\n\nexport type Type =\n NullTypeT |\n NumberTypeT |\n StringTypeT |\n BooleanTypeT |\n ColorTypeT |\n ObjectTypeT |\n ValueTypeT |\n ArrayType | // eslint-disable-line no-use-before-define\n ErrorTypeT |\n CollatorTypeT |\n FormattedTypeT |\n ResolvedImageTypeT\n\nexport type ArrayType = {\n kind: 'array',\n itemType: Type,\n N: ?number\n}\n\nexport type NativeType = 'number' | 'string' | 'boolean' | 'null' | 'array' | 'object'\n\nexport const NullType = {kind: 'null'};\nexport const NumberType = {kind: 'number'};\nexport const StringType = {kind: 'string'};\nexport const BooleanType = {kind: 'boolean'};\nexport const ColorType = {kind: 'color'};\nexport const ObjectType = {kind: 'object'};\nexport const ValueType = {kind: 'value'};\nexport const ErrorType = {kind: 'error'};\nexport const CollatorType = {kind: 'collator'};\nexport const FormattedType = {kind: 'formatted'};\nexport const ResolvedImageType = {kind: 'resolvedImage'};\n\nexport function array(itemType: Type, N: ?number): ArrayType {\n return {\n kind: 'array',\n itemType,\n N\n };\n}\n\nexport function toString(type: Type): string {\n if (type.kind === 'array') {\n const itemType = toString(type.itemType);\n return typeof type.N === 'number' ?\n `array<${itemType}, ${type.N}>` :\n type.itemType.kind === 'value' ? 'array' : `array<${itemType}>`;\n } else {\n return type.kind;\n }\n}\n\nconst valueMemberTypes = [\n NullType,\n NumberType,\n StringType,\n BooleanType,\n ColorType,\n FormattedType,\n ObjectType,\n array(ValueType),\n ResolvedImageType\n];\n\n/**\n * Returns null if `t` is a subtype of `expected`; otherwise returns an\n * error message.\n * @private\n */\nexport function checkSubtype(expected: Type, t: Type): ?string {\n if (t.kind === 'error') {\n // Error is a subtype of every type\n return null;\n } else if (expected.kind === 'array') {\n if (t.kind === 'array' &&\n ((t.N === 0 && t.itemType.kind === 'value') || !checkSubtype(expected.itemType, t.itemType)) &&\n (typeof expected.N !== 'number' || expected.N === t.N)) {\n return null;\n }\n } else if (expected.kind === t.kind) {\n return null;\n } else if (expected.kind === 'value') {\n for (const memberType of valueMemberTypes) {\n if (!checkSubtype(memberType, t)) {\n return null;\n }\n }\n }\n\n return `Expected ${toString(expected)} but found ${toString(t)} instead.`;\n}\n\nexport function isValidType(provided: Type, allowedTypes: Array): boolean {\n return allowedTypes.some(t => t.kind === provided.kind);\n}\n\nexport function isValidNativeType(provided: any, allowedTypes: Array): boolean {\n return allowedTypes.some(t => {\n if (t === 'null') {\n return provided === null;\n } else if (t === 'array') {\n return Array.isArray(provided);\n } else if (t === 'object') {\n return provided && !Array.isArray(provided) && typeof provided === 'object';\n } else {\n return t === typeof provided;\n }\n });\n}\n","// (c) Dean McNamee , 2012.\n//\n// https://github.com/deanm/css-color-parser-js\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n\n// http://www.w3.org/TR/css3-color/\nvar kCSSColorTable = {\n \"transparent\": [0,0,0,0], \"aliceblue\": [240,248,255,1],\n \"antiquewhite\": [250,235,215,1], \"aqua\": [0,255,255,1],\n \"aquamarine\": [127,255,212,1], \"azure\": [240,255,255,1],\n \"beige\": [245,245,220,1], \"bisque\": [255,228,196,1],\n \"black\": [0,0,0,1], \"blanchedalmond\": [255,235,205,1],\n \"blue\": [0,0,255,1], \"blueviolet\": [138,43,226,1],\n \"brown\": [165,42,42,1], \"burlywood\": [222,184,135,1],\n \"cadetblue\": [95,158,160,1], \"chartreuse\": [127,255,0,1],\n \"chocolate\": [210,105,30,1], \"coral\": [255,127,80,1],\n \"cornflowerblue\": [100,149,237,1], \"cornsilk\": [255,248,220,1],\n \"crimson\": [220,20,60,1], \"cyan\": [0,255,255,1],\n \"darkblue\": [0,0,139,1], \"darkcyan\": [0,139,139,1],\n \"darkgoldenrod\": [184,134,11,1], \"darkgray\": [169,169,169,1],\n \"darkgreen\": [0,100,0,1], \"darkgrey\": [169,169,169,1],\n \"darkkhaki\": [189,183,107,1], \"darkmagenta\": [139,0,139,1],\n \"darkolivegreen\": [85,107,47,1], \"darkorange\": [255,140,0,1],\n \"darkorchid\": [153,50,204,1], \"darkred\": [139,0,0,1],\n \"darksalmon\": [233,150,122,1], \"darkseagreen\": [143,188,143,1],\n \"darkslateblue\": [72,61,139,1], \"darkslategray\": [47,79,79,1],\n \"darkslategrey\": [47,79,79,1], \"darkturquoise\": [0,206,209,1],\n \"darkviolet\": [148,0,211,1], \"deeppink\": [255,20,147,1],\n \"deepskyblue\": [0,191,255,1], \"dimgray\": [105,105,105,1],\n \"dimgrey\": [105,105,105,1], \"dodgerblue\": [30,144,255,1],\n \"firebrick\": [178,34,34,1], \"floralwhite\": [255,250,240,1],\n \"forestgreen\": [34,139,34,1], \"fuchsia\": [255,0,255,1],\n \"gainsboro\": [220,220,220,1], \"ghostwhite\": [248,248,255,1],\n \"gold\": [255,215,0,1], \"goldenrod\": [218,165,32,1],\n \"gray\": [128,128,128,1], \"green\": [0,128,0,1],\n \"greenyellow\": [173,255,47,1], \"grey\": [128,128,128,1],\n \"honeydew\": [240,255,240,1], \"hotpink\": [255,105,180,1],\n \"indianred\": [205,92,92,1], \"indigo\": [75,0,130,1],\n \"ivory\": [255,255,240,1], \"khaki\": [240,230,140,1],\n \"lavender\": [230,230,250,1], \"lavenderblush\": [255,240,245,1],\n \"lawngreen\": [124,252,0,1], \"lemonchiffon\": [255,250,205,1],\n \"lightblue\": [173,216,230,1], \"lightcoral\": [240,128,128,1],\n \"lightcyan\": [224,255,255,1], \"lightgoldenrodyellow\": [250,250,210,1],\n \"lightgray\": [211,211,211,1], \"lightgreen\": [144,238,144,1],\n \"lightgrey\": [211,211,211,1], \"lightpink\": [255,182,193,1],\n \"lightsalmon\": [255,160,122,1], \"lightseagreen\": [32,178,170,1],\n \"lightskyblue\": [135,206,250,1], \"lightslategray\": [119,136,153,1],\n \"lightslategrey\": [119,136,153,1], \"lightsteelblue\": [176,196,222,1],\n \"lightyellow\": [255,255,224,1], \"lime\": [0,255,0,1],\n \"limegreen\": [50,205,50,1], \"linen\": [250,240,230,1],\n \"magenta\": [255,0,255,1], \"maroon\": [128,0,0,1],\n \"mediumaquamarine\": [102,205,170,1], \"mediumblue\": [0,0,205,1],\n \"mediumorchid\": [186,85,211,1], \"mediumpurple\": [147,112,219,1],\n \"mediumseagreen\": [60,179,113,1], \"mediumslateblue\": [123,104,238,1],\n \"mediumspringgreen\": [0,250,154,1], \"mediumturquoise\": [72,209,204,1],\n \"mediumvioletred\": [199,21,133,1], \"midnightblue\": [25,25,112,1],\n \"mintcream\": [245,255,250,1], \"mistyrose\": [255,228,225,1],\n \"moccasin\": [255,228,181,1], \"navajowhite\": [255,222,173,1],\n \"navy\": [0,0,128,1], \"oldlace\": [253,245,230,1],\n \"olive\": [128,128,0,1], \"olivedrab\": [107,142,35,1],\n \"orange\": [255,165,0,1], \"orangered\": [255,69,0,1],\n \"orchid\": [218,112,214,1], \"palegoldenrod\": [238,232,170,1],\n \"palegreen\": [152,251,152,1], \"paleturquoise\": [175,238,238,1],\n \"palevioletred\": [219,112,147,1], \"papayawhip\": [255,239,213,1],\n \"peachpuff\": [255,218,185,1], \"peru\": [205,133,63,1],\n \"pink\": [255,192,203,1], \"plum\": [221,160,221,1],\n \"powderblue\": [176,224,230,1], \"purple\": [128,0,128,1],\n \"rebeccapurple\": [102,51,153,1],\n \"red\": [255,0,0,1], \"rosybrown\": [188,143,143,1],\n \"royalblue\": [65,105,225,1], \"saddlebrown\": [139,69,19,1],\n \"salmon\": [250,128,114,1], \"sandybrown\": [244,164,96,1],\n \"seagreen\": [46,139,87,1], \"seashell\": [255,245,238,1],\n \"sienna\": [160,82,45,1], \"silver\": [192,192,192,1],\n \"skyblue\": [135,206,235,1], \"slateblue\": [106,90,205,1],\n \"slategray\": [112,128,144,1], \"slategrey\": [112,128,144,1],\n \"snow\": [255,250,250,1], \"springgreen\": [0,255,127,1],\n \"steelblue\": [70,130,180,1], \"tan\": [210,180,140,1],\n \"teal\": [0,128,128,1], \"thistle\": [216,191,216,1],\n \"tomato\": [255,99,71,1], \"turquoise\": [64,224,208,1],\n \"violet\": [238,130,238,1], \"wheat\": [245,222,179,1],\n \"white\": [255,255,255,1], \"whitesmoke\": [245,245,245,1],\n \"yellow\": [255,255,0,1], \"yellowgreen\": [154,205,50,1]}\n\nfunction clamp_css_byte(i) { // Clamp to integer 0 .. 255.\n i = Math.round(i); // Seems to be what Chrome does (vs truncation).\n return i < 0 ? 0 : i > 255 ? 255 : i;\n}\n\nfunction clamp_css_float(f) { // Clamp to float 0.0 .. 1.0.\n return f < 0 ? 0 : f > 1 ? 1 : f;\n}\n\nfunction parse_css_int(str) { // int or percentage.\n if (str[str.length - 1] === '%')\n return clamp_css_byte(parseFloat(str) / 100 * 255);\n return clamp_css_byte(parseInt(str));\n}\n\nfunction parse_css_float(str) { // float or percentage.\n if (str[str.length - 1] === '%')\n return clamp_css_float(parseFloat(str) / 100);\n return clamp_css_float(parseFloat(str));\n}\n\nfunction css_hue_to_rgb(m1, m2, h) {\n if (h < 0) h += 1;\n else if (h > 1) h -= 1;\n\n if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;\n if (h * 2 < 1) return m2;\n if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6;\n return m1;\n}\n\nfunction parseCSSColor(css_str) {\n // Remove all whitespace, not compliant, but should just be more accepting.\n var str = css_str.replace(/ /g, '').toLowerCase();\n\n // Color keywords (and transparent) lookup.\n if (str in kCSSColorTable) return kCSSColorTable[str].slice(); // dup.\n\n // #abc and #abc123 syntax.\n if (str[0] === '#') {\n if (str.length === 4) {\n var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.\n if (!(iv >= 0 && iv <= 0xfff)) return null; // Covers NaN.\n return [((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),\n (iv & 0xf0) | ((iv & 0xf0) >> 4),\n (iv & 0xf) | ((iv & 0xf) << 4),\n 1];\n } else if (str.length === 7) {\n var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.\n if (!(iv >= 0 && iv <= 0xffffff)) return null; // Covers NaN.\n return [(iv & 0xff0000) >> 16,\n (iv & 0xff00) >> 8,\n iv & 0xff,\n 1];\n }\n\n return null;\n }\n\n var op = str.indexOf('('), ep = str.indexOf(')');\n if (op !== -1 && ep + 1 === str.length) {\n var fname = str.substr(0, op);\n var params = str.substr(op+1, ep-(op+1)).split(',');\n var alpha = 1; // To allow case fallthrough.\n switch (fname) {\n case 'rgba':\n if (params.length !== 4) return null;\n alpha = parse_css_float(params.pop());\n // Fall through.\n case 'rgb':\n if (params.length !== 3) return null;\n return [parse_css_int(params[0]),\n parse_css_int(params[1]),\n parse_css_int(params[2]),\n alpha];\n case 'hsla':\n if (params.length !== 4) return null;\n alpha = parse_css_float(params.pop());\n // Fall through.\n case 'hsl':\n if (params.length !== 3) return null;\n var h = (((parseFloat(params[0]) % 360) + 360) % 360) / 360; // 0 .. 1\n // NOTE(deanm): According to the CSS spec s/l should only be\n // percentages, but we don't bother and let float or percentage.\n var s = parse_css_float(params[1]);\n var l = parse_css_float(params[2]);\n var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;\n var m1 = l * 2 - m2;\n return [clamp_css_byte(css_hue_to_rgb(m1, m2, h+1/3) * 255),\n clamp_css_byte(css_hue_to_rgb(m1, m2, h) * 255),\n clamp_css_byte(css_hue_to_rgb(m1, m2, h-1/3) * 255),\n alpha];\n default:\n return null;\n }\n }\n\n return null;\n}\n\ntry { exports.parseCSSColor = parseCSSColor } catch(e) { }\n","// @flow\n\nimport {parseCSSColor} from 'csscolorparser';\n\n/**\n * An RGBA color value. Create instances from color strings using the static\n * method `Color.parse`. The constructor accepts RGB channel values in the range\n * `[0, 1]`, premultiplied by A.\n *\n * @param {number} r The red channel.\n * @param {number} g The green channel.\n * @param {number} b The blue channel.\n * @param {number} a The alpha channel.\n * @private\n */\nclass Color {\n r: number;\n g: number;\n b: number;\n a: number;\n\n constructor(r: number, g: number, b: number, a: number = 1) {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n }\n\n static black: Color;\n static white: Color;\n static transparent: Color;\n static red: Color;\n\n /**\n * Parses valid CSS color strings and returns a `Color` instance.\n * @returns A `Color` instance, or `undefined` if the input is not a valid color string.\n */\n static parse(input?: string | Color | null): Color | void {\n if (!input) {\n return undefined;\n }\n\n if (input instanceof Color) {\n return input;\n }\n\n if (typeof input !== 'string') {\n return undefined;\n }\n\n const rgba = parseCSSColor(input);\n if (!rgba) {\n return undefined;\n }\n\n return new Color(\n rgba[0] / 255 * rgba[3],\n rgba[1] / 255 * rgba[3],\n rgba[2] / 255 * rgba[3],\n rgba[3]\n );\n }\n\n /**\n * Returns an RGBA string representing the color value.\n *\n * @returns An RGBA string.\n * @example\n * var purple = new Color.parse('purple');\n * purple.toString; // = \"rgba(128,0,128,1)\"\n * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)');\n * translucentGreen.toString(); // = \"rgba(26,207,26,0.73)\"\n */\n toString(): string {\n const [r, g, b, a] = this.toArray();\n return `rgba(${Math.round(r)},${Math.round(g)},${Math.round(b)},${a})`;\n }\n\n toArray(): [number, number, number, number] {\n const {r, g, b, a} = this;\n return a === 0 ? [0, 0, 0, 0] : [\n r * 255 / a,\n g * 255 / a,\n b * 255 / a,\n a\n ];\n }\n}\n\nColor.black = new Color(0, 0, 0, 1);\nColor.white = new Color(1, 1, 1, 1);\nColor.transparent = new Color(0, 0, 0, 0);\nColor.red = new Color(1, 0, 0, 1);\n\nexport default Color;\n","// @flow\n\n// Flow type declarations for Intl cribbed from\n// https://github.com/facebook/flow/issues/1270\n\ndeclare var Intl: {\n Collator: Class\n};\n\ndeclare class Intl$Collator {\n constructor (\n locales?: string | string[],\n options?: CollatorOptions\n ): Intl$Collator;\n\n static (\n locales?: string | string[],\n options?: CollatorOptions\n ): Intl$Collator;\n\n compare (a: string, b: string): number;\n\n resolvedOptions(): any;\n}\n\ntype CollatorOptions = {\n localeMatcher?: 'lookup' | 'best fit',\n usage?: 'sort' | 'search',\n sensitivity?: 'base' | 'accent' | 'case' | 'variant',\n ignorePunctuation?: boolean,\n numeric?: boolean,\n caseFirst?: 'upper' | 'lower' | 'false'\n}\n\nexport default class Collator {\n locale: string | null;\n sensitivity: 'base' | 'accent' | 'case' | 'variant';\n collator: Intl$Collator;\n\n constructor(caseSensitive: boolean, diacriticSensitive: boolean, locale: string | null) {\n if (caseSensitive)\n this.sensitivity = diacriticSensitive ? 'variant' : 'case';\n else\n this.sensitivity = diacriticSensitive ? 'accent' : 'base';\n\n this.locale = locale;\n this.collator = new Intl.Collator(this.locale ? this.locale : [],\n {sensitivity: this.sensitivity, usage: 'search'});\n }\n\n compare(lhs: string, rhs: string): number {\n return this.collator.compare(lhs, rhs);\n }\n\n resolvedLocale(): string {\n // We create a Collator without \"usage: search\" because we don't want\n // the search options encoded in our result (e.g. \"en-u-co-search\")\n return new Intl.Collator(this.locale ? this.locale : [])\n .resolvedOptions().locale;\n }\n}\n","// @flow\nimport type Color from '../../util/color';\nimport type ResolvedImage from '../types/resolved_image';\n\nexport class FormattedSection {\n text: string;\n image: ResolvedImage | null;\n scale: number | null;\n fontStack: string | null;\n textColor: Color | null;\n\n constructor(text: string, image: ResolvedImage | null, scale: number | null, fontStack: string | null, textColor: Color | null) {\n this.text = text;\n this.image = image;\n this.scale = scale;\n this.fontStack = fontStack;\n this.textColor = textColor;\n }\n}\n\nexport default class Formatted {\n sections: Array;\n\n constructor(sections: Array) {\n this.sections = sections;\n }\n\n static fromString(unformatted: string): Formatted {\n return new Formatted([new FormattedSection(unformatted, null, null, null, null)]);\n }\n\n isEmpty(): boolean {\n if (this.sections.length === 0) return true;\n return !this.sections.some(section => section.text.length !== 0 ||\n (section.image && section.image.name.length !== 0));\n }\n\n static factory(text: Formatted | string): Formatted {\n if (text instanceof Formatted) {\n return text;\n } else {\n return Formatted.fromString(text);\n }\n }\n\n toString(): string {\n if (this.sections.length === 0) return '';\n return this.sections.map(section => section.text).join('');\n }\n\n serialize(): Array {\n const serialized: Array = [\"format\"];\n for (const section of this.sections) {\n if (section.image) {\n serialized.push([\"image\", section.image.name]);\n continue;\n }\n serialized.push(section.text);\n const options: { [key: string]: mixed } = {};\n if (section.fontStack) {\n options[\"text-font\"] = [\"literal\", section.fontStack.split(',')];\n }\n if (section.scale) {\n options[\"font-scale\"] = section.scale;\n }\n if (section.textColor) {\n options[\"text-color\"] = ([\"rgba\"]: Array).concat(section.textColor.toArray());\n }\n serialized.push(options);\n }\n return serialized;\n }\n}\n","// @flow\n\nexport type ResolvedImageOptions = {\n name: string,\n available: boolean\n};\n\nexport default class ResolvedImage {\n name: string;\n available: boolean;\n\n constructor(options: ResolvedImageOptions) {\n this.name = options.name;\n this.available = options.available;\n }\n\n toString(): string {\n return this.name;\n }\n\n static fromString(name: string): ResolvedImage | null {\n if (!name) return null; // treat empty values as no image\n return new ResolvedImage({name, available: false});\n }\n\n serialize(): Array {\n return [\"image\", this.name];\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport Color from '../util/color';\nimport Collator from './types/collator';\nimport Formatted from './types/formatted';\nimport ResolvedImage from './types/resolved_image';\nimport {NullType, NumberType, StringType, BooleanType, ColorType, ObjectType, ValueType, CollatorType, FormattedType, ResolvedImageType, array} from './types';\n\nimport type {Type} from './types';\n\nexport function validateRGBA(r: mixed, g: mixed, b: mixed, a?: mixed): string | null {\n if (!(\n typeof r === 'number' && r >= 0 && r <= 255 &&\n typeof g === 'number' && g >= 0 && g <= 255 &&\n typeof b === 'number' && b >= 0 && b <= 255\n )) {\n const value = typeof a === 'number' ? [r, g, b, a] : [r, g, b];\n return `Invalid rgba value [${value.join(', ')}]: 'r', 'g', and 'b' must be between 0 and 255.`;\n }\n\n if (!(\n typeof a === 'undefined' || (typeof a === 'number' && a >= 0 && a <= 1)\n )) {\n return `Invalid rgba value [${[r, g, b, a].join(', ')}]: 'a' must be between 0 and 1.`;\n }\n\n return null;\n}\n\nexport type Value = null | string | boolean | number | Color | Collator | Formatted | ResolvedImage | $ReadOnlyArray | { +[string]: Value }\n\nexport function isValue(mixed: mixed): boolean {\n if (mixed === null) {\n return true;\n } else if (typeof mixed === 'string') {\n return true;\n } else if (typeof mixed === 'boolean') {\n return true;\n } else if (typeof mixed === 'number') {\n return true;\n } else if (mixed instanceof Color) {\n return true;\n } else if (mixed instanceof Collator) {\n return true;\n } else if (mixed instanceof Formatted) {\n return true;\n } else if (mixed instanceof ResolvedImage) {\n return true;\n } else if (Array.isArray(mixed)) {\n for (const item of mixed) {\n if (!isValue(item)) {\n return false;\n }\n }\n return true;\n } else if (typeof mixed === 'object') {\n for (const key in mixed) {\n if (!isValue(mixed[key])) {\n return false;\n }\n }\n return true;\n } else {\n return false;\n }\n}\n\nexport function typeOf(value: Value): Type {\n if (value === null) {\n return NullType;\n } else if (typeof value === 'string') {\n return StringType;\n } else if (typeof value === 'boolean') {\n return BooleanType;\n } else if (typeof value === 'number') {\n return NumberType;\n } else if (value instanceof Color) {\n return ColorType;\n } else if (value instanceof Collator) {\n return CollatorType;\n } else if (value instanceof Formatted) {\n return FormattedType;\n } else if (value instanceof ResolvedImage) {\n return ResolvedImageType;\n } else if (Array.isArray(value)) {\n const length = value.length;\n let itemType: Type | typeof undefined;\n\n for (const item of value) {\n const t = typeOf(item);\n if (!itemType) {\n itemType = t;\n } else if (itemType === t) {\n continue;\n } else {\n itemType = ValueType;\n break;\n }\n }\n\n return array(itemType || ValueType, length);\n } else {\n assert(typeof value === 'object');\n return ObjectType;\n }\n}\n\nexport function toString(value: Value) {\n const type = typeof value;\n if (value === null) {\n return '';\n } else if (type === 'string' || type === 'number' || type === 'boolean') {\n return String(value);\n } else if (value instanceof Color || value instanceof Formatted || value instanceof ResolvedImage) {\n return value.toString();\n } else {\n return JSON.stringify(value);\n }\n}\n\nexport {Color, Collator};\n","// @flow\n\nimport assert from 'assert';\nimport {isValue, typeOf, Color} from '../values';\nimport Formatted from '../types/formatted';\n\nimport type {Type} from '../types';\nimport type {Value} from '../values';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\n\nclass Literal implements Expression {\n type: Type;\n value: Value;\n\n constructor(type: Type, value: Value) {\n this.type = type;\n this.value = value;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 2)\n return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`);\n\n if (!isValue(args[1]))\n return context.error(`invalid value`);\n\n const value = (args[1]: any);\n let type = typeOf(value);\n\n // special case: infer the item type if possible for zero-length arrays\n const expected = context.expectedType;\n if (\n type.kind === 'array' &&\n type.N === 0 &&\n expected &&\n expected.kind === 'array' &&\n (typeof expected.N !== 'number' || expected.N === 0)\n ) {\n type = expected;\n }\n\n return new Literal(type, value);\n }\n\n evaluate() {\n return this.value;\n }\n\n eachChild() {}\n\n outputDefined() {\n return true;\n }\n\n serialize(): Array {\n if (this.type.kind === 'array' || this.type.kind === 'object') {\n return [\"literal\", this.value];\n } else if (this.value instanceof Color) {\n // Constant-folding can generate Literal expressions that you\n // couldn't actually generate with a \"literal\" expression,\n // so we have to implement an equivalent serialization here\n return [\"rgba\"].concat(this.value.toArray());\n } else if (this.value instanceof Formatted) {\n // Same as Color\n return this.value.serialize();\n } else {\n assert(this.value === null ||\n typeof this.value === 'string' ||\n typeof this.value === 'number' ||\n typeof this.value === 'boolean');\n return (this.value: any);\n }\n }\n}\n\nexport default Literal;\n","// @flow\n\nclass RuntimeError {\n name: string;\n message: string;\n\n constructor(message: string) {\n this.name = 'ExpressionEvaluationError';\n this.message = message;\n }\n\n toJSON() {\n return this.message;\n }\n}\n\nexport default RuntimeError;\n","// @flow\n\nimport assert from 'assert';\n\nimport {\n ObjectType,\n ValueType,\n StringType,\n NumberType,\n BooleanType,\n checkSubtype,\n toString,\n array\n} from '../types';\nimport RuntimeError from '../runtime_error';\nimport {typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nconst types = {\n string: StringType,\n number: NumberType,\n boolean: BooleanType,\n object: ObjectType\n};\n\nclass Assertion implements Expression {\n type: Type;\n args: Array;\n\n constructor(type: Type, args: Array) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length < 2)\n return context.error(`Expected at least one argument.`);\n\n let i = 1;\n let type;\n\n const name: string = (args[0]: any);\n if (name === 'array') {\n let itemType;\n if (args.length > 2) {\n const type = args[1];\n if (typeof type !== 'string' || !(type in types) || type === 'object')\n return context.error('The item type argument of \"array\" must be one of string, number, boolean', 1);\n itemType = types[type];\n i++;\n } else {\n itemType = ValueType;\n }\n\n let N;\n if (args.length > 3) {\n if (args[2] !== null &&\n (typeof args[2] !== 'number' ||\n args[2] < 0 ||\n args[2] !== Math.floor(args[2]))\n ) {\n return context.error('The length argument to \"array\" must be a positive integer literal', 2);\n }\n N = args[2];\n i++;\n }\n\n type = array(itemType, N);\n } else {\n assert(types[name], name);\n type = types[name];\n }\n\n const parsed = [];\n for (; i < args.length; i++) {\n const input = context.parse(args[i], i, ValueType);\n if (!input) return null;\n parsed.push(input);\n }\n\n return new Assertion(type, parsed);\n }\n\n evaluate(ctx: EvaluationContext) {\n for (let i = 0; i < this.args.length; i++) {\n const value = this.args[i].evaluate(ctx);\n const error = checkSubtype(this.type, typeOf(value));\n if (!error) {\n return value;\n } else if (i === this.args.length - 1) {\n throw new RuntimeError(`Expected value to be of type ${toString(this.type)}, but found ${toString(typeOf(value))} instead.`);\n }\n }\n\n assert(false);\n return null;\n }\n\n eachChild(fn: (_: Expression) => void) {\n this.args.forEach(fn);\n }\n\n outputDefined(): boolean {\n return this.args.every(arg => arg.outputDefined());\n }\n\n serialize(): Array {\n const type = this.type;\n const serialized = [type.kind];\n if (type.kind === 'array') {\n const itemType = type.itemType;\n if (itemType.kind === 'string' ||\n itemType.kind === 'number' ||\n itemType.kind === 'boolean') {\n serialized.push(itemType.kind);\n const N = type.N;\n if (typeof N === 'number' || this.args.length > 1) {\n serialized.push(N);\n }\n }\n }\n return serialized.concat(this.args.map(arg => arg.serialize()));\n }\n}\n\nexport default Assertion;\n","// @flow\n\nimport {NumberType, ValueType, FormattedType, array, StringType, ColorType, ResolvedImageType} from '../types';\nimport Formatted, {FormattedSection} from '../types/formatted';\nimport {toString, typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\n\ntype FormattedSectionExpression = {\n // Content of a section may be Image expression or other\n // type of expression that is coercable to 'string'.\n content: Expression,\n scale: Expression | null;\n font: Expression | null;\n textColor: Expression | null;\n}\n\nexport default class FormatExpression implements Expression {\n type: Type;\n sections: Array;\n\n constructor(sections: Array) {\n this.type = FormattedType;\n this.sections = sections;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length < 2) {\n return context.error(`Expected at least one argument.`);\n }\n\n const firstArg = args[1];\n if (!Array.isArray(firstArg) && typeof firstArg === 'object') {\n return context.error(`First argument must be an image or text section.`);\n }\n\n const sections: Array = [];\n let nextTokenMayBeObject = false;\n for (let i = 1; i <= args.length - 1; ++i) {\n const arg = (args[i]: any);\n\n if (nextTokenMayBeObject && typeof arg === \"object\" && !Array.isArray(arg)) {\n nextTokenMayBeObject = false;\n\n let scale = null;\n if (arg['font-scale']) {\n scale = context.parse(arg['font-scale'], 1, NumberType);\n if (!scale) return null;\n }\n\n let font = null;\n if (arg['text-font']) {\n font = context.parse(arg['text-font'], 1, array(StringType));\n if (!font) return null;\n }\n\n let textColor = null;\n if (arg['text-color']) {\n textColor = context.parse(arg['text-color'], 1, ColorType);\n if (!textColor) return null;\n }\n\n const lastExpression = sections[sections.length - 1];\n lastExpression.scale = scale;\n lastExpression.font = font;\n lastExpression.textColor = textColor;\n } else {\n const content = context.parse(args[i], 1, ValueType);\n if (!content) return null;\n\n const kind = content.type.kind;\n if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage')\n return context.error(`Formatted text type must be 'string', 'value', 'image' or 'null'.`);\n\n nextTokenMayBeObject = true;\n sections.push({content, scale: null, font: null, textColor: null});\n }\n }\n\n return new FormatExpression(sections);\n }\n\n evaluate(ctx: EvaluationContext) {\n const evaluateSection = section => {\n const evaluatedContent = section.content.evaluate(ctx);\n if (typeOf(evaluatedContent) === ResolvedImageType) {\n return new FormattedSection('', evaluatedContent, null, null, null);\n }\n\n return new FormattedSection(\n toString(evaluatedContent),\n null,\n section.scale ? section.scale.evaluate(ctx) : null,\n section.font ? section.font.evaluate(ctx).join(',') : null,\n section.textColor ? section.textColor.evaluate(ctx) : null\n );\n };\n\n return new Formatted(this.sections.map(evaluateSection));\n }\n\n eachChild(fn: (_: Expression) => void) {\n for (const section of this.sections) {\n fn(section.content);\n if (section.scale) {\n fn(section.scale);\n }\n if (section.font) {\n fn(section.font);\n }\n if (section.textColor) {\n fn(section.textColor);\n }\n }\n }\n\n outputDefined() {\n // Technically the combinatoric set of all children\n // Usually, this.text will be undefined anyway\n return false;\n }\n\n serialize() {\n const serialized = [\"format\"];\n for (const section of this.sections) {\n serialized.push(section.content.serialize());\n const options = {};\n if (section.scale) {\n options['font-scale'] = section.scale.serialize();\n }\n if (section.font) {\n options['text-font'] = section.font.serialize();\n }\n if (section.textColor) {\n options['text-color'] = section.textColor.serialize();\n }\n serialized.push(options);\n }\n return serialized;\n }\n}\n","// @flow\n\nimport {ResolvedImageType, StringType} from '../types';\nimport ResolvedImage from '../types/resolved_image';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\n\nexport default class ImageExpression implements Expression {\n type: Type;\n input: Expression;\n\n constructor(input: Expression) {\n this.type = ResolvedImageType;\n this.input = input;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length !== 2) {\n return context.error(`Expected two arguments.`);\n }\n\n const name = context.parse(args[1], 1, StringType);\n if (!name) return context.error(`No image name provided.`);\n\n return new ImageExpression(name);\n }\n\n evaluate(ctx: EvaluationContext) {\n const evaluatedImageName = this.input.evaluate(ctx);\n\n const value = ResolvedImage.fromString(evaluatedImageName);\n if (value && ctx.availableImages) value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1;\n\n return value;\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n }\n\n outputDefined() {\n // The output of image is determined by the list of available images in the evaluation context\n return false;\n }\n\n serialize() {\n return [\"image\", this.input.serialize()];\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport {BooleanType, ColorType, NumberType, StringType, ValueType} from '../types';\nimport {Color, toString as valueToString, validateRGBA} from '../values';\nimport RuntimeError from '../runtime_error';\nimport Formatted from '../types/formatted';\nimport FormatExpression from '../definitions/format';\nimport ImageExpression from '../definitions/image';\nimport ResolvedImage from '../types/resolved_image';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nconst types = {\n 'to-boolean': BooleanType,\n 'to-color': ColorType,\n 'to-number': NumberType,\n 'to-string': StringType\n};\n\n/**\n * Special form for error-coalescing coercion expressions \"to-number\",\n * \"to-color\". Since these coercions can fail at runtime, they accept multiple\n * arguments, only evaluating one at a time until one succeeds.\n *\n * @private\n */\nclass Coercion implements Expression {\n type: Type;\n args: Array;\n\n constructor(type: Type, args: Array) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length < 2)\n return context.error(`Expected at least one argument.`);\n\n const name: string = (args[0]: any);\n assert(types[name], name);\n\n if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2)\n return context.error(`Expected one argument.`);\n\n const type = types[name];\n\n const parsed = [];\n for (let i = 1; i < args.length; i++) {\n const input = context.parse(args[i], i, ValueType);\n if (!input) return null;\n parsed.push(input);\n }\n\n return new Coercion(type, parsed);\n }\n\n evaluate(ctx: EvaluationContext) {\n if (this.type.kind === 'boolean') {\n return Boolean(this.args[0].evaluate(ctx));\n } else if (this.type.kind === 'color') {\n let input;\n let error;\n for (const arg of this.args) {\n input = arg.evaluate(ctx);\n error = null;\n if (input instanceof Color) {\n return input;\n } else if (typeof input === 'string') {\n const c = ctx.parseColor(input);\n if (c) return c;\n } else if (Array.isArray(input)) {\n if (input.length < 3 || input.length > 4) {\n error = `Invalid rbga value ${JSON.stringify(input)}: expected an array containing either three or four numeric values.`;\n } else {\n error = validateRGBA(input[0], input[1], input[2], input[3]);\n }\n if (!error) {\n return new Color((input[0]: any) / 255, (input[1]: any) / 255, (input[2]: any) / 255, (input[3]: any));\n }\n }\n }\n throw new RuntimeError(error || `Could not parse color from value '${typeof input === 'string' ? input : String(JSON.stringify(input))}'`);\n } else if (this.type.kind === 'number') {\n let value = null;\n for (const arg of this.args) {\n value = arg.evaluate(ctx);\n if (value === null) return 0;\n const num = Number(value);\n if (isNaN(num)) continue;\n return num;\n }\n throw new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`);\n } else if (this.type.kind === 'formatted') {\n // There is no explicit 'to-formatted' but this coercion can be implicitly\n // created by properties that expect the 'formatted' type.\n return Formatted.fromString(valueToString(this.args[0].evaluate(ctx)));\n } else if (this.type.kind === 'resolvedImage') {\n return ResolvedImage.fromString(valueToString(this.args[0].evaluate(ctx)));\n } else {\n return valueToString(this.args[0].evaluate(ctx));\n }\n }\n\n eachChild(fn: (_: Expression) => void) {\n this.args.forEach(fn);\n }\n\n outputDefined(): boolean {\n return this.args.every(arg => arg.outputDefined());\n }\n\n serialize() {\n if (this.type.kind === 'formatted') {\n return new FormatExpression([{content: this.args[0], scale: null, font: null, textColor: null}]).serialize();\n }\n\n if (this.type.kind === 'resolvedImage') {\n return new ImageExpression(this.args[0]).serialize();\n }\n\n const serialized = [`to-${this.type.kind}`];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Coercion;\n","// @flow\n\nimport {Color} from './values';\nimport type {FormattedSection} from './types/formatted';\nimport type {GlobalProperties, Feature, FeatureState} from './index';\nimport type {CanonicalTileID} from '../../source/tile_id';\n\nconst geometryTypes = ['Unknown', 'Point', 'LineString', 'Polygon'];\n\nclass EvaluationContext {\n globals: GlobalProperties;\n feature: ?Feature;\n featureState: ?FeatureState;\n formattedSection: ?FormattedSection;\n availableImages: ?Array;\n canonical: ?CanonicalTileID;\n\n _parseColorCache: {[_: string]: ?Color};\n\n constructor() {\n this.globals = (null: any);\n this.feature = null;\n this.featureState = null;\n this.formattedSection = null;\n this._parseColorCache = {};\n this.availableImages = null;\n this.canonical = null;\n }\n\n id() {\n return this.feature && 'id' in this.feature ? this.feature.id : null;\n }\n\n geometryType() {\n return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null;\n }\n\n geometry() {\n return this.feature && 'geometry' in this.feature ? this.feature.geometry : null;\n }\n\n canonicalID() {\n return this.canonical;\n }\n\n properties() {\n return this.feature && this.feature.properties || {};\n }\n\n parseColor(input: string): ?Color {\n let cached = this._parseColorCache[input];\n if (!cached) {\n cached = this._parseColorCache[input] = Color.parse(input);\n }\n return cached;\n }\n}\n\nexport default EvaluationContext;\n","// @flow\n\nimport {toString} from './types';\n\nimport ParsingContext from './parsing_context';\nimport EvaluationContext from './evaluation_context';\nimport assert from 'assert';\n\nimport type {Expression, ExpressionRegistry} from './expression';\nimport type {Type} from './types';\nimport type {Value} from './values';\n\nexport type Varargs = {| type: Type |};\ntype Signature = Array | Varargs;\ntype Evaluate = (EvaluationContext, Array) => Value;\ntype Definition = [Type, Signature, Evaluate] |\n {|type: Type, overloads: Array<[Signature, Evaluate]>|};\n\nclass CompoundExpression implements Expression {\n name: string;\n type: Type;\n _evaluate: Evaluate;\n args: Array;\n\n static definitions: {[_: string]: Definition };\n\n constructor(name: string, type: Type, evaluate: Evaluate, args: Array) {\n this.name = name;\n this.type = type;\n this._evaluate = evaluate;\n this.args = args;\n }\n\n evaluate(ctx: EvaluationContext) {\n return this._evaluate(ctx, this.args);\n }\n\n eachChild(fn: (_: Expression) => void) {\n this.args.forEach(fn);\n }\n\n outputDefined() {\n return false;\n }\n\n serialize(): Array {\n return [this.name].concat(this.args.map(arg => arg.serialize()));\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n const op: string = (args[0]: any);\n const definition = CompoundExpression.definitions[op];\n if (!definition) {\n return context.error(`Unknown expression \"${op}\". If you wanted a literal array, use [\"literal\", [...]].`, 0);\n }\n\n // Now check argument types against each signature\n const type = Array.isArray(definition) ?\n definition[0] : definition.type;\n\n const availableOverloads = Array.isArray(definition) ?\n [[definition[1], definition[2]]] :\n definition.overloads;\n\n const overloads = availableOverloads.filter(([signature]) => (\n !Array.isArray(signature) || // varags\n signature.length === args.length - 1 // correct param count\n ));\n\n let signatureContext: ParsingContext = (null: any);\n\n for (const [params, evaluate] of overloads) {\n // Use a fresh context for each attempted signature so that, if\n // we eventually succeed, we haven't polluted `context.errors`.\n signatureContext = new ParsingContext(context.registry, context.path, null, context.scope);\n\n // First parse all the args, potentially coercing to the\n // types expected by this overload.\n const parsedArgs: Array = [];\n let argParseFailed = false;\n for (let i = 1; i < args.length; i++) {\n const arg = args[i];\n const expectedType = Array.isArray(params) ?\n params[i - 1] :\n params.type;\n\n const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType);\n if (!parsed) {\n argParseFailed = true;\n break;\n }\n parsedArgs.push(parsed);\n }\n if (argParseFailed) {\n // Couldn't coerce args of this overload to expected type, move\n // on to next one.\n continue;\n }\n\n if (Array.isArray(params)) {\n if (params.length !== parsedArgs.length) {\n signatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`);\n continue;\n }\n }\n\n for (let i = 0; i < parsedArgs.length; i++) {\n const expected = Array.isArray(params) ? params[i] : params.type;\n const arg = parsedArgs[i];\n signatureContext.concat(i + 1).checkSubtype(expected, arg.type);\n }\n\n if (signatureContext.errors.length === 0) {\n return new CompoundExpression(op, type, evaluate, parsedArgs);\n }\n }\n\n assert(!signatureContext || signatureContext.errors.length > 0);\n\n if (overloads.length === 1) {\n context.errors.push(...signatureContext.errors);\n } else {\n const expected = overloads.length ? overloads : availableOverloads;\n const signatures = expected\n .map(([params]) => stringifySignature(params))\n .join(' | ');\n\n const actualTypes = [];\n // For error message, re-parse arguments without trying to\n // apply any coercions\n for (let i = 1; i < args.length; i++) {\n const parsed = context.parse(args[i], 1 + actualTypes.length);\n if (!parsed) return null;\n actualTypes.push(toString(parsed.type));\n }\n context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(', ')}) instead.`);\n }\n\n return null;\n }\n\n static register(\n registry: ExpressionRegistry,\n definitions: {[_: string]: Definition }\n ) {\n assert(!CompoundExpression.definitions);\n CompoundExpression.definitions = definitions;\n for (const name in definitions) {\n registry[name] = CompoundExpression;\n }\n }\n}\n\nfunction stringifySignature(signature: Signature): string {\n if (Array.isArray(signature)) {\n return `(${signature.map(toString).join(', ')})`;\n } else {\n return `(${toString(signature.type)}...)`;\n }\n}\n\nexport default CompoundExpression;\n","// @flow\n\nimport {StringType, BooleanType, CollatorType} from '../types';\nimport Collator from '../types/collator';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\n\nexport default class CollatorExpression implements Expression {\n type: Type;\n caseSensitive: Expression;\n diacriticSensitive: Expression;\n locale: Expression | null;\n\n constructor(caseSensitive: Expression, diacriticSensitive: Expression, locale: Expression | null) {\n this.type = CollatorType;\n this.locale = locale;\n this.caseSensitive = caseSensitive;\n this.diacriticSensitive = diacriticSensitive;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length !== 2)\n return context.error(`Expected one argument.`);\n\n const options = (args[1]: any);\n if (typeof options !== \"object\" || Array.isArray(options))\n return context.error(`Collator options argument must be an object.`);\n\n const caseSensitive = context.parse(\n options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType);\n if (!caseSensitive) return null;\n\n const diacriticSensitive = context.parse(\n options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType);\n if (!diacriticSensitive) return null;\n\n let locale = null;\n if (options['locale']) {\n locale = context.parse(options['locale'], 1, StringType);\n if (!locale) return null;\n }\n\n return new CollatorExpression(caseSensitive, diacriticSensitive, locale);\n }\n\n evaluate(ctx: EvaluationContext) {\n return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.caseSensitive);\n fn(this.diacriticSensitive);\n if (this.locale) {\n fn(this.locale);\n }\n }\n\n outputDefined() {\n // Technically the set of possible outputs is the combinatoric set of Collators produced\n // by all possible outputs of locale/caseSensitive/diacriticSensitive\n // But for the primary use of Collators in comparison operators, we ignore the Collator's\n // possible outputs anyway, so we can get away with leaving this false for now.\n return false;\n }\n\n serialize() {\n const options = {};\n options['case-sensitive'] = this.caseSensitive.serialize();\n options['diacritic-sensitive'] = this.diacriticSensitive.serialize();\n if (this.locale) {\n options['locale'] = this.locale.serialize();\n }\n return [\"collator\", options];\n }\n}\n","// @flow\n\nimport {isValue} from '../values';\nimport type {Type} from '../types';\nimport {BooleanType} from '../types';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {GeoJSON, GeoJSONPolygon, GeoJSONMultiPolygon} from '@mapbox/geojson-types';\nimport Point from '@mapbox/point-geometry';\nimport type {CanonicalTileID} from '../../../source/tile_id';\n\ntype GeoJSONPolygons =| GeoJSONPolygon | GeoJSONMultiPolygon;\n\n// minX, minY, maxX, maxY\ntype BBox = [number, number, number, number];\nconst EXTENT = 8192;\n\nfunction updateBBox(bbox: BBox, coord: Point) {\n bbox[0] = Math.min(bbox[0], coord[0]);\n bbox[1] = Math.min(bbox[1], coord[1]);\n bbox[2] = Math.max(bbox[2], coord[0]);\n bbox[3] = Math.max(bbox[3], coord[1]);\n}\n\nfunction mercatorXfromLng(lng: number) {\n return (180 + lng) / 360;\n}\n\nfunction mercatorYfromLat(lat: number) {\n return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360;\n}\n\nfunction boxWithinBox(bbox1: BBox, bbox2: BBox) {\n if (bbox1[0] <= bbox2[0]) return false;\n if (bbox1[2] >= bbox2[2]) return false;\n if (bbox1[1] <= bbox2[1]) return false;\n if (bbox1[3] >= bbox2[3]) return false;\n return true;\n}\n\nfunction getTileCoordinates(p, canonical: CanonicalTileID) {\n const x = mercatorXfromLng(p[0]);\n const y = mercatorYfromLat(p[1]);\n const tilesAtZoom = Math.pow(2, canonical.z);\n return [Math.round(x * tilesAtZoom * EXTENT), Math.round(y * tilesAtZoom * EXTENT)];\n}\n\nfunction onBoundary(p, p1, p2) {\n const x1 = p[0] - p1[0];\n const y1 = p[1] - p1[1];\n const x2 = p[0] - p2[0];\n const y2 = p[1] - p2[1];\n return (x1 * y2 - x2 * y1 === 0) && (x1 * x2 <= 0) && (y1 * y2 <= 0);\n}\n\nfunction rayIntersect(p, p1, p2) {\n return ((p1[1] > p[1]) !== (p2[1] > p[1])) && (p[0] < (p2[0] - p1[0]) * (p[1] - p1[1]) / (p2[1] - p1[1]) + p1[0]);\n}\n\n// ray casting algorithm for detecting if point is in polygon\nfunction pointWithinPolygon(point, rings) {\n let inside = false;\n for (let i = 0, len = rings.length; i < len; i++) {\n const ring = rings[i];\n for (let j = 0, len2 = ring.length; j < len2 - 1; j++) {\n if (onBoundary(point, ring[j], ring[j + 1])) return false;\n if (rayIntersect(point, ring[j], ring[j + 1])) inside = !inside;\n }\n }\n return inside;\n}\n\nfunction pointWithinPolygons(point, polygons) {\n for (let i = 0; i < polygons.length; i++) {\n if (pointWithinPolygon(point, polygons[i])) return true;\n }\n return false;\n}\n\nfunction perp(v1, v2) {\n return (v1[0] * v2[1] - v1[1] * v2[0]);\n}\n\n// check if p1 and p2 are in different sides of line segment q1->q2\nfunction twoSided(p1, p2, q1, q2) {\n // q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3)\n const x1 = p1[0] - q1[0];\n const y1 = p1[1] - q1[1];\n const x2 = p2[0] - q1[0];\n const y2 = p2[1] - q1[1];\n const x3 = q2[0] - q1[0];\n const y3 = q2[1] - q1[1];\n const det1 = (x1 * y3 - x3 * y1);\n const det2 = (x2 * y3 - x3 * y2);\n if ((det1 > 0 && det2 < 0) || (det1 < 0 && det2 > 0)) return true;\n return false;\n}\n// a, b are end points for line segment1, c and d are end points for line segment2\nfunction lineIntersectLine(a, b, c, d) {\n // check if two segments are parallel or not\n // precondition is end point a, b is inside polygon, if line a->b is\n // parallel to polygon edge c->d, then a->b won't intersect with c->d\n const vectorP = [b[0] - a[0], b[1] - a[1]];\n const vectorQ = [d[0] - c[0], d[1] - c[1]];\n if (perp(vectorQ, vectorP) === 0) return false;\n\n // If lines are intersecting with each other, the relative location should be:\n // a and b lie in different sides of segment c->d\n // c and d lie in different sides of segment a->b\n if (twoSided(a, b, c, d) && twoSided(c, d, a, b)) return true;\n return false;\n}\n\nfunction lineIntersectPolygon(p1, p2, polygon) {\n for (const ring of polygon) {\n // loop through every edge of the ring\n for (let j = 0; j < ring.length - 1; ++j) {\n if (lineIntersectLine(p1, p2, ring[j], ring[j + 1])) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction lineStringWithinPolygon(line, polygon) {\n // First, check if geometry points of line segments are all inside polygon\n for (let i = 0; i < line.length; ++i) {\n if (!pointWithinPolygon(line[i], polygon)) {\n return false;\n }\n }\n\n // Second, check if there is line segment intersecting polygon edge\n for (let i = 0; i < line.length - 1; ++i) {\n if (lineIntersectPolygon(line[i], line[i + 1], polygon)) {\n return false;\n }\n }\n return true;\n}\n\nfunction lineStringWithinPolygons(line, polygons) {\n for (let i = 0; i < polygons.length; i++) {\n if (lineStringWithinPolygon(line, polygons[i])) return true;\n }\n return false;\n}\n\nfunction getTilePolygon(coordinates, bbox, canonical) {\n const polygon = [];\n for (let i = 0; i < coordinates.length; i++) {\n const ring = [];\n for (let j = 0; j < coordinates[i].length; j++) {\n const coord = getTileCoordinates(coordinates[i][j], canonical);\n updateBBox(bbox, coord);\n ring.push(coord);\n }\n polygon.push(ring);\n }\n return polygon;\n}\n\nfunction getTilePolygons(coordinates, bbox, canonical) {\n const polygons = [];\n for (let i = 0; i < coordinates.length; i++) {\n const polygon = getTilePolygon(coordinates[i], bbox, canonical);\n polygons.push(polygon);\n }\n return polygons;\n}\n\nfunction updatePoint(p, bbox, polyBBox, worldSize) {\n if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) {\n const halfWorldSize = worldSize * 0.5;\n let shift = (p[0] - polyBBox[0] > halfWorldSize) ? -worldSize : (polyBBox[0] - p[0] > halfWorldSize) ? worldSize : 0;\n if (shift === 0) {\n shift = (p[0] - polyBBox[2] > halfWorldSize) ? -worldSize : (polyBBox[2] - p[0] > halfWorldSize) ? worldSize : 0;\n }\n p[0] += shift;\n }\n updateBBox(bbox, p);\n}\n\nfunction resetBBox(bbox) {\n bbox[0] = bbox[1] = Infinity;\n bbox[2] = bbox[3] = -Infinity;\n}\n\nfunction getTilePoints(geometry, pointBBox, polyBBox, canonical) {\n const worldSize = Math.pow(2, canonical.z) * EXTENT;\n const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];\n const tilePoints = [];\n for (const points of geometry) {\n for (const point of points) {\n const p = [point.x + shifts[0], point.y + shifts[1]];\n updatePoint(p, pointBBox, polyBBox, worldSize);\n tilePoints.push(p);\n }\n }\n return tilePoints;\n}\n\nfunction getTileLines(geometry, lineBBox, polyBBox, canonical) {\n const worldSize = Math.pow(2, canonical.z) * EXTENT;\n const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];\n const tileLines = [];\n for (const line of geometry) {\n const tileLine = [];\n for (const point of line) {\n const p = [point.x + shifts[0], point.y + shifts[1]];\n updateBBox(lineBBox, p);\n tileLine.push(p);\n }\n tileLines.push(tileLine);\n }\n if (lineBBox[2] - lineBBox[0] <= worldSize / 2) {\n resetBBox(lineBBox);\n for (const line of tileLines) {\n for (const p of line) {\n updatePoint(p, lineBBox, polyBBox, worldSize);\n }\n }\n }\n return tileLines;\n}\n\nfunction pointsWithinPolygons(ctx: EvaluationContext, polygonGeometry: GeoJSONPolygons) {\n const pointBBox = [Infinity, Infinity, -Infinity, -Infinity];\n const polyBBox = [Infinity, Infinity, -Infinity, -Infinity];\n\n const canonical = ctx.canonicalID();\n\n if (polygonGeometry.type === 'Polygon') {\n const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);\n const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);\n if (!boxWithinBox(pointBBox, polyBBox)) return false;\n\n for (const point of tilePoints) {\n if (!pointWithinPolygon(point, tilePolygon)) return false;\n }\n }\n if (polygonGeometry.type === 'MultiPolygon') {\n const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);\n const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);\n if (!boxWithinBox(pointBBox, polyBBox)) return false;\n\n for (const point of tilePoints) {\n if (!pointWithinPolygons(point, tilePolygons)) return false;\n }\n }\n\n return true;\n}\n\nfunction linesWithinPolygons(ctx: EvaluationContext, polygonGeometry: GeoJSONPolygons) {\n const lineBBox = [Infinity, Infinity, -Infinity, -Infinity];\n const polyBBox = [Infinity, Infinity, -Infinity, -Infinity];\n\n const canonical = ctx.canonicalID();\n\n if (polygonGeometry.type === 'Polygon') {\n const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);\n const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);\n if (!boxWithinBox(lineBBox, polyBBox)) return false;\n\n for (const line of tileLines) {\n if (!lineStringWithinPolygon(line, tilePolygon)) return false;\n }\n }\n if (polygonGeometry.type === 'MultiPolygon') {\n const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);\n const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);\n if (!boxWithinBox(lineBBox, polyBBox)) return false;\n\n for (const line of tileLines) {\n if (!lineStringWithinPolygons(line, tilePolygons)) return false;\n }\n }\n return true;\n}\n\nclass Within implements Expression {\n type: Type;\n geojson: GeoJSON\n geometries: GeoJSONPolygons;\n\n constructor(geojson: GeoJSON, geometries: GeoJSONPolygons) {\n this.type = BooleanType;\n this.geojson = geojson;\n this.geometries = geometries;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 2)\n return context.error(`'within' expression requires exactly one argument, but found ${args.length - 1} instead.`);\n if (isValue(args[1])) {\n const geojson = (args[1]: Object);\n if (geojson.type === 'FeatureCollection') {\n for (let i = 0; i < geojson.features.length; ++i) {\n const type = geojson.features[i].geometry.type;\n if (type === 'Polygon' || type === 'MultiPolygon') {\n return new Within(geojson, geojson.features[i].geometry);\n }\n }\n } else if (geojson.type === 'Feature') {\n const type = geojson.geometry.type;\n if (type === 'Polygon' || type === 'MultiPolygon') {\n return new Within(geojson, geojson.geometry);\n }\n } else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') {\n return new Within(geojson, geojson);\n }\n }\n return context.error(`'within' expression requires valid geojson object that contains polygon geometry type.`);\n }\n\n evaluate(ctx: EvaluationContext) {\n if (ctx.geometry() != null && ctx.canonicalID() != null) {\n if (ctx.geometryType() === 'Point') {\n return pointsWithinPolygons(ctx, this.geometries);\n } else if (ctx.geometryType() === 'LineString') {\n return linesWithinPolygons(ctx, this.geometries);\n }\n }\n return false;\n }\n\n eachChild() {}\n\n outputDefined(): boolean {\n return true;\n }\n\n serialize(): Array {\n return [\"within\", this.geojson];\n }\n\n}\n\nexport default Within;\n","// @flow\n\nimport CompoundExpression from './compound_expression';\nimport Within from './definitions/within';\nimport type {Expression} from './expression.js';\n\nfunction isFeatureConstant(e: Expression) {\n if (e instanceof CompoundExpression) {\n if (e.name === 'get' && e.args.length === 1) {\n return false;\n } else if (e.name === 'feature-state') {\n return false;\n } else if (e.name === 'has' && e.args.length === 1) {\n return false;\n } else if (\n e.name === 'properties' ||\n e.name === 'geometry-type' ||\n e.name === 'id'\n ) {\n return false;\n } else if (/^filter-/.test(e.name)) {\n return false;\n }\n }\n\n if (e instanceof Within) {\n return false;\n }\n\n let result = true;\n e.eachChild(arg => {\n if (result && !isFeatureConstant(arg)) { result = false; }\n });\n return result;\n}\n\nfunction isStateConstant(e: Expression) {\n if (e instanceof CompoundExpression) {\n if (e.name === 'feature-state') {\n return false;\n }\n }\n let result = true;\n e.eachChild(arg => {\n if (result && !isStateConstant(arg)) { result = false; }\n });\n return result;\n}\n\nfunction isGlobalPropertyConstant(e: Expression, properties: Array) {\n if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) { return false; }\n let result = true;\n e.eachChild((arg) => {\n if (result && !isGlobalPropertyConstant(arg, properties)) { result = false; }\n });\n return result;\n}\n\nexport {isFeatureConstant, isGlobalPropertyConstant, isStateConstant};\n","// @flow\n\nimport type {Type} from '../types';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\n\nclass Var implements Expression {\n type: Type;\n name: string;\n boundExpression: Expression;\n\n constructor(name: string, boundExpression: Expression) {\n this.type = boundExpression.type;\n this.name = name;\n this.boundExpression = boundExpression;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 2 || typeof args[1] !== 'string')\n return context.error(`'var' expression requires exactly one string literal argument.`);\n\n const name = args[1];\n if (!context.scope.has(name)) {\n return context.error(`Unknown variable \"${name}\". Make sure \"${name}\" has been bound in an enclosing \"let\" expression before using it.`, 1);\n }\n\n return new Var(name, context.scope.get(name));\n }\n\n evaluate(ctx: EvaluationContext) {\n return this.boundExpression.evaluate(ctx);\n }\n\n eachChild() {}\n\n outputDefined() {\n return false;\n }\n\n serialize() {\n return [\"var\", this.name];\n }\n}\n\nexport default Var;\n","// @flow\n\nimport Scope from './scope';\nimport {checkSubtype} from './types';\nimport ParsingError from './parsing_error';\nimport Literal from './definitions/literal';\nimport Assertion from './definitions/assertion';\nimport Coercion from './definitions/coercion';\nimport EvaluationContext from './evaluation_context';\nimport CompoundExpression from './compound_expression';\nimport CollatorExpression from './definitions/collator';\nimport Within from './definitions/within';\nimport {isGlobalPropertyConstant, isFeatureConstant} from './is_constant';\nimport Var from './definitions/var';\n\nimport type {Expression, ExpressionRegistry} from './expression';\nimport type {Type} from './types';\n\n/**\n * State associated parsing at a given point in an expression tree.\n * @private\n */\nclass ParsingContext {\n registry: ExpressionRegistry;\n path: Array;\n key: string;\n scope: Scope;\n errors: Array;\n\n // The expected type of this expression. Provided only to allow Expression\n // implementations to infer argument types: Expression#parse() need not\n // check that the output type of the parsed expression matches\n // `expectedType`.\n expectedType: ?Type;\n\n constructor(\n registry: ExpressionRegistry,\n path: Array = [],\n expectedType: ?Type,\n scope: Scope = new Scope(),\n errors: Array = []\n ) {\n this.registry = registry;\n this.path = path;\n this.key = path.map(part => `[${part}]`).join('');\n this.scope = scope;\n this.errors = errors;\n this.expectedType = expectedType;\n }\n\n /**\n * @param expr the JSON expression to parse\n * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed\n * @param options\n * @param options.omitTypeAnnotations set true to omit inferred type annotations. Caller beware: with this option set, the parsed expression's type will NOT satisfy `expectedType` if it would normally be wrapped in an inferred annotation.\n * @private\n */\n parse(\n expr: mixed,\n index?: number,\n expectedType?: ?Type,\n bindings?: Array<[string, Expression]>,\n options: {typeAnnotation?: 'assert' | 'coerce' | 'omit'} = {}\n ): ?Expression {\n if (index) {\n return this.concat(index, expectedType, bindings)._parse(expr, options);\n }\n return this._parse(expr, options);\n }\n\n _parse(expr: mixed, options: {typeAnnotation?: 'assert' | 'coerce' | 'omit'}): ?Expression {\n if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') {\n expr = ['literal', expr];\n }\n\n function annotate(parsed, type, typeAnnotation: 'assert' | 'coerce' | 'omit') {\n if (typeAnnotation === 'assert') {\n return new Assertion(type, [parsed]);\n } else if (typeAnnotation === 'coerce') {\n return new Coercion(type, [parsed]);\n } else {\n return parsed;\n }\n }\n\n if (Array.isArray(expr)) {\n if (expr.length === 0) {\n return this.error(`Expected an array with at least one element. If you wanted a literal array, use [\"literal\", []].`);\n }\n\n const op = expr[0];\n if (typeof op !== 'string') {\n this.error(`Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use [\"literal\", [...]].`, 0);\n return null;\n }\n\n const Expr = this.registry[op];\n if (Expr) {\n let parsed = Expr.parse(expr, this);\n if (!parsed) return null;\n\n if (this.expectedType) {\n const expected = this.expectedType;\n const actual = parsed.type;\n\n // When we expect a number, string, boolean, or array but have a value, wrap it in an assertion.\n // When we expect a color or formatted string, but have a string or value, wrap it in a coercion.\n // Otherwise, we do static type-checking.\n //\n // These behaviors are overridable for:\n // * The \"coalesce\" operator, which needs to omit type annotations.\n // * String-valued properties (e.g. `text-field`), where coercion is more convenient than assertion.\n //\n if ((expected.kind === 'string' || expected.kind === 'number' || expected.kind === 'boolean' || expected.kind === 'object' || expected.kind === 'array') && actual.kind === 'value') {\n parsed = annotate(parsed, expected, options.typeAnnotation || 'assert');\n } else if ((expected.kind === 'color' || expected.kind === 'formatted' || expected.kind === 'resolvedImage') && (actual.kind === 'value' || actual.kind === 'string')) {\n parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce');\n } else if (this.checkSubtype(expected, actual)) {\n return null;\n }\n }\n\n // If an expression's arguments are all literals, we can evaluate\n // it immediately and replace it with a literal value in the\n // parsed/compiled result. Expressions that expect an image should\n // not be resolved here so we can later get the available images.\n if (!(parsed instanceof Literal) && (parsed.type.kind !== 'resolvedImage') && isConstant(parsed)) {\n const ec = new EvaluationContext();\n try {\n parsed = new Literal(parsed.type, parsed.evaluate(ec));\n } catch (e) {\n this.error(e.message);\n return null;\n }\n }\n\n return parsed;\n }\n\n return this.error(`Unknown expression \"${op}\". If you wanted a literal array, use [\"literal\", [...]].`, 0);\n } else if (typeof expr === 'undefined') {\n return this.error(`'undefined' value invalid. Use null instead.`);\n } else if (typeof expr === 'object') {\n return this.error(`Bare objects invalid. Use [\"literal\", {...}] instead.`);\n } else {\n return this.error(`Expected an array, but found ${typeof expr} instead.`);\n }\n }\n\n /**\n * Returns a copy of this context suitable for parsing the subexpression at\n * index `index`, optionally appending to 'let' binding map.\n *\n * Note that `errors` property, intended for collecting errors while\n * parsing, is copied by reference rather than cloned.\n * @private\n */\n concat(index: number, expectedType?: ?Type, bindings?: Array<[string, Expression]>) {\n const path = typeof index === 'number' ? this.path.concat(index) : this.path;\n const scope = bindings ? this.scope.concat(bindings) : this.scope;\n return new ParsingContext(\n this.registry,\n path,\n expectedType || null,\n scope,\n this.errors\n );\n }\n\n /**\n * Push a parsing (or type checking) error into the `this.errors`\n * @param error The message\n * @param keys Optionally specify the source of the error at a child\n * of the current expression at `this.key`.\n * @private\n */\n error(error: string, ...keys: Array) {\n const key = `${this.key}${keys.map(k => `[${k}]`).join('')}`;\n this.errors.push(new ParsingError(key, error));\n }\n\n /**\n * Returns null if `t` is a subtype of `expected`; otherwise returns an\n * error message and also pushes it to `this.errors`.\n */\n checkSubtype(expected: Type, t: Type): ?string {\n const error = checkSubtype(expected, t);\n if (error) this.error(error);\n return error;\n }\n}\n\nexport default ParsingContext;\n\nfunction isConstant(expression: Expression) {\n if (expression instanceof Var) {\n return isConstant(expression.boundExpression);\n } else if (expression instanceof CompoundExpression && expression.name === 'error') {\n return false;\n } else if (expression instanceof CollatorExpression) {\n // Although the results of a Collator expression with fixed arguments\n // generally shouldn't change between executions, we can't serialize them\n // as constant expressions because results change based on environment.\n return false;\n } else if (expression instanceof Within) {\n return false;\n }\n\n const isTypeAnnotation = expression instanceof Coercion ||\n expression instanceof Assertion;\n\n let childrenConstant = true;\n expression.eachChild(child => {\n // We can _almost_ assume that if `expressions` children are constant,\n // they would already have been evaluated to Literal values when they\n // were parsed. Type annotations are the exception, because they might\n // have been inferred and added after a child was parsed.\n\n // So we recurse into isConstant() for the children of type annotations,\n // but otherwise simply check whether they are Literals.\n if (isTypeAnnotation) {\n childrenConstant = childrenConstant && isConstant(child);\n } else {\n childrenConstant = childrenConstant && child instanceof Literal;\n }\n });\n if (!childrenConstant) {\n return false;\n }\n\n return isFeatureConstant(expression) &&\n isGlobalPropertyConstant(expression, ['zoom', 'heatmap-density', 'line-progress', 'accumulated', 'is-supported-script']);\n}\n","// @flow\n\nimport RuntimeError from './runtime_error';\n\nimport type {Expression} from './expression';\n\nexport type Stops = Array<[number, Expression]>;\n\n/**\n * Returns the index of the last stop <= input, or 0 if it doesn't exist.\n * @private\n */\nexport function findStopLessThanOrEqualTo(stops: Array, input: number) {\n const lastIndex = stops.length - 1;\n let lowerIndex = 0;\n let upperIndex = lastIndex;\n let currentIndex = 0;\n let currentValue, nextValue;\n\n while (lowerIndex <= upperIndex) {\n currentIndex = Math.floor((lowerIndex + upperIndex) / 2);\n currentValue = stops[currentIndex];\n nextValue = stops[currentIndex + 1];\n\n if (currentValue <= input) {\n if (currentIndex === lastIndex || input < nextValue) { // Search complete\n return currentIndex;\n }\n\n lowerIndex = currentIndex + 1;\n } else if (currentValue > input) {\n upperIndex = currentIndex - 1;\n } else {\n throw new RuntimeError('Input is not a number.');\n }\n }\n\n return 0;\n}\n","// @flow\n\nimport {NumberType} from '../types';\n\nimport {findStopLessThanOrEqualTo} from '../stops';\n\nimport type {Stops} from '../stops';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nclass Step implements Expression {\n type: Type;\n\n input: Expression;\n labels: Array;\n outputs: Array;\n\n constructor(type: Type, input: Expression, stops: Stops) {\n this.type = type;\n this.input = input;\n\n this.labels = [];\n this.outputs = [];\n for (const [label, expression] of stops) {\n this.labels.push(label);\n this.outputs.push(expression);\n }\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length - 1 < 4) {\n return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n }\n\n if ((args.length - 1) % 2 !== 0) {\n return context.error(`Expected an even number of arguments.`);\n }\n\n const input = context.parse(args[1], 1, NumberType);\n if (!input) return null;\n\n const stops: Stops = [];\n\n let outputType: Type = (null: any);\n if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n\n for (let i = 1; i < args.length; i += 2) {\n const label = i === 1 ? -Infinity : args[i];\n const value = args[i + 1];\n\n const labelKey = i;\n const valueKey = i + 1;\n\n if (typeof label !== 'number') {\n return context.error('Input/output pairs for \"step\" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey);\n }\n\n if (stops.length && stops[stops.length - 1][0] >= label) {\n return context.error('Input/output pairs for \"step\" expressions must be arranged with input values in strictly ascending order.', labelKey);\n }\n\n const parsed = context.parse(value, valueKey, outputType);\n if (!parsed) return null;\n outputType = outputType || parsed.type;\n stops.push([label, parsed]);\n }\n\n return new Step(outputType, input, stops);\n }\n\n evaluate(ctx: EvaluationContext) {\n const labels = this.labels;\n const outputs = this.outputs;\n\n if (labels.length === 1) {\n return outputs[0].evaluate(ctx);\n }\n\n const value = ((this.input.evaluate(ctx): any): number);\n if (value <= labels[0]) {\n return outputs[0].evaluate(ctx);\n }\n\n const stopCount = labels.length;\n if (value >= labels[stopCount - 1]) {\n return outputs[stopCount - 1].evaluate(ctx);\n }\n\n const index = findStopLessThanOrEqualTo(labels, value);\n return outputs[index].evaluate(ctx);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n for (const expression of this.outputs) {\n fn(expression);\n }\n }\n\n outputDefined(): boolean {\n return this.outputs.every(out => out.outputDefined());\n }\n\n serialize() {\n const serialized = [\"step\", this.input.serialize()];\n for (let i = 0; i < this.labels.length; i++) {\n if (i > 0) {\n serialized.push(this.labels[i]);\n }\n serialized.push(this.outputs[i].serialize());\n }\n return serialized;\n }\n}\n\nexport default Step;\n","/*\n * Copyright (C) 2008 Apple Inc. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Ported from Webkit\n * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h\n */\n\nmodule.exports = UnitBezier;\n\nfunction UnitBezier(p1x, p1y, p2x, p2y) {\n // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).\n this.cx = 3.0 * p1x;\n this.bx = 3.0 * (p2x - p1x) - this.cx;\n this.ax = 1.0 - this.cx - this.bx;\n\n this.cy = 3.0 * p1y;\n this.by = 3.0 * (p2y - p1y) - this.cy;\n this.ay = 1.0 - this.cy - this.by;\n\n this.p1x = p1x;\n this.p1y = p2y;\n this.p2x = p2x;\n this.p2y = p2y;\n}\n\nUnitBezier.prototype.sampleCurveX = function(t) {\n // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.\n return ((this.ax * t + this.bx) * t + this.cx) * t;\n};\n\nUnitBezier.prototype.sampleCurveY = function(t) {\n return ((this.ay * t + this.by) * t + this.cy) * t;\n};\n\nUnitBezier.prototype.sampleCurveDerivativeX = function(t) {\n return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;\n};\n\nUnitBezier.prototype.solveCurveX = function(x, epsilon) {\n if (typeof epsilon === 'undefined') epsilon = 1e-6;\n\n var t0, t1, t2, x2, i;\n\n // First try a few iterations of Newton's method -- normally very fast.\n for (t2 = x, i = 0; i < 8; i++) {\n\n x2 = this.sampleCurveX(t2) - x;\n if (Math.abs(x2) < epsilon) return t2;\n\n var d2 = this.sampleCurveDerivativeX(t2);\n if (Math.abs(d2) < 1e-6) break;\n\n t2 = t2 - x2 / d2;\n }\n\n // Fall back to the bisection method for reliability.\n t0 = 0.0;\n t1 = 1.0;\n t2 = x;\n\n if (t2 < t0) return t0;\n if (t2 > t1) return t1;\n\n while (t0 < t1) {\n\n x2 = this.sampleCurveX(t2);\n if (Math.abs(x2 - x) < epsilon) return t2;\n\n if (x > x2) {\n t0 = t2;\n } else {\n t1 = t2;\n }\n\n t2 = (t1 - t0) * 0.5 + t0;\n }\n\n // Failure.\n return t2;\n};\n\nUnitBezier.prototype.solve = function(x, epsilon) {\n return this.sampleCurveY(this.solveCurveX(x, epsilon));\n};\n","// @flow\n\nimport Color from './color';\n\nexport function number(a: number, b: number, t: number) {\n return (a * (1 - t)) + (b * t);\n}\n\nexport function color(from: Color, to: Color, t: number) {\n return new Color(\n number(from.r, to.r, t),\n number(from.g, to.g, t),\n number(from.b, to.b, t),\n number(from.a, to.a, t)\n );\n}\n\nexport function array(from: Array, to: Array, t: number): Array {\n return from.map((d, i) => {\n return number(d, to[i], t);\n });\n}\n","// @flow\n\nimport Color from './color';\n\nimport {number as interpolateNumber} from './interpolate';\n\ntype LABColor = {\n l: number,\n a: number,\n b: number,\n alpha: number\n};\n\ntype HCLColor = {\n h: number,\n c: number,\n l: number,\n alpha: number\n};\n\n// Constants\nconst Xn = 0.950470, // D65 standard referent\n Yn = 1,\n Zn = 1.088830,\n t0 = 4 / 29,\n t1 = 6 / 29,\n t2 = 3 * t1 * t1,\n t3 = t1 * t1 * t1,\n deg2rad = Math.PI / 180,\n rad2deg = 180 / Math.PI;\n\n// Utilities\nfunction xyz2lab(t: number) {\n return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;\n}\n\nfunction lab2xyz(t: number) {\n return t > t1 ? t * t * t : t2 * (t - t0);\n}\n\nfunction xyz2rgb(x: number) {\n return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);\n}\n\nfunction rgb2xyz(x: number) {\n x /= 255;\n return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);\n}\n\n// LAB\nfunction rgbToLab(rgbColor: Color): LABColor {\n const b = rgb2xyz(rgbColor.r),\n a = rgb2xyz(rgbColor.g),\n l = rgb2xyz(rgbColor.b),\n x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn),\n y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.0721750 * l) / Yn),\n z = xyz2lab((0.0193339 * b + 0.1191920 * a + 0.9503041 * l) / Zn);\n\n return {\n l: 116 * y - 16,\n a: 500 * (x - y),\n b: 200 * (y - z),\n alpha: rgbColor.a\n };\n}\n\nfunction labToRgb(labColor: LABColor): Color {\n let y = (labColor.l + 16) / 116,\n x = isNaN(labColor.a) ? y : y + labColor.a / 500,\n z = isNaN(labColor.b) ? y : y - labColor.b / 200;\n y = Yn * lab2xyz(y);\n x = Xn * lab2xyz(x);\n z = Zn * lab2xyz(z);\n return new Color(\n xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z), // D65 -> sRGB\n xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z),\n xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z),\n labColor.alpha\n );\n}\n\nfunction interpolateLab(from: LABColor, to: LABColor, t: number) {\n return {\n l: interpolateNumber(from.l, to.l, t),\n a: interpolateNumber(from.a, to.a, t),\n b: interpolateNumber(from.b, to.b, t),\n alpha: interpolateNumber(from.alpha, to.alpha, t)\n };\n}\n\n// HCL\nfunction rgbToHcl(rgbColor: Color): HCLColor {\n const {l, a, b} = rgbToLab(rgbColor);\n const h = Math.atan2(b, a) * rad2deg;\n return {\n h: h < 0 ? h + 360 : h,\n c: Math.sqrt(a * a + b * b),\n l,\n alpha: rgbColor.a\n };\n}\n\nfunction hclToRgb(hclColor: HCLColor): Color {\n const h = hclColor.h * deg2rad,\n c = hclColor.c,\n l = hclColor.l;\n return labToRgb({\n l,\n a: Math.cos(h) * c,\n b: Math.sin(h) * c,\n alpha: hclColor.alpha\n });\n}\n\nfunction interpolateHue(a: number, b: number, t: number) {\n const d = b - a;\n return a + t * (d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d);\n}\n\nfunction interpolateHcl(from: HCLColor, to: HCLColor, t: number) {\n return {\n h: interpolateHue(from.h, to.h, t),\n c: interpolateNumber(from.c, to.c, t),\n l: interpolateNumber(from.l, to.l, t),\n alpha: interpolateNumber(from.alpha, to.alpha, t)\n };\n}\n\nexport const lab = {\n forward: rgbToLab,\n reverse: labToRgb,\n interpolate: interpolateLab\n};\n\nexport const hcl = {\n forward: rgbToHcl,\n reverse: hclToRgb,\n interpolate: interpolateHcl\n};\n","// @flow\n\nimport UnitBezier from '@mapbox/unitbezier';\n\nimport * as interpolate from '../../util/interpolate';\nimport {toString, NumberType, ColorType} from '../types';\nimport {findStopLessThanOrEqualTo} from '../stops';\nimport {hcl, lab} from '../../util/color_spaces';\n\nimport type {Stops} from '../stops';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nexport type InterpolationType =\n { name: 'linear' } |\n { name: 'exponential', base: number } |\n { name: 'cubic-bezier', controlPoints: [number, number, number, number] };\n\nclass Interpolate implements Expression {\n type: Type;\n\n operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab';\n interpolation: InterpolationType;\n input: Expression;\n labels: Array;\n outputs: Array;\n\n constructor(type: Type, operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab', interpolation: InterpolationType, input: Expression, stops: Stops) {\n this.type = type;\n this.operator = operator;\n this.interpolation = interpolation;\n this.input = input;\n\n this.labels = [];\n this.outputs = [];\n for (const [label, expression] of stops) {\n this.labels.push(label);\n this.outputs.push(expression);\n }\n }\n\n static interpolationFactor(interpolation: InterpolationType, input: number, lower: number, upper: number) {\n let t = 0;\n if (interpolation.name === 'exponential') {\n t = exponentialInterpolation(input, interpolation.base, lower, upper);\n } else if (interpolation.name === 'linear') {\n t = exponentialInterpolation(input, 1, lower, upper);\n } else if (interpolation.name === 'cubic-bezier') {\n const c = interpolation.controlPoints;\n const ub = new UnitBezier(c[0], c[1], c[2], c[3]);\n t = ub.solve(exponentialInterpolation(input, 1, lower, upper));\n }\n return t;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n let [operator, interpolation, input, ...rest] = args;\n\n if (!Array.isArray(interpolation) || interpolation.length === 0) {\n return context.error(`Expected an interpolation type expression.`, 1);\n }\n\n if (interpolation[0] === 'linear') {\n interpolation = {name: 'linear'};\n } else if (interpolation[0] === 'exponential') {\n const base = interpolation[1];\n if (typeof base !== 'number')\n return context.error(`Exponential interpolation requires a numeric base.`, 1, 1);\n interpolation = {\n name: 'exponential',\n base\n };\n } else if (interpolation[0] === 'cubic-bezier') {\n const controlPoints = interpolation.slice(1);\n if (\n controlPoints.length !== 4 ||\n controlPoints.some(t => typeof t !== 'number' || t < 0 || t > 1)\n ) {\n return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1);\n }\n\n interpolation = {\n name: 'cubic-bezier',\n controlPoints: (controlPoints: any)\n };\n } else {\n return context.error(`Unknown interpolation type ${String(interpolation[0])}`, 1, 0);\n }\n\n if (args.length - 1 < 4) {\n return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n }\n\n if ((args.length - 1) % 2 !== 0) {\n return context.error(`Expected an even number of arguments.`);\n }\n\n input = context.parse(input, 2, NumberType);\n if (!input) return null;\n\n const stops: Stops = [];\n\n let outputType: Type = (null: any);\n if (operator === 'interpolate-hcl' || operator === 'interpolate-lab') {\n outputType = ColorType;\n } else if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n\n for (let i = 0; i < rest.length; i += 2) {\n const label = rest[i];\n const value = rest[i + 1];\n\n const labelKey = i + 3;\n const valueKey = i + 4;\n\n if (typeof label !== 'number') {\n return context.error('Input/output pairs for \"interpolate\" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey);\n }\n\n if (stops.length && stops[stops.length - 1][0] >= label) {\n return context.error('Input/output pairs for \"interpolate\" expressions must be arranged with input values in strictly ascending order.', labelKey);\n }\n\n const parsed = context.parse(value, valueKey, outputType);\n if (!parsed) return null;\n outputType = outputType || parsed.type;\n stops.push([label, parsed]);\n }\n\n if (outputType.kind !== 'number' &&\n outputType.kind !== 'color' &&\n !(\n outputType.kind === 'array' &&\n outputType.itemType.kind === 'number' &&\n typeof outputType.N === 'number'\n )\n ) {\n return context.error(`Type ${toString(outputType)} is not interpolatable.`);\n }\n\n return new Interpolate(outputType, (operator: any), interpolation, input, stops);\n }\n\n evaluate(ctx: EvaluationContext) {\n const labels = this.labels;\n const outputs = this.outputs;\n\n if (labels.length === 1) {\n return outputs[0].evaluate(ctx);\n }\n\n const value = ((this.input.evaluate(ctx): any): number);\n if (value <= labels[0]) {\n return outputs[0].evaluate(ctx);\n }\n\n const stopCount = labels.length;\n if (value >= labels[stopCount - 1]) {\n return outputs[stopCount - 1].evaluate(ctx);\n }\n\n const index = findStopLessThanOrEqualTo(labels, value);\n const lower = labels[index];\n const upper = labels[index + 1];\n const t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper);\n\n const outputLower = outputs[index].evaluate(ctx);\n const outputUpper = outputs[index + 1].evaluate(ctx);\n\n if (this.operator === 'interpolate') {\n return (interpolate[this.type.kind.toLowerCase()]: any)(outputLower, outputUpper, t); // eslint-disable-line import/namespace\n } else if (this.operator === 'interpolate-hcl') {\n return hcl.reverse(hcl.interpolate(hcl.forward(outputLower), hcl.forward(outputUpper), t));\n } else {\n return lab.reverse(lab.interpolate(lab.forward(outputLower), lab.forward(outputUpper), t));\n }\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n for (const expression of this.outputs) {\n fn(expression);\n }\n }\n\n outputDefined(): boolean {\n return this.outputs.every(out => out.outputDefined());\n }\n\n serialize(): Array {\n let interpolation;\n if (this.interpolation.name === 'linear') {\n interpolation = [\"linear\"];\n } else if (this.interpolation.name === 'exponential') {\n if (this.interpolation.base === 1) {\n interpolation = [\"linear\"];\n } else {\n interpolation = [\"exponential\", this.interpolation.base];\n }\n } else {\n interpolation = [\"cubic-bezier\" ].concat(this.interpolation.controlPoints);\n }\n\n const serialized = [this.operator, interpolation, this.input.serialize()];\n\n for (let i = 0; i < this.labels.length; i++) {\n serialized.push(\n this.labels[i],\n this.outputs[i].serialize()\n );\n }\n return serialized;\n }\n}\n\n/**\n * Returns a ratio that can be used to interpolate between exponential function\n * stops.\n * How it works: Two consecutive stop values define a (scaled and shifted) exponential function `f(x) = a * base^x + b`, where `base` is the user-specified base,\n * and `a` and `b` are constants affording sufficient degrees of freedom to fit\n * the function to the given stops.\n *\n * Here's a bit of algebra that lets us compute `f(x)` directly from the stop\n * values without explicitly solving for `a` and `b`:\n *\n * First stop value: `f(x0) = y0 = a * base^x0 + b`\n * Second stop value: `f(x1) = y1 = a * base^x1 + b`\n * => `y1 - y0 = a(base^x1 - base^x0)`\n * => `a = (y1 - y0)/(base^x1 - base^x0)`\n *\n * Desired value: `f(x) = y = a * base^x + b`\n * => `f(x) = y0 + a * (base^x - base^x0)`\n *\n * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a\n * little algebra:\n * ```\n * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0)\n * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0)\n * ```\n *\n * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have\n * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as\n * an interpolation factor between the two stops' output values.\n *\n * (Note: a slightly different form for `ratio`,\n * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer\n * expensive `Math.pow()` operations.)\n *\n * @private\n*/\nfunction exponentialInterpolation(input, base, lowerValue, upperValue) {\n const difference = upperValue - lowerValue;\n const progress = input - lowerValue;\n\n if (difference === 0) {\n return 0;\n } else if (base === 1) {\n return progress / difference;\n } else {\n return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);\n }\n}\n\nexport default Interpolate;\n","// @flow\n\nimport assert from 'assert';\n\nimport {checkSubtype, ValueType} from '../types';\nimport ResolvedImage from '../types/resolved_image';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nclass Coalesce implements Expression {\n type: Type;\n args: Array;\n\n constructor(type: Type, args: Array) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length < 2) {\n return context.error(\"Expectected at least one argument.\");\n }\n let outputType: Type = (null: any);\n const expectedType = context.expectedType;\n if (expectedType && expectedType.kind !== 'value') {\n outputType = expectedType;\n }\n const parsedArgs = [];\n\n for (const arg of args.slice(1)) {\n const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, {typeAnnotation: 'omit'});\n if (!parsed) return null;\n outputType = outputType || parsed.type;\n parsedArgs.push(parsed);\n }\n assert(outputType);\n\n // Above, we parse arguments without inferred type annotation so that\n // they don't produce a runtime error for `null` input, which would\n // preempt the desired null-coalescing behavior.\n // Thus, if any of our arguments would have needed an annotation, we\n // need to wrap the enclosing coalesce expression with it instead.\n const needsAnnotation = expectedType &&\n parsedArgs.some(arg => checkSubtype(expectedType, arg.type));\n\n return needsAnnotation ?\n new Coalesce(ValueType, parsedArgs) :\n new Coalesce((outputType: any), parsedArgs);\n }\n\n evaluate(ctx: EvaluationContext) {\n let result = null;\n let argCount = 0;\n let requestedImageName;\n for (const arg of this.args) {\n argCount++;\n result = arg.evaluate(ctx);\n // we need to keep track of the first requested image in a coalesce statement\n // if coalesce can't find a valid image, we return the first image name so styleimagemissing can fire\n if (result && result instanceof ResolvedImage && !result.available) {\n if (!requestedImageName) {\n requestedImageName = result.name;\n }\n result = null;\n if (argCount === this.args.length) {\n result = requestedImageName;\n }\n }\n\n if (result !== null) break;\n }\n return result;\n }\n\n eachChild(fn: (_: Expression) => void) {\n this.args.forEach(fn);\n }\n\n outputDefined(): boolean {\n return this.args.every(arg => arg.outputDefined());\n }\n\n serialize() {\n const serialized = [\"coalesce\"];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Coalesce;\n","// @flow\n\nimport type {Type} from '../types';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\n\nclass Let implements Expression {\n type: Type;\n bindings: Array<[string, Expression]>;\n result: Expression;\n\n constructor(bindings: Array<[string, Expression]>, result: Expression) {\n this.type = result.type;\n this.bindings = [].concat(bindings);\n this.result = result;\n }\n\n evaluate(ctx: EvaluationContext) {\n return this.result.evaluate(ctx);\n }\n\n eachChild(fn: (_: Expression) => void) {\n for (const binding of this.bindings) {\n fn(binding[1]);\n }\n fn(this.result);\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length < 4)\n return context.error(`Expected at least 3 arguments, but found ${args.length - 1} instead.`);\n\n const bindings: Array<[string, Expression]> = [];\n for (let i = 1; i < args.length - 1; i += 2) {\n const name = args[i];\n\n if (typeof name !== 'string') {\n return context.error(`Expected string, but found ${typeof name} instead.`, i);\n }\n\n if (/[^a-zA-Z0-9_]/.test(name)) {\n return context.error(`Variable names must contain only alphanumeric characters or '_'.`, i);\n }\n\n const value = context.parse(args[i + 1], i + 1);\n if (!value) return null;\n\n bindings.push([name, value]);\n }\n\n const result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings);\n if (!result) return null;\n\n return new Let(bindings, result);\n }\n\n outputDefined() {\n return this.result.outputDefined();\n }\n\n serialize() {\n const serialized = [\"let\"];\n for (const [name, expr] of this.bindings) {\n serialized.push(name, expr.serialize());\n }\n serialized.push(this.result.serialize());\n return serialized;\n }\n}\n\nexport default Let;\n","// @flow\n\nimport {array, ValueType, NumberType} from '../types';\n\nimport RuntimeError from '../runtime_error';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type, ArrayType} from '../types';\nimport type {Value} from '../values';\n\nclass At implements Expression {\n type: Type;\n index: Expression;\n input: Expression;\n\n constructor(type: Type, index: Expression, input: Expression) {\n this.type = type;\n this.index = index;\n this.input = input;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 3)\n return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`);\n\n const index = context.parse(args[1], 1, NumberType);\n const input = context.parse(args[2], 2, array(context.expectedType || ValueType));\n\n if (!index || !input) return null;\n\n const t: ArrayType = (input.type: any);\n return new At(t.itemType, index, input);\n }\n\n evaluate(ctx: EvaluationContext) {\n const index = ((this.index.evaluate(ctx): any): number);\n const array = ((this.input.evaluate(ctx): any): Array);\n\n if (index < 0) {\n throw new RuntimeError(`Array index out of bounds: ${index} < 0.`);\n }\n\n if (index >= array.length) {\n throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`);\n }\n\n if (index !== Math.floor(index)) {\n throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`);\n }\n\n return array[index];\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.index);\n fn(this.input);\n }\n\n outputDefined() {\n return false;\n }\n\n serialize() {\n return [\"at\", this.index.serialize(), this.input.serialize()];\n }\n}\n\nexport default At;\n","// @flow\n\nimport {BooleanType, StringType, ValueType, NullType, toString, NumberType, isValidType, isValidNativeType} from '../types';\nimport RuntimeError from '../runtime_error';\nimport {typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nclass In implements Expression {\n type: Type;\n needle: Expression;\n haystack: Expression;\n\n constructor(needle: Expression, haystack: Expression) {\n this.type = BooleanType;\n this.needle = needle;\n this.haystack = haystack;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 3) {\n return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`);\n }\n\n const needle = context.parse(args[1], 1, ValueType);\n\n const haystack = context.parse(args[2], 2, ValueType);\n\n if (!needle || !haystack) return null;\n\n if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) {\n return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString(needle.type)} instead`);\n }\n\n return new In(needle, haystack);\n }\n\n evaluate(ctx: EvaluationContext) {\n const needle = (this.needle.evaluate(ctx): any);\n const haystack = (this.haystack.evaluate(ctx): any);\n\n if (!haystack) return false;\n\n if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) {\n throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString(typeOf(needle))} instead.`);\n }\n\n if (!isValidNativeType(haystack, ['string', 'array'])) {\n throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString(typeOf(haystack))} instead.`);\n }\n\n return haystack.indexOf(needle) >= 0;\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.needle);\n fn(this.haystack);\n }\n\n outputDefined() {\n return true;\n }\n\n serialize() {\n return [\"in\", this.needle.serialize(), this.haystack.serialize()];\n }\n}\n\nexport default In;\n","// @flow\n\nimport {BooleanType, StringType, ValueType, NullType, toString, NumberType, isValidType, isValidNativeType} from '../types';\nimport RuntimeError from '../runtime_error';\nimport {typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nclass IndexOf implements Expression {\n type: Type;\n needle: Expression;\n haystack: Expression;\n fromIndex: ?Expression;\n\n constructor(needle: Expression, haystack: Expression, fromIndex?: Expression) {\n this.type = NumberType;\n this.needle = needle;\n this.haystack = haystack;\n this.fromIndex = fromIndex;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length <= 2 || args.length >= 5) {\n return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`);\n }\n\n const needle = context.parse(args[1], 1, ValueType);\n\n const haystack = context.parse(args[2], 2, ValueType);\n\n if (!needle || !haystack) return null;\n if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) {\n return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString(needle.type)} instead`);\n }\n\n if (args.length === 4) {\n const fromIndex = context.parse(args[3], 3, NumberType);\n if (!fromIndex) return null;\n return new IndexOf(needle, haystack, fromIndex);\n } else {\n return new IndexOf(needle, haystack);\n }\n }\n\n evaluate(ctx: EvaluationContext) {\n const needle = (this.needle.evaluate(ctx): any);\n const haystack = (this.haystack.evaluate(ctx): any);\n\n if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) {\n throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString(typeOf(needle))} instead.`);\n }\n\n if (!isValidNativeType(haystack, ['string', 'array'])) {\n throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString(typeOf(haystack))} instead.`);\n }\n\n if (this.fromIndex) {\n const fromIndex = (this.fromIndex.evaluate(ctx): number);\n return haystack.indexOf(needle, fromIndex);\n }\n\n return haystack.indexOf(needle);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.needle);\n fn(this.haystack);\n if (this.fromIndex) {\n fn(this.fromIndex);\n }\n }\n\n outputDefined() {\n return false;\n }\n\n serialize() {\n if (this.fromIndex != null && this.fromIndex !== undefined) {\n const fromIndex = this.fromIndex.serialize();\n return [\"index-of\", this.needle.serialize(), this.haystack.serialize(), fromIndex];\n }\n return [\"index-of\", this.needle.serialize(), this.haystack.serialize()];\n }\n}\n\nexport default IndexOf;\n","// @flow\n\nimport assert from 'assert';\n\nimport {typeOf} from '../values';\nimport {ValueType, type Type} from '../types';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\n\n// Map input label values to output expression index\ntype Cases = {[number | string]: number};\n\nclass Match implements Expression {\n type: Type;\n inputType: Type;\n\n input: Expression;\n cases: Cases;\n outputs: Array;\n otherwise: Expression;\n\n constructor(inputType: Type, outputType: Type, input: Expression, cases: Cases, outputs: Array, otherwise: Expression) {\n this.inputType = inputType;\n this.type = outputType;\n this.input = input;\n this.cases = cases;\n this.outputs = outputs;\n this.otherwise = otherwise;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length < 5)\n return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n if (args.length % 2 !== 1)\n return context.error(`Expected an even number of arguments.`);\n\n let inputType;\n let outputType;\n if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n const cases = {};\n const outputs = [];\n for (let i = 2; i < args.length - 1; i += 2) {\n let labels = args[i];\n const value = args[i + 1];\n\n if (!Array.isArray(labels)) {\n labels = [labels];\n }\n\n const labelContext = context.concat(i);\n if (labels.length === 0) {\n return labelContext.error('Expected at least one branch label.');\n }\n\n for (const label of labels) {\n if (typeof label !== 'number' && typeof label !== 'string') {\n return labelContext.error(`Branch labels must be numbers or strings.`);\n } else if (typeof label === 'number' && Math.abs(label) > Number.MAX_SAFE_INTEGER) {\n return labelContext.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);\n\n } else if (typeof label === 'number' && Math.floor(label) !== label) {\n return labelContext.error(`Numeric branch labels must be integer values.`);\n\n } else if (!inputType) {\n inputType = typeOf(label);\n } else if (labelContext.checkSubtype(inputType, typeOf(label))) {\n return null;\n }\n\n if (typeof cases[String(label)] !== 'undefined') {\n return labelContext.error('Branch labels must be unique.');\n }\n\n cases[String(label)] = outputs.length;\n }\n\n const result = context.parse(value, i, outputType);\n if (!result) return null;\n outputType = outputType || result.type;\n outputs.push(result);\n }\n\n const input = context.parse(args[1], 1, ValueType);\n if (!input) return null;\n\n const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);\n if (!otherwise) return null;\n\n assert(inputType && outputType);\n\n if (input.type.kind !== 'value' && context.concat(1).checkSubtype((inputType: any), input.type)) {\n return null;\n }\n\n return new Match((inputType: any), (outputType: any), input, cases, outputs, otherwise);\n }\n\n evaluate(ctx: EvaluationContext) {\n const input = (this.input.evaluate(ctx): any);\n const output = (typeOf(input) === this.inputType && this.outputs[this.cases[input]]) || this.otherwise;\n return output.evaluate(ctx);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n this.outputs.forEach(fn);\n fn(this.otherwise);\n }\n\n outputDefined(): boolean {\n return this.outputs.every(out => out.outputDefined()) && this.otherwise.outputDefined();\n }\n\n serialize(): Array {\n const serialized = [\"match\", this.input.serialize()];\n\n // Sort so serialization has an arbitrary defined order, even though\n // branch order doesn't affect evaluation\n const sortedLabels = Object.keys(this.cases).sort();\n\n // Group branches by unique match expression to support condensed\n // serializations of the form [case1, case2, ...] -> matchExpression\n const groupedByOutput: Array<[number, Array]> = [];\n const outputLookup: {[index: number]: number} = {}; // lookup index into groupedByOutput for a given output expression\n for (const label of sortedLabels) {\n const outputIndex = outputLookup[this.cases[label]];\n if (outputIndex === undefined) {\n // First time seeing this output, add it to the end of the grouped list\n outputLookup[this.cases[label]] = groupedByOutput.length;\n groupedByOutput.push([this.cases[label], [label]]);\n } else {\n // We've seen this expression before, add the label to that output's group\n groupedByOutput[outputIndex][1].push(label);\n }\n }\n\n const coerceLabel = (label) => this.inputType.kind === 'number' ? Number(label) : label;\n\n for (const [outputIndex, labels] of groupedByOutput) {\n if (labels.length === 1) {\n // Only a single label matches this output expression\n serialized.push(coerceLabel(labels[0]));\n } else {\n // Array of literal labels pointing to this output expression\n serialized.push(labels.map(coerceLabel));\n }\n serialized.push(this.outputs[outputIndex].serialize());\n }\n serialized.push(this.otherwise.serialize());\n return serialized;\n }\n}\n\nexport default Match;\n","// @flow\n\nimport assert from 'assert';\n\nimport {BooleanType} from '../types';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\ntype Branches = Array<[Expression, Expression]>;\n\nclass Case implements Expression {\n type: Type;\n\n branches: Branches;\n otherwise: Expression;\n\n constructor(type: Type, branches: Branches, otherwise: Expression) {\n this.type = type;\n this.branches = branches;\n this.otherwise = otherwise;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length < 4)\n return context.error(`Expected at least 3 arguments, but found only ${args.length - 1}.`);\n if (args.length % 2 !== 0)\n return context.error(`Expected an odd number of arguments.`);\n\n let outputType: ?Type;\n if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n\n const branches = [];\n for (let i = 1; i < args.length - 1; i += 2) {\n const test = context.parse(args[i], i, BooleanType);\n if (!test) return null;\n\n const result = context.parse(args[i + 1], i + 1, outputType);\n if (!result) return null;\n\n branches.push([test, result]);\n\n outputType = outputType || result.type;\n }\n\n const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);\n if (!otherwise) return null;\n\n assert(outputType);\n return new Case((outputType: any), branches, otherwise);\n }\n\n evaluate(ctx: EvaluationContext) {\n for (const [test, expression] of this.branches) {\n if (test.evaluate(ctx)) {\n return expression.evaluate(ctx);\n }\n }\n return this.otherwise.evaluate(ctx);\n }\n\n eachChild(fn: (_: Expression) => void) {\n for (const [test, expression] of this.branches) {\n fn(test);\n fn(expression);\n }\n fn(this.otherwise);\n }\n\n outputDefined(): boolean {\n return this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined();\n }\n\n serialize() {\n const serialized = [\"case\"];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Case;\n","// @flow\n\nimport {ValueType, NumberType, StringType, array, toString, isValidType, isValidNativeType} from '../types';\nimport RuntimeError from '../runtime_error';\nimport {typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nclass Slice implements Expression {\n type: Type;\n input: Expression;\n beginIndex: Expression;\n endIndex: ?Expression;\n\n constructor(type: Type, input: Expression, beginIndex: Expression, endIndex?: Expression) {\n this.type = type;\n this.input = input;\n this.beginIndex = beginIndex;\n this.endIndex = endIndex;\n\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length <= 2 || args.length >= 5) {\n return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`);\n }\n\n const input = context.parse(args[1], 1, ValueType);\n const beginIndex = context.parse(args[2], 2, NumberType);\n\n if (!input || !beginIndex) return null;\n\n if (!isValidType(input.type, [array(ValueType), StringType, ValueType])) {\n return context.error(`Expected first argument to be of type array or string, but found ${toString(input.type)} instead`);\n }\n\n if (args.length === 4) {\n const endIndex = context.parse(args[3], 3, NumberType);\n if (!endIndex) return null;\n return new Slice(input.type, input, beginIndex, endIndex);\n } else {\n return new Slice(input.type, input, beginIndex);\n }\n }\n\n evaluate(ctx: EvaluationContext) {\n const input = (this.input.evaluate(ctx): any);\n const beginIndex = (this.beginIndex.evaluate(ctx): number);\n\n if (!isValidNativeType(input, ['string', 'array'])) {\n throw new RuntimeError(`Expected first argument to be of type array or string, but found ${toString(typeOf(input))} instead.`);\n }\n\n if (this.endIndex) {\n const endIndex = (this.endIndex.evaluate(ctx): number);\n return input.slice(beginIndex, endIndex);\n }\n\n return input.slice(beginIndex);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n fn(this.beginIndex);\n if (this.endIndex) {\n fn(this.endIndex);\n }\n }\n\n outputDefined() {\n return false;\n }\n\n serialize() {\n if (this.endIndex != null && this.endIndex !== undefined) {\n const endIndex = this.endIndex.serialize();\n return [\"slice\", this.input.serialize(), this.beginIndex.serialize(), endIndex];\n }\n return [\"slice\", this.input.serialize(), this.beginIndex.serialize()];\n }\n}\n\nexport default Slice;\n","// @flow\n\nimport {toString, ValueType, BooleanType, CollatorType} from '../types';\nimport Assertion from './assertion';\nimport {typeOf} from '../values';\nimport RuntimeError from '../runtime_error';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\n\ntype ComparisonOperator = '==' | '!=' | '<' | '>' | '<=' | '>=' ;\n\nfunction isComparableType(op: ComparisonOperator, type: Type) {\n if (op === '==' || op === '!=') {\n // equality operator\n return type.kind === 'boolean' ||\n type.kind === 'string' ||\n type.kind === 'number' ||\n type.kind === 'null' ||\n type.kind === 'value';\n } else {\n // ordering operator\n return type.kind === 'string' ||\n type.kind === 'number' ||\n type.kind === 'value';\n }\n}\n\nfunction eq(ctx, a, b) { return a === b; }\nfunction neq(ctx, a, b) { return a !== b; }\nfunction lt(ctx, a, b) { return a < b; }\nfunction gt(ctx, a, b) { return a > b; }\nfunction lteq(ctx, a, b) { return a <= b; }\nfunction gteq(ctx, a, b) { return a >= b; }\n\nfunction eqCollate(ctx, a, b, c) { return c.compare(a, b) === 0; }\nfunction neqCollate(ctx, a, b, c) { return !eqCollate(ctx, a, b, c); }\nfunction ltCollate(ctx, a, b, c) { return c.compare(a, b) < 0; }\nfunction gtCollate(ctx, a, b, c) { return c.compare(a, b) > 0; }\nfunction lteqCollate(ctx, a, b, c) { return c.compare(a, b) <= 0; }\nfunction gteqCollate(ctx, a, b, c) { return c.compare(a, b) >= 0; }\n\n/**\n * Special form for comparison operators, implementing the signatures:\n * - (T, T, ?Collator) => boolean\n * - (T, value, ?Collator) => boolean\n * - (value, T, ?Collator) => boolean\n *\n * For inequalities, T must be either value, string, or number. For ==/!=, it\n * can also be boolean or null.\n *\n * Equality semantics are equivalent to Javascript's strict equality (===/!==)\n * -- i.e., when the arguments' types don't match, == evaluates to false, != to\n * true.\n *\n * When types don't match in an ordering comparison, a runtime error is thrown.\n *\n * @private\n */\nfunction makeComparison(op: ComparisonOperator, compareBasic, compareWithCollator) {\n const isOrderComparison = op !== '==' && op !== '!=';\n\n return class Comparison implements Expression {\n type: Type;\n lhs: Expression;\n rhs: Expression;\n collator: ?Expression;\n hasUntypedArgument: boolean;\n\n constructor(lhs: Expression, rhs: Expression, collator: ?Expression) {\n this.type = BooleanType;\n this.lhs = lhs;\n this.rhs = rhs;\n this.collator = collator;\n this.hasUntypedArgument = lhs.type.kind === 'value' || rhs.type.kind === 'value';\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length !== 3 && args.length !== 4)\n return context.error(`Expected two or three arguments.`);\n\n const op: ComparisonOperator = (args[0]: any);\n\n let lhs = context.parse(args[1], 1, ValueType);\n if (!lhs) return null;\n if (!isComparableType(op, lhs.type)) {\n return context.concat(1).error(`\"${op}\" comparisons are not supported for type '${toString(lhs.type)}'.`);\n }\n let rhs = context.parse(args[2], 2, ValueType);\n if (!rhs) return null;\n if (!isComparableType(op, rhs.type)) {\n return context.concat(2).error(`\"${op}\" comparisons are not supported for type '${toString(rhs.type)}'.`);\n }\n\n if (\n lhs.type.kind !== rhs.type.kind &&\n lhs.type.kind !== 'value' &&\n rhs.type.kind !== 'value'\n ) {\n return context.error(`Cannot compare types '${toString(lhs.type)}' and '${toString(rhs.type)}'.`);\n }\n\n if (isOrderComparison) {\n // typing rules specific to less/greater than operators\n if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') {\n // (value, T)\n lhs = new Assertion(rhs.type, [lhs]);\n } else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') {\n // (T, value)\n rhs = new Assertion(lhs.type, [rhs]);\n }\n }\n\n let collator = null;\n if (args.length === 4) {\n if (\n lhs.type.kind !== 'string' &&\n rhs.type.kind !== 'string' &&\n lhs.type.kind !== 'value' &&\n rhs.type.kind !== 'value'\n ) {\n return context.error(`Cannot use collator to compare non-string types.`);\n }\n collator = context.parse(args[3], 3, CollatorType);\n if (!collator) return null;\n }\n\n return new Comparison(lhs, rhs, collator);\n }\n\n evaluate(ctx: EvaluationContext) {\n const lhs = this.lhs.evaluate(ctx);\n const rhs = this.rhs.evaluate(ctx);\n\n if (isOrderComparison && this.hasUntypedArgument) {\n const lt = typeOf(lhs);\n const rt = typeOf(rhs);\n // check that type is string or number, and equal\n if (lt.kind !== rt.kind || !(lt.kind === 'string' || lt.kind === 'number')) {\n throw new RuntimeError(`Expected arguments for \"${op}\" to be (string, string) or (number, number), but found (${lt.kind}, ${rt.kind}) instead.`);\n }\n }\n\n if (this.collator && !isOrderComparison && this.hasUntypedArgument) {\n const lt = typeOf(lhs);\n const rt = typeOf(rhs);\n if (lt.kind !== 'string' || rt.kind !== 'string') {\n return compareBasic(ctx, lhs, rhs);\n }\n }\n\n return this.collator ?\n compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) :\n compareBasic(ctx, lhs, rhs);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.lhs);\n fn(this.rhs);\n if (this.collator) {\n fn(this.collator);\n }\n }\n\n outputDefined(): boolean {\n return true;\n }\n\n serialize() {\n const serialized = [op];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n };\n}\n\nexport const Equals = makeComparison('==', eq, eqCollate);\nexport const NotEquals = makeComparison('!=', neq, neqCollate);\nexport const LessThan = makeComparison('<', lt, ltCollate);\nexport const GreaterThan = makeComparison('>', gt, gtCollate);\nexport const LessThanOrEqual = makeComparison('<=', lteq, lteqCollate);\nexport const GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate);\n","// @flow\n\nimport {StringType, NumberType} from '../types';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\n\ndeclare var Intl: {\n NumberFormat: Class\n};\n\ndeclare class Intl$NumberFormat {\n constructor (\n locales?: string | string[],\n options?: NumberFormatOptions\n ): Intl$NumberFormat;\n\n static (\n locales?: string | string[],\n options?: NumberFormatOptions\n ): Intl$NumberFormat;\n\n format(a: number): string;\n\n resolvedOptions(): any;\n}\n\ntype NumberFormatOptions = {\n style?: 'decimal' | 'currency' | 'percent';\n currency?: null | string;\n minimumFractionDigits?: null | string;\n maximumFractionDigits?: null | string;\n};\n\nexport default class NumberFormat implements Expression {\n type: Type;\n number: Expression;\n locale: Expression | null; // BCP 47 language tag\n currency: Expression | null; // ISO 4217 currency code, required if style=currency\n minFractionDigits: Expression | null; // Default 0\n maxFractionDigits: Expression | null; // Default 3\n\n constructor(number: Expression,\n locale: Expression | null,\n currency: Expression | null,\n minFractionDigits: Expression | null,\n maxFractionDigits: Expression | null) {\n this.type = StringType;\n this.number = number;\n this.locale = locale;\n this.currency = currency;\n this.minFractionDigits = minFractionDigits;\n this.maxFractionDigits = maxFractionDigits;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length !== 3)\n return context.error(`Expected two arguments.`);\n\n const number = context.parse(args[1], 1, NumberType);\n if (!number) return null;\n\n const options = (args[2]: any);\n if (typeof options !== \"object\" || Array.isArray(options))\n return context.error(`NumberFormat options argument must be an object.`);\n\n let locale = null;\n if (options['locale']) {\n locale = context.parse(options['locale'], 1, StringType);\n if (!locale) return null;\n }\n\n let currency = null;\n if (options['currency']) {\n currency = context.parse(options['currency'], 1, StringType);\n if (!currency) return null;\n }\n\n let minFractionDigits = null;\n if (options['min-fraction-digits']) {\n minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType);\n if (!minFractionDigits) return null;\n }\n\n let maxFractionDigits = null;\n if (options['max-fraction-digits']) {\n maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType);\n if (!maxFractionDigits) return null;\n }\n\n return new NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits);\n }\n\n evaluate(ctx: EvaluationContext) {\n return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [],\n {\n style: this.currency ? \"currency\" : \"decimal\",\n currency: this.currency ? this.currency.evaluate(ctx) : undefined,\n minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : undefined,\n maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : undefined,\n }).format(this.number.evaluate(ctx));\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.number);\n if (this.locale) {\n fn(this.locale);\n }\n if (this.currency) {\n fn(this.currency);\n }\n if (this.minFractionDigits) {\n fn(this.minFractionDigits);\n }\n if (this.maxFractionDigits) {\n fn(this.maxFractionDigits);\n }\n }\n\n outputDefined() {\n return false;\n }\n\n serialize() {\n const options = {};\n if (this.locale) {\n options['locale'] = this.locale.serialize();\n }\n if (this.currency) {\n options['currency'] = this.currency.serialize();\n }\n if (this.minFractionDigits) {\n options['min-fraction-digits'] = this.minFractionDigits.serialize();\n }\n if (this.maxFractionDigits) {\n options['max-fraction-digits'] = this.maxFractionDigits.serialize();\n }\n return [\"number-format\", this.number.serialize(), options];\n }\n}\n","// @flow\n\nimport {NumberType, toString} from '../types';\n\nimport {typeOf} from '../values';\nimport RuntimeError from '../runtime_error';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nclass Length implements Expression {\n type: Type;\n input: Expression;\n\n constructor(input: Expression) {\n this.type = NumberType;\n this.input = input;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 2)\n return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`);\n\n const input = context.parse(args[1], 1);\n if (!input) return null;\n\n if (input.type.kind !== 'array' && input.type.kind !== 'string' && input.type.kind !== 'value')\n return context.error(`Expected argument of type string or array, but found ${toString(input.type)} instead.`);\n\n return new Length(input);\n }\n\n evaluate(ctx: EvaluationContext) {\n const input = this.input.evaluate(ctx);\n if (typeof input === 'string') {\n return input.length;\n } else if (Array.isArray(input)) {\n return input.length;\n } else {\n throw new RuntimeError(`Expected value to be of type string or array, but found ${toString(typeOf(input))} instead.`);\n }\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n }\n\n outputDefined() {\n return false;\n }\n\n serialize() {\n const serialized = [\"length\"];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Length;\n","// @flow\n\nimport {\n type Type,\n NumberType,\n StringType,\n BooleanType,\n ColorType,\n ObjectType,\n ValueType,\n ErrorType,\n CollatorType,\n array,\n toString as typeToString\n} from '../types';\n\nimport {typeOf, Color, validateRGBA, toString as valueToString} from '../values';\nimport CompoundExpression from '../compound_expression';\nimport RuntimeError from '../runtime_error';\nimport Let from './let';\nimport Var from './var';\nimport Literal from './literal';\nimport Assertion from './assertion';\nimport Coercion from './coercion';\nimport At from './at';\nimport In from './in';\nimport IndexOf from './index_of';\nimport Match from './match';\nimport Case from './case';\nimport Slice from './slice';\nimport Step from './step';\nimport Interpolate from './interpolate';\nimport Coalesce from './coalesce';\nimport {\n Equals,\n NotEquals,\n LessThan,\n GreaterThan,\n LessThanOrEqual,\n GreaterThanOrEqual\n} from './comparison';\nimport CollatorExpression from './collator';\nimport NumberFormat from './number_format';\nimport FormatExpression from './format';\nimport ImageExpression from './image';\nimport Length from './length';\nimport Within from './within';\n\nimport type {Varargs} from '../compound_expression';\nimport type {ExpressionRegistry} from '../expression';\n\nconst expressions: ExpressionRegistry = {\n // special forms\n '==': Equals,\n '!=': NotEquals,\n '>': GreaterThan,\n '<': LessThan,\n '>=': GreaterThanOrEqual,\n '<=': LessThanOrEqual,\n 'array': Assertion,\n 'at': At,\n 'boolean': Assertion,\n 'case': Case,\n 'coalesce': Coalesce,\n 'collator': CollatorExpression,\n 'format': FormatExpression,\n 'image': ImageExpression,\n 'in': In,\n 'index-of': IndexOf,\n 'interpolate': Interpolate,\n 'interpolate-hcl': Interpolate,\n 'interpolate-lab': Interpolate,\n 'length': Length,\n 'let': Let,\n 'literal': Literal,\n 'match': Match,\n 'number': Assertion,\n 'number-format': NumberFormat,\n 'object': Assertion,\n 'slice': Slice,\n 'step': Step,\n 'string': Assertion,\n 'to-boolean': Coercion,\n 'to-color': Coercion,\n 'to-number': Coercion,\n 'to-string': Coercion,\n 'var': Var,\n 'within': Within\n};\n\nfunction rgba(ctx, [r, g, b, a]) {\n r = r.evaluate(ctx);\n g = g.evaluate(ctx);\n b = b.evaluate(ctx);\n const alpha = a ? a.evaluate(ctx) : 1;\n const error = validateRGBA(r, g, b, alpha);\n if (error) throw new RuntimeError(error);\n return new Color(r / 255 * alpha, g / 255 * alpha, b / 255 * alpha, alpha);\n}\n\nfunction has(key, obj) {\n return key in obj;\n}\n\nfunction get(key, obj) {\n const v = obj[key];\n return typeof v === 'undefined' ? null : v;\n}\n\nfunction binarySearch(v, a, i, j) {\n while (i <= j) {\n const m = (i + j) >> 1;\n if (a[m] === v)\n return true;\n if (a[m] > v)\n j = m - 1;\n else\n i = m + 1;\n }\n return false;\n}\n\nfunction varargs(type: Type): Varargs {\n return {type};\n}\n\nCompoundExpression.register(expressions, {\n 'error': [\n ErrorType,\n [StringType],\n (ctx, [v]) => { throw new RuntimeError(v.evaluate(ctx)); }\n ],\n 'typeof': [\n StringType,\n [ValueType],\n (ctx, [v]) => typeToString(typeOf(v.evaluate(ctx)))\n ],\n 'to-rgba': [\n array(NumberType, 4),\n [ColorType],\n (ctx, [v]) => {\n return v.evaluate(ctx).toArray();\n }\n ],\n 'rgb': [\n ColorType,\n [NumberType, NumberType, NumberType],\n rgba\n ],\n 'rgba': [\n ColorType,\n [NumberType, NumberType, NumberType, NumberType],\n rgba\n ],\n 'has': {\n type: BooleanType,\n overloads: [\n [\n [StringType],\n (ctx, [key]) => has(key.evaluate(ctx), ctx.properties())\n ], [\n [StringType, ObjectType],\n (ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx))\n ]\n ]\n },\n 'get': {\n type: ValueType,\n overloads: [\n [\n [StringType],\n (ctx, [key]) => get(key.evaluate(ctx), ctx.properties())\n ], [\n [StringType, ObjectType],\n (ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx))\n ]\n ]\n },\n 'feature-state': [\n ValueType,\n [StringType],\n (ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {})\n ],\n 'properties': [\n ObjectType,\n [],\n (ctx) => ctx.properties()\n ],\n 'geometry-type': [\n StringType,\n [],\n (ctx) => ctx.geometryType()\n ],\n 'id': [\n ValueType,\n [],\n (ctx) => ctx.id()\n ],\n 'zoom': [\n NumberType,\n [],\n (ctx) => ctx.globals.zoom\n ],\n 'heatmap-density': [\n NumberType,\n [],\n (ctx) => ctx.globals.heatmapDensity || 0\n ],\n 'line-progress': [\n NumberType,\n [],\n (ctx) => ctx.globals.lineProgress || 0\n ],\n 'accumulated': [\n ValueType,\n [],\n (ctx) => ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated\n ],\n '+': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => {\n let result = 0;\n for (const arg of args) {\n result += arg.evaluate(ctx);\n }\n return result;\n }\n ],\n '*': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => {\n let result = 1;\n for (const arg of args) {\n result *= arg.evaluate(ctx);\n }\n return result;\n }\n ],\n '-': {\n type: NumberType,\n overloads: [\n [\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx)\n ], [\n [NumberType],\n (ctx, [a]) => -a.evaluate(ctx)\n ]\n ]\n },\n '/': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx)\n ],\n '%': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx)\n ],\n 'ln2': [\n NumberType,\n [],\n () => Math.LN2\n ],\n 'pi': [\n NumberType,\n [],\n () => Math.PI\n ],\n 'e': [\n NumberType,\n [],\n () => Math.E\n ],\n '^': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx))\n ],\n 'sqrt': [\n NumberType,\n [NumberType],\n (ctx, [x]) => Math.sqrt(x.evaluate(ctx))\n ],\n 'log10': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10\n ],\n 'ln': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx))\n ],\n 'log2': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2\n ],\n 'sin': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.sin(n.evaluate(ctx))\n ],\n 'cos': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.cos(n.evaluate(ctx))\n ],\n 'tan': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.tan(n.evaluate(ctx))\n ],\n 'asin': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.asin(n.evaluate(ctx))\n ],\n 'acos': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.acos(n.evaluate(ctx))\n ],\n 'atan': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.atan(n.evaluate(ctx))\n ],\n 'min': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => Math.min(...args.map(arg => arg.evaluate(ctx)))\n ],\n 'max': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => Math.max(...args.map(arg => arg.evaluate(ctx)))\n ],\n 'abs': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.abs(n.evaluate(ctx))\n ],\n 'round': [\n NumberType,\n [NumberType],\n (ctx, [n]) => {\n const v = n.evaluate(ctx);\n // Javascript's Math.round() rounds towards +Infinity for halfway\n // values, even when they're negative. It's more common to round\n // away from 0 (e.g., this is what python and C++ do)\n return v < 0 ? -Math.round(-v) : Math.round(v);\n }\n ],\n 'floor': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.floor(n.evaluate(ctx))\n ],\n 'ceil': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.ceil(n.evaluate(ctx))\n ],\n 'filter-==': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => ctx.properties()[(k: any).value] === (v: any).value\n ],\n 'filter-id-==': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => ctx.id() === (v: any).value\n ],\n 'filter-type-==': [\n BooleanType,\n [StringType],\n (ctx, [v]) => ctx.geometryType() === (v: any).value\n ],\n 'filter-<': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a < b;\n }\n ],\n 'filter-id-<': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a < b;\n }\n ],\n 'filter->': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a > b;\n }\n ],\n 'filter-id->': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a > b;\n }\n ],\n 'filter-<=': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a <= b;\n }\n ],\n 'filter-id-<=': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a <= b;\n }\n ],\n 'filter->=': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a >= b;\n }\n ],\n 'filter-id->=': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a >= b;\n }\n ],\n 'filter-has': [\n BooleanType,\n [ValueType],\n (ctx, [k]) => (k: any).value in ctx.properties()\n ],\n 'filter-has-id': [\n BooleanType,\n [],\n (ctx) => (ctx.id() !== null && ctx.id() !== undefined)\n ],\n 'filter-type-in': [\n BooleanType,\n [array(StringType)],\n (ctx, [v]) => (v: any).value.indexOf(ctx.geometryType()) >= 0\n ],\n 'filter-id-in': [\n BooleanType,\n [array(ValueType)],\n (ctx, [v]) => (v: any).value.indexOf(ctx.id()) >= 0\n ],\n 'filter-in-small': [\n BooleanType,\n [StringType, array(ValueType)],\n // assumes v is an array literal\n (ctx, [k, v]) => (v: any).value.indexOf(ctx.properties()[(k: any).value]) >= 0\n ],\n 'filter-in-large': [\n BooleanType,\n [StringType, array(ValueType)],\n // assumes v is a array literal with values sorted in ascending order and of a single type\n (ctx, [k, v]) => binarySearch(ctx.properties()[(k: any).value], (v: any).value, 0, (v: any).value.length - 1)\n ],\n 'all': {\n type: BooleanType,\n overloads: [\n [\n [BooleanType, BooleanType],\n (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx)\n ],\n [\n varargs(BooleanType),\n (ctx, args) => {\n for (const arg of args) {\n if (!arg.evaluate(ctx))\n return false;\n }\n return true;\n }\n ]\n ]\n },\n 'any': {\n type: BooleanType,\n overloads: [\n [\n [BooleanType, BooleanType],\n (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx)\n ],\n [\n varargs(BooleanType),\n (ctx, args) => {\n for (const arg of args) {\n if (arg.evaluate(ctx))\n return true;\n }\n return false;\n }\n ]\n ]\n },\n '!': [\n BooleanType,\n [BooleanType],\n (ctx, [b]) => !b.evaluate(ctx)\n ],\n 'is-supported-script': [\n BooleanType,\n [StringType],\n // At parse time this will always return true, so we need to exclude this expression with isGlobalPropertyConstant\n (ctx, [s]) => {\n const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript;\n if (isSupportedScript) {\n return isSupportedScript(s.evaluate(ctx));\n }\n return true;\n }\n ],\n 'upcase': [\n StringType,\n [StringType],\n (ctx, [s]) => s.evaluate(ctx).toUpperCase()\n ],\n 'downcase': [\n StringType,\n [StringType],\n (ctx, [s]) => s.evaluate(ctx).toLowerCase()\n ],\n 'concat': [\n StringType,\n varargs(ValueType),\n (ctx, args) => args.map(arg => valueToString(arg.evaluate(ctx))).join('')\n ],\n 'resolved-locale': [\n StringType,\n [CollatorType],\n (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale()\n ]\n});\n\nexport default expressions;\n","// @flow\n\n/**\n * A type used for returning and propagating errors. The first element of the union\n * represents success and contains a value, and the second represents an error and\n * contains an error value.\n * @private\n */\nexport type Result =\n | {| result: 'success', value: T |}\n | {| result: 'error', value: E |};\n\nexport function success(value: T): Result {\n return {result: 'success', value};\n}\n\nexport function error(value: E): Result {\n return {result: 'error', value};\n}\n","// @flow\n\nimport type {StylePropertySpecification} from '../style-spec';\n\nexport function supportsPropertyExpression(spec: StylePropertySpecification): boolean {\n return spec['property-type'] === 'data-driven' || spec['property-type'] === 'cross-faded-data-driven';\n}\n\nexport function supportsZoomExpression(spec: StylePropertySpecification): boolean {\n return !!spec.expression && spec.expression.parameters.indexOf('zoom') > -1;\n}\n\nexport function supportsInterpolation(spec: StylePropertySpecification): boolean {\n return !!spec.expression && spec.expression.interpolated;\n}\n","// @flow\n\nexport default function getType(val: mixed): string {\n if (val instanceof Number) {\n return 'number';\n } else if (val instanceof String) {\n return 'string';\n } else if (val instanceof Boolean) {\n return 'boolean';\n } else if (Array.isArray(val)) {\n return 'array';\n } else if (val === null) {\n return 'null';\n } else {\n return typeof val;\n }\n}\n","\nimport * as colorSpaces from '../util/color_spaces';\nimport Color from '../util/color';\nimport extend from '../util/extend';\nimport getType from '../util/get_type';\nimport * as interpolate from '../util/interpolate';\nimport Interpolate from '../expression/definitions/interpolate';\nimport Formatted from '../expression/types/formatted';\nimport ResolvedImage from '../expression/types/resolved_image';\nimport {supportsInterpolation} from '../util/properties';\nimport {findStopLessThanOrEqualTo} from '../expression/stops';\n\nexport function isFunction(value) {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction identityFunction(x) {\n return x;\n}\n\nexport function createFunction(parameters, propertySpec) {\n const isColor = propertySpec.type === 'color';\n const zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === 'object';\n const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined;\n const zoomDependent = zoomAndFeatureDependent || !featureDependent;\n const type = parameters.type || (supportsInterpolation(propertySpec) ? 'exponential' : 'interval');\n\n if (isColor) {\n parameters = extend({}, parameters);\n\n if (parameters.stops) {\n parameters.stops = parameters.stops.map((stop) => {\n return [stop[0], Color.parse(stop[1])];\n });\n }\n\n if (parameters.default) {\n parameters.default = Color.parse(parameters.default);\n } else {\n parameters.default = Color.parse(propertySpec.default);\n }\n }\n\n if (parameters.colorSpace && parameters.colorSpace !== 'rgb' && !colorSpaces[parameters.colorSpace]) { // eslint-disable-line import/namespace\n throw new Error(`Unknown color space: ${parameters.colorSpace}`);\n }\n\n let innerFun;\n let hashedStops;\n let categoricalKeyType;\n if (type === 'exponential') {\n innerFun = evaluateExponentialFunction;\n } else if (type === 'interval') {\n innerFun = evaluateIntervalFunction;\n } else if (type === 'categorical') {\n innerFun = evaluateCategoricalFunction;\n\n // For categorical functions, generate an Object as a hashmap of the stops for fast searching\n hashedStops = Object.create(null);\n for (const stop of parameters.stops) {\n hashedStops[stop[0]] = stop[1];\n }\n\n // Infer key type based on first stop key-- used to encforce strict type checking later\n categoricalKeyType = typeof parameters.stops[0][0];\n\n } else if (type === 'identity') {\n innerFun = evaluateIdentityFunction;\n } else {\n throw new Error(`Unknown function type \"${type}\"`);\n }\n\n if (zoomAndFeatureDependent) {\n const featureFunctions = {};\n const zoomStops = [];\n for (let s = 0; s < parameters.stops.length; s++) {\n const stop = parameters.stops[s];\n const zoom = stop[0].zoom;\n if (featureFunctions[zoom] === undefined) {\n featureFunctions[zoom] = {\n zoom,\n type: parameters.type,\n property: parameters.property,\n default: parameters.default,\n stops: []\n };\n zoomStops.push(zoom);\n }\n featureFunctions[zoom].stops.push([stop[0].value, stop[1]]);\n }\n\n const featureFunctionStops = [];\n for (const z of zoomStops) {\n featureFunctionStops.push([featureFunctions[z].zoom, createFunction(featureFunctions[z], propertySpec)]);\n }\n\n const interpolationType = {name: 'linear'};\n return {\n kind: 'composite',\n interpolationType,\n interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType),\n zoomStops: featureFunctionStops.map(s => s[0]),\n evaluate({zoom}, properties) {\n return evaluateExponentialFunction({\n stops: featureFunctionStops,\n base: parameters.base\n }, propertySpec, zoom).evaluate(zoom, properties);\n }\n };\n } else if (zoomDependent) {\n const interpolationType = type === 'exponential' ?\n {name: 'exponential', base: parameters.base !== undefined ? parameters.base : 1} : null;\n return {\n kind: 'camera',\n interpolationType,\n interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType),\n zoomStops: parameters.stops.map(s => s[0]),\n evaluate: ({zoom}) => innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType)\n };\n } else {\n return {\n kind: 'source',\n evaluate(_, feature) {\n const value = feature && feature.properties ? feature.properties[parameters.property] : undefined;\n if (value === undefined) {\n return coalesce(parameters.default, propertySpec.default);\n }\n return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType);\n }\n };\n }\n}\n\nfunction coalesce(a, b, c) {\n if (a !== undefined) return a;\n if (b !== undefined) return b;\n if (c !== undefined) return c;\n}\n\nfunction evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) {\n const evaluated = typeof input === keyType ? hashedStops[input] : undefined; // Enforce strict typing on input\n return coalesce(evaluated, parameters.default, propertySpec.default);\n}\n\nfunction evaluateIntervalFunction(parameters, propertySpec, input) {\n // Edge cases\n if (getType(input) !== 'number') return coalesce(parameters.default, propertySpec.default);\n const n = parameters.stops.length;\n if (n === 1) return parameters.stops[0][1];\n if (input <= parameters.stops[0][0]) return parameters.stops[0][1];\n if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1];\n\n const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input);\n\n return parameters.stops[index][1];\n}\n\nfunction evaluateExponentialFunction(parameters, propertySpec, input) {\n const base = parameters.base !== undefined ? parameters.base : 1;\n\n // Edge cases\n if (getType(input) !== 'number') return coalesce(parameters.default, propertySpec.default);\n const n = parameters.stops.length;\n if (n === 1) return parameters.stops[0][1];\n if (input <= parameters.stops[0][0]) return parameters.stops[0][1];\n if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1];\n\n const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input);\n const t = interpolationFactor(\n input, base,\n parameters.stops[index][0],\n parameters.stops[index + 1][0]);\n\n const outputLower = parameters.stops[index][1];\n const outputUpper = parameters.stops[index + 1][1];\n let interp = interpolate[propertySpec.type] || identityFunction; // eslint-disable-line import/namespace\n\n if (parameters.colorSpace && parameters.colorSpace !== 'rgb') {\n const colorspace = colorSpaces[parameters.colorSpace]; // eslint-disable-line import/namespace\n interp = (a, b) => colorspace.reverse(colorspace.interpolate(colorspace.forward(a), colorspace.forward(b), t));\n }\n\n if (typeof outputLower.evaluate === 'function') {\n return {\n evaluate(...args) {\n const evaluatedLower = outputLower.evaluate.apply(undefined, args);\n const evaluatedUpper = outputUpper.evaluate.apply(undefined, args);\n // Special case for fill-outline-color, which has no spec default.\n if (evaluatedLower === undefined || evaluatedUpper === undefined) {\n return undefined;\n }\n return interp(evaluatedLower, evaluatedUpper, t);\n }\n };\n }\n\n return interp(outputLower, outputUpper, t);\n}\n\nfunction evaluateIdentityFunction(parameters, propertySpec, input) {\n if (propertySpec.type === 'color') {\n input = Color.parse(input);\n } else if (propertySpec.type === 'formatted') {\n input = Formatted.fromString(input.toString());\n } else if (propertySpec.type === 'resolvedImage') {\n input = ResolvedImage.fromString(input.toString());\n } else if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) {\n input = undefined;\n }\n return coalesce(input, parameters.default, propertySpec.default);\n}\n\n/**\n * Returns a ratio that can be used to interpolate between exponential function\n * stops.\n *\n * How it works:\n * Two consecutive stop values define a (scaled and shifted) exponential\n * function `f(x) = a * base^x + b`, where `base` is the user-specified base,\n * and `a` and `b` are constants affording sufficient degrees of freedom to fit\n * the function to the given stops.\n *\n * Here's a bit of algebra that lets us compute `f(x)` directly from the stop\n * values without explicitly solving for `a` and `b`:\n *\n * First stop value: `f(x0) = y0 = a * base^x0 + b`\n * Second stop value: `f(x1) = y1 = a * base^x1 + b`\n * => `y1 - y0 = a(base^x1 - base^x0)`\n * => `a = (y1 - y0)/(base^x1 - base^x0)`\n *\n * Desired value: `f(x) = y = a * base^x + b`\n * => `f(x) = y0 + a * (base^x - base^x0)`\n *\n * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a\n * little algebra:\n * ```\n * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0)\n * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0)\n * ```\n *\n * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have\n * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as\n * an interpolation factor between the two stops' output values.\n *\n * (Note: a slightly different form for `ratio`,\n * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer\n * expensive `Math.pow()` operations.)\n *\n * @private\n */\nfunction interpolationFactor(input, base, lowerValue, upperValue) {\n const difference = upperValue - lowerValue;\n const progress = input - lowerValue;\n\n if (difference === 0) {\n return 0;\n } else if (base === 1) {\n return progress / difference;\n } else {\n return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport extend from '../util/extend';\nimport ParsingError from './parsing_error';\nimport ParsingContext from './parsing_context';\nimport EvaluationContext from './evaluation_context';\nimport CompoundExpression from './compound_expression';\nimport Step from './definitions/step';\nimport Interpolate from './definitions/interpolate';\nimport Coalesce from './definitions/coalesce';\nimport Let from './definitions/let';\nimport definitions from './definitions';\nimport * as isConstant from './is_constant';\nimport RuntimeError from './runtime_error';\nimport {success, error} from '../util/result';\nimport {supportsPropertyExpression, supportsZoomExpression, supportsInterpolation} from '../util/properties';\n\nimport type {Type, EvaluationKind} from './types';\nimport type {Value} from './values';\nimport type {Expression} from './expression';\nimport type {StylePropertySpecification} from '../style-spec';\nimport type {Result} from '../util/result';\nimport type {InterpolationType} from './definitions/interpolate';\nimport type {PropertyValueSpecification} from '../types';\nimport type {FormattedSection} from './types/formatted';\nimport type Point from '@mapbox/point-geometry';\nimport type {CanonicalTileID} from '../../source/tile_id';\n\nexport type Feature = {\n +type: 1 | 2 | 3 | 'Unknown' | 'Point' | 'MultiPoint' | 'LineString' | 'MultiLineString' | 'Polygon' | 'MultiPolygon',\n +id?: any,\n +properties: {[_: string]: any},\n +patterns?: {[_: string]: {\"min\": string, \"mid\": string, \"max\": string}},\n +geometry?: Array>\n};\n\nexport type FeatureState = {[_: string]: any};\n\nexport type GlobalProperties = $ReadOnly<{\n zoom: number,\n heatmapDensity?: number,\n lineProgress?: number,\n isSupportedScript?: (_: string) => boolean,\n accumulated?: Value\n}>;\n\nexport class StyleExpression {\n expression: Expression;\n\n _evaluator: EvaluationContext;\n _defaultValue: Value;\n _warningHistory: {[key: string]: boolean};\n _enumValues: ?{[_: string]: any};\n\n constructor(expression: Expression, propertySpec: ?StylePropertySpecification) {\n this.expression = expression;\n this._warningHistory = {};\n this._evaluator = new EvaluationContext();\n this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null;\n this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null;\n }\n\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any {\n this._evaluator.globals = globals;\n this._evaluator.feature = feature;\n this._evaluator.featureState = featureState;\n this._evaluator.canonical = canonical;\n this._evaluator.availableImages = availableImages || null;\n this._evaluator.formattedSection = formattedSection;\n\n return this.expression.evaluate(this._evaluator);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any {\n this._evaluator.globals = globals;\n this._evaluator.feature = feature || null;\n this._evaluator.featureState = featureState || null;\n this._evaluator.canonical = canonical;\n this._evaluator.availableImages = availableImages || null;\n this._evaluator.formattedSection = formattedSection || null;\n\n try {\n const val = this.expression.evaluate(this._evaluator);\n // eslint-disable-next-line no-self-compare\n if (val === null || val === undefined || (typeof val === 'number' && val !== val)) {\n return this._defaultValue;\n }\n if (this._enumValues && !(val in this._enumValues)) {\n throw new RuntimeError(`Expected value to be one of ${Object.keys(this._enumValues).map(v => JSON.stringify(v)).join(', ')}, but found ${JSON.stringify(val)} instead.`);\n }\n return val;\n } catch (e) {\n if (!this._warningHistory[e.message]) {\n this._warningHistory[e.message] = true;\n if (typeof console !== 'undefined') {\n console.warn(e.message);\n }\n }\n return this._defaultValue;\n }\n }\n}\n\nexport function isExpression(expression: mixed) {\n return Array.isArray(expression) && expression.length > 0 &&\n typeof expression[0] === 'string' && expression[0] in definitions;\n}\n\n/**\n * Parse and typecheck the given style spec JSON expression. If\n * options.defaultValue is provided, then the resulting StyleExpression's\n * `evaluate()` method will handle errors by logging a warning (once per\n * message) and returning the default value. Otherwise, it will throw\n * evaluation errors.\n *\n * @private\n */\nexport function createExpression(expression: mixed, propertySpec: ?StylePropertySpecification): Result> {\n const parser = new ParsingContext(definitions, [], propertySpec ? getExpectedType(propertySpec) : undefined);\n\n // For string-valued properties, coerce to string at the top level rather than asserting.\n const parsed = parser.parse(expression, undefined, undefined, undefined,\n propertySpec && propertySpec.type === 'string' ? {typeAnnotation: 'coerce'} : undefined);\n\n if (!parsed) {\n assert(parser.errors.length > 0);\n return error(parser.errors);\n }\n\n return success(new StyleExpression(parsed, propertySpec));\n}\n\nexport class ZoomConstantExpression {\n kind: Kind;\n isStateDependent: boolean;\n _styleExpression: StyleExpression;\n\n constructor(kind: Kind, expression: StyleExpression) {\n this.kind = kind;\n this._styleExpression = expression;\n this.isStateDependent = kind !== ('constant': EvaluationKind) && !isConstant.isStateConstant(expression.expression);\n }\n\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n}\n\nexport class ZoomDependentExpression {\n kind: Kind;\n zoomStops: Array;\n isStateDependent: boolean;\n\n _styleExpression: StyleExpression;\n interpolationType: ?InterpolationType;\n\n constructor(kind: Kind, expression: StyleExpression, zoomStops: Array, interpolationType?: InterpolationType) {\n this.kind = kind;\n this.zoomStops = zoomStops;\n this._styleExpression = expression;\n this.isStateDependent = kind !== ('camera': EvaluationKind) && !isConstant.isStateConstant(expression.expression);\n this.interpolationType = interpolationType;\n }\n\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n\n interpolationFactor(input: number, lower: number, upper: number): number {\n if (this.interpolationType) {\n return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper);\n } else {\n return 0;\n }\n }\n}\n\nexport type ConstantExpression = {\n kind: 'constant',\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array) => any,\n}\n\nexport type SourceExpression = {\n kind: 'source',\n isStateDependent: boolean,\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection) => any,\n};\n\nexport type CameraExpression = {\n kind: 'camera',\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array) => any,\n +interpolationFactor: (input: number, lower: number, upper: number) => number,\n zoomStops: Array,\n interpolationType: ?InterpolationType\n};\n\nexport type CompositeExpression = {\n kind: 'composite',\n isStateDependent: boolean,\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection) => any,\n +interpolationFactor: (input: number, lower: number, upper: number) => number,\n zoomStops: Array,\n interpolationType: ?InterpolationType\n};\n\nexport type StylePropertyExpression =\n | ConstantExpression\n | SourceExpression\n | CameraExpression\n | CompositeExpression;\n\nexport function createPropertyExpression(expression: mixed, propertySpec: StylePropertySpecification): Result> {\n expression = createExpression(expression, propertySpec);\n if (expression.result === 'error') {\n return expression;\n }\n\n const parsed = expression.value.expression;\n\n const isFeatureConstant = isConstant.isFeatureConstant(parsed);\n if (!isFeatureConstant && !supportsPropertyExpression(propertySpec)) {\n return error([new ParsingError('', 'data expressions not supported')]);\n }\n\n const isZoomConstant = isConstant.isGlobalPropertyConstant(parsed, ['zoom']);\n if (!isZoomConstant && !supportsZoomExpression(propertySpec)) {\n return error([new ParsingError('', 'zoom expressions not supported')]);\n }\n\n const zoomCurve = findZoomCurve(parsed);\n if (!zoomCurve && !isZoomConstant) {\n return error([new ParsingError('', '\"zoom\" expression may only be used as input to a top-level \"step\" or \"interpolate\" expression.')]);\n } else if (zoomCurve instanceof ParsingError) {\n return error([zoomCurve]);\n } else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) {\n return error([new ParsingError('', '\"interpolate\" expressions cannot be used with this property')]);\n }\n\n if (!zoomCurve) {\n return success(isFeatureConstant ?\n (new ZoomConstantExpression('constant', expression.value): ConstantExpression) :\n (new ZoomConstantExpression('source', expression.value): SourceExpression));\n }\n\n const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined;\n\n return success(isFeatureConstant ?\n (new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType): CameraExpression) :\n (new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType): CompositeExpression));\n}\n\nimport {isFunction, createFunction} from '../function';\nimport {Color} from './values';\n\n// serialization wrapper for old-style stop functions normalized to the\n// expression interface\nexport class StylePropertyFunction {\n _parameters: PropertyValueSpecification;\n _specification: StylePropertySpecification;\n\n kind: EvaluationKind;\n evaluate: (globals: GlobalProperties, feature?: Feature) => any;\n interpolationFactor: ?(input: number, lower: number, upper: number) => number;\n zoomStops: ?Array;\n\n constructor(parameters: PropertyValueSpecification, specification: StylePropertySpecification) {\n this._parameters = parameters;\n this._specification = specification;\n extend(this, createFunction(this._parameters, this._specification));\n }\n\n static deserialize(serialized: {_parameters: PropertyValueSpecification, _specification: StylePropertySpecification}) {\n return ((new StylePropertyFunction(serialized._parameters, serialized._specification)): StylePropertyFunction);\n }\n\n static serialize(input: StylePropertyFunction) {\n return {\n _parameters: input._parameters,\n _specification: input._specification\n };\n }\n}\n\nexport function normalizePropertyExpression(value: PropertyValueSpecification, specification: StylePropertySpecification): StylePropertyExpression {\n if (isFunction(value)) {\n return (new StylePropertyFunction(value, specification): any);\n\n } else if (isExpression(value)) {\n const expression = createPropertyExpression(value, specification);\n if (expression.result === 'error') {\n // this should have been caught in validation\n throw new Error(expression.value.map(err => `${err.key}: ${err.message}`).join(', '));\n }\n return expression.value;\n\n } else {\n let constant: any = value;\n if (typeof value === 'string' && specification.type === 'color') {\n constant = Color.parse(value);\n }\n return {\n kind: 'constant',\n evaluate: () => constant\n };\n }\n}\n\n// Zoom-dependent expressions may only use [\"zoom\"] as the input to a top-level \"step\" or \"interpolate\"\n// expression (collectively referred to as a \"curve\"). The curve may be wrapped in one or more \"let\" or\n// \"coalesce\" expressions.\nfunction findZoomCurve(expression: Expression): Step | Interpolate | ParsingError | null {\n let result = null;\n if (expression instanceof Let) {\n result = findZoomCurve(expression.result);\n\n } else if (expression instanceof Coalesce) {\n for (const arg of expression.args) {\n result = findZoomCurve(arg);\n if (result) {\n break;\n }\n }\n\n } else if ((expression instanceof Step || expression instanceof Interpolate) &&\n expression.input instanceof CompoundExpression &&\n expression.input.name === 'zoom') {\n\n result = expression;\n }\n\n if (result instanceof ParsingError) {\n return result;\n }\n\n expression.eachChild((child) => {\n const childResult = findZoomCurve(child);\n if (childResult instanceof ParsingError) {\n result = childResult;\n } else if (!result && childResult) {\n result = new ParsingError('', '\"zoom\" expression may only be used as input to a top-level \"step\" or \"interpolate\" expression.');\n } else if (result && childResult && result !== childResult) {\n result = new ParsingError('', 'Only one zoom-based \"step\" or \"interpolate\" subexpression may be used in an expression.');\n }\n });\n\n return result;\n}\n\nimport {ColorType, StringType, NumberType, BooleanType, ValueType, FormattedType, ResolvedImageType, array} from './types';\n\nfunction getExpectedType(spec: StylePropertySpecification): Type {\n const types = {\n color: ColorType,\n string: StringType,\n number: NumberType,\n enum: StringType,\n boolean: BooleanType,\n formatted: FormattedType,\n resolvedImage: ResolvedImageType\n };\n\n if (spec.type === 'array') {\n return array(types[spec.value] || ValueType, spec.length);\n }\n\n return types[spec.type];\n}\n\nfunction getDefaultValue(spec: StylePropertySpecification): Value {\n if (spec.type === 'color' && isFunction(spec.default)) {\n // Special case for heatmap-color: it uses the 'default:' to define a\n // default color ramp, but createExpression expects a simple value to fall\n // back to in case of runtime errors\n return new Color(0, 0, 0, 0);\n } else if (spec.type === 'color') {\n return Color.parse(spec.default) || null;\n } else if (spec.default === undefined) {\n return null;\n } else {\n return spec.default;\n }\n}\n","// @flow\n\nimport assert from 'assert';\nimport type {StylePropertySpecification} from '../style-spec';\n\nexport default convertFunction;\n\nfunction convertLiteral(value) {\n return typeof value === 'object' ? ['literal', value] : value;\n}\n\nfunction convertFunction(parameters: any, propertySpec: StylePropertySpecification) {\n let stops = parameters.stops;\n if (!stops) {\n // identity function\n return convertIdentityFunction(parameters, propertySpec);\n }\n\n const zoomAndFeatureDependent = stops && typeof stops[0][0] === 'object';\n const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined;\n const zoomDependent = zoomAndFeatureDependent || !featureDependent;\n\n stops = stops.map((stop) => {\n if (!featureDependent && propertySpec.tokens && typeof stop[1] === 'string') {\n return [stop[0], convertTokenString(stop[1])];\n }\n return [stop[0], convertLiteral(stop[1])];\n });\n\n if (zoomAndFeatureDependent) {\n return convertZoomAndPropertyFunction(parameters, propertySpec, stops);\n } else if (zoomDependent) {\n return convertZoomFunction(parameters, propertySpec, stops);\n } else {\n return convertPropertyFunction(parameters, propertySpec, stops);\n }\n}\n\nfunction convertIdentityFunction(parameters, propertySpec): Array {\n const get = ['get', parameters.property];\n\n if (parameters.default === undefined) {\n // By default, expressions for string-valued properties get coerced. To preserve\n // legacy function semantics, insert an explicit assertion instead.\n return propertySpec.type === 'string' ? ['string', get] : get;\n } else if (propertySpec.type === 'enum') {\n return [\n 'match',\n get,\n Object.keys(propertySpec.values),\n get,\n parameters.default\n ];\n } else {\n const expression = [propertySpec.type === 'color' ? 'to-color' : propertySpec.type, get, convertLiteral(parameters.default)];\n if (propertySpec.type === 'array') {\n expression.splice(1, 0, propertySpec.value, propertySpec.length || null);\n }\n return expression;\n }\n}\n\nfunction getInterpolateOperator(parameters) {\n switch (parameters.colorSpace) {\n case 'hcl': return 'interpolate-hcl';\n case 'lab': return 'interpolate-lab';\n default: return 'interpolate';\n }\n}\n\nfunction convertZoomAndPropertyFunction(parameters, propertySpec, stops) {\n const featureFunctionParameters = {};\n const featureFunctionStops = {};\n const zoomStops = [];\n for (let s = 0; s < stops.length; s++) {\n const stop = stops[s];\n const zoom = stop[0].zoom;\n if (featureFunctionParameters[zoom] === undefined) {\n featureFunctionParameters[zoom] = {\n zoom,\n type: parameters.type,\n property: parameters.property,\n default: parameters.default,\n };\n featureFunctionStops[zoom] = [];\n zoomStops.push(zoom);\n }\n featureFunctionStops[zoom].push([stop[0].value, stop[1]]);\n }\n\n // the interpolation type for the zoom dimension of a zoom-and-property\n // function is determined directly from the style property specification\n // for which it's being used: linear for interpolatable properties, step\n // otherwise.\n const functionType = getFunctionType({}, propertySpec);\n if (functionType === 'exponential') {\n const expression = [getInterpolateOperator(parameters), ['linear'], ['zoom']];\n\n for (const z of zoomStops) {\n const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]);\n appendStopPair(expression, z, output, false);\n }\n\n return expression;\n } else {\n const expression = ['step', ['zoom']];\n\n for (const z of zoomStops) {\n const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]);\n appendStopPair(expression, z, output, true);\n }\n\n fixupDegenerateStepCurve(expression);\n\n return expression;\n }\n}\n\nfunction coalesce(a, b) {\n if (a !== undefined) return a;\n if (b !== undefined) return b;\n}\n\nfunction getFallback(parameters, propertySpec) {\n const defaultValue = convertLiteral(coalesce(parameters.default, propertySpec.default));\n\n /*\n * Some fields with type: resolvedImage have an undefined default.\n * Because undefined is an invalid value for resolvedImage, set fallback to\n * an empty string instead of undefined to ensure output\n * passes validation.\n */\n if (defaultValue === undefined && propertySpec.type === 'resolvedImage') {\n return '';\n }\n return defaultValue;\n}\n\nfunction convertPropertyFunction(parameters, propertySpec, stops) {\n const type = getFunctionType(parameters, propertySpec);\n const get = ['get', parameters.property];\n if (type === 'categorical' && typeof stops[0][0] === 'boolean') {\n assert(parameters.stops.length > 0 && parameters.stops.length <= 2);\n const expression = ['case'];\n for (const stop of stops) {\n expression.push(['==', get, stop[0]], stop[1]);\n }\n\n expression.push(getFallback(parameters, propertySpec));\n return expression;\n } else if (type === 'categorical') {\n const expression = ['match', get];\n for (const stop of stops) {\n appendStopPair(expression, stop[0], stop[1], false);\n }\n expression.push(getFallback(parameters, propertySpec));\n return expression;\n } else if (type === 'interval') {\n const expression = ['step', ['number', get]];\n for (const stop of stops) {\n appendStopPair(expression, stop[0], stop[1], true);\n }\n fixupDegenerateStepCurve(expression);\n return parameters.default === undefined ? expression : [\n 'case',\n ['==', ['typeof', get], 'number'],\n expression,\n convertLiteral(parameters.default)\n ];\n } else if (type === 'exponential') {\n const base = parameters.base !== undefined ? parameters.base : 1;\n const expression = [\n getInterpolateOperator(parameters),\n base === 1 ? [\"linear\"] : [\"exponential\", base],\n [\"number\", get]\n ];\n\n for (const stop of stops) {\n appendStopPair(expression, stop[0], stop[1], false);\n }\n return parameters.default === undefined ? expression : [\n 'case',\n ['==', ['typeof', get], 'number'],\n expression,\n convertLiteral(parameters.default)\n ];\n } else {\n throw new Error(`Unknown property function type ${type}`);\n }\n}\n\nfunction convertZoomFunction(parameters, propertySpec, stops, input = ['zoom']) {\n const type = getFunctionType(parameters, propertySpec);\n let expression;\n let isStep = false;\n if (type === 'interval') {\n expression = ['step', input];\n isStep = true;\n } else if (type === 'exponential') {\n const base = parameters.base !== undefined ? parameters.base : 1;\n expression = [getInterpolateOperator(parameters), base === 1 ? [\"linear\"] : [\"exponential\", base], input];\n\n } else {\n throw new Error(`Unknown zoom function type \"${type}\"`);\n }\n\n for (const stop of stops) {\n appendStopPair(expression, stop[0], stop[1], isStep);\n }\n\n fixupDegenerateStepCurve(expression);\n\n return expression;\n}\n\nfunction fixupDegenerateStepCurve(expression) {\n // degenerate step curve (i.e. a constant function): add a noop stop\n if (expression[0] === 'step' && expression.length === 3) {\n expression.push(0);\n expression.push(expression[3]);\n }\n}\n\nfunction appendStopPair(curve, input, output, isStep) {\n // Skip duplicate stop values. They were not validated for functions, but they are for expressions.\n // https://github.com/mapbox/mapbox-gl-js/issues/4107\n if (curve.length > 3 && input === curve[curve.length - 2]) {\n return;\n }\n // step curves don't get the first input value, as it is redundant.\n if (!(isStep && curve.length === 2)) {\n curve.push(input);\n }\n curve.push(output);\n}\n\nfunction getFunctionType(parameters, propertySpec) {\n if (parameters.type) {\n return parameters.type;\n } else {\n assert(propertySpec.expression);\n return (propertySpec.expression: any).interpolated ? 'exponential' : 'interval';\n }\n}\n\n// \"String with {name} token\" => [\"concat\", \"String with \", [\"get\", \"name\"], \" token\"]\nexport function convertTokenString(s: string) {\n const result = ['concat'];\n const re = /{([^{}]+)}/g;\n let pos = 0;\n for (let match = re.exec(s); match !== null; match = re.exec(s)) {\n const literal = s.slice(pos, re.lastIndex - match[0].length);\n pos = re.lastIndex;\n if (literal.length > 0) result.push(literal);\n result.push(['get', match[1]]);\n }\n\n if (result.length === 1) {\n return s;\n }\n\n if (pos < s.length) {\n result.push(s.slice(pos));\n } else if (result.length === 2) {\n return ['to-string', result[1]];\n }\n\n return result;\n}\n\n","// @flow\n\nimport {createExpression} from '../expression';\nimport type {GlobalProperties, Feature} from '../expression';\nimport type {CanonicalTileID} from '../../source/tile_id';\n\ntype FilterExpression = (globalProperties: GlobalProperties, feature: Feature, canonical?: CanonicalTileID) => boolean;\nexport type FeatureFilter ={filter: FilterExpression, needGeometry: boolean};\n\nexport default createFilter;\nexport {isExpressionFilter};\n\nfunction isExpressionFilter(filter: any) {\n if (filter === true || filter === false) {\n return true;\n }\n\n if (!Array.isArray(filter) || filter.length === 0) {\n return false;\n }\n switch (filter[0]) {\n case 'has':\n return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type';\n\n case 'in':\n return filter.length >= 3 && (typeof filter[1] !== 'string' || Array.isArray(filter[2]));\n\n case '!in':\n case '!has':\n case 'none':\n return false;\n\n case '==':\n case '!=':\n case '>':\n case '>=':\n case '<':\n case '<=':\n return filter.length !== 3 || (Array.isArray(filter[1]) || Array.isArray(filter[2]));\n\n case 'any':\n case 'all':\n for (const f of filter.slice(1)) {\n if (!isExpressionFilter(f) && typeof f !== 'boolean') {\n return false;\n }\n }\n return true;\n\n default:\n return true;\n }\n}\n\nconst filterSpec = {\n 'type': 'boolean',\n 'default': false,\n 'transition': false,\n 'property-type': 'data-driven',\n 'expression': {\n 'interpolated': false,\n 'parameters': ['zoom', 'feature']\n }\n};\n\n/**\n * Given a filter expressed as nested arrays, return a new function\n * that evaluates whether a given feature (with a .properties or .tags property)\n * passes its test.\n *\n * @private\n * @param {Array} filter mapbox gl filter\n * @returns {Function} filter-evaluating function\n */\nfunction createFilter(filter: any): FeatureFilter {\n if (filter === null || filter === undefined) {\n return {filter: () => true, needGeometry: false};\n }\n\n if (!isExpressionFilter(filter)) {\n filter = convertFilter(filter);\n }\n\n const compiled = createExpression(filter, filterSpec);\n if (compiled.result === 'error') {\n throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', '));\n } else {\n const needGeometry = geometryNeeded(filter);\n return {filter: (globalProperties: GlobalProperties, feature: Feature, canonical?: CanonicalTileID) => compiled.value.evaluate(globalProperties, feature, {}, canonical),\n needGeometry};\n }\n}\n\n// Comparison function to sort numbers and strings\nfunction compare(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction geometryNeeded(filter) {\n if (!Array.isArray(filter)) return false;\n if (filter[0] === 'within') return true;\n for (let index = 1; index < filter.length; index++) {\n if (geometryNeeded(filter[index])) return true;\n }\n return false;\n}\n\nfunction convertFilter(filter: ?Array): mixed {\n if (!filter) return true;\n const op = filter[0];\n if (filter.length <= 1) return (op !== 'any');\n const converted =\n op === '==' ? convertComparisonOp(filter[1], filter[2], '==') :\n op === '!=' ? convertNegation(convertComparisonOp(filter[1], filter[2], '==')) :\n op === '<' ||\n op === '>' ||\n op === '<=' ||\n op === '>=' ? convertComparisonOp(filter[1], filter[2], op) :\n op === 'any' ? convertDisjunctionOp(filter.slice(1)) :\n op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter)) :\n op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter).map(convertNegation)) :\n op === 'in' ? convertInOp(filter[1], filter.slice(2)) :\n op === '!in' ? convertNegation(convertInOp(filter[1], filter.slice(2))) :\n op === 'has' ? convertHasOp(filter[1]) :\n op === '!has' ? convertNegation(convertHasOp(filter[1])) :\n op === 'within' ? filter :\n true;\n return converted;\n}\n\nfunction convertComparisonOp(property: string, value: any, op: string) {\n switch (property) {\n case '$type':\n return [`filter-type-${op}`, value];\n case '$id':\n return [`filter-id-${op}`, value];\n default:\n return [`filter-${op}`, property, value];\n }\n}\n\nfunction convertDisjunctionOp(filters: Array>) {\n return ['any'].concat(filters.map(convertFilter));\n}\n\nfunction convertInOp(property: string, values: Array) {\n if (values.length === 0) { return false; }\n switch (property) {\n case '$type':\n return [`filter-type-in`, ['literal', values]];\n case '$id':\n return [`filter-id-in`, ['literal', values]];\n default:\n if (values.length > 200 && !values.some(v => typeof v !== typeof values[0])) {\n return ['filter-in-large', property, ['literal', values.sort(compare)]];\n } else {\n return ['filter-in-small', property, ['literal', values]];\n }\n }\n}\n\nfunction convertHasOp(property: string) {\n switch (property) {\n case '$type':\n return true;\n case '$id':\n return [`filter-has-id`];\n default:\n return [`filter-has`, property];\n }\n}\n\nfunction convertNegation(filter: mixed) {\n return ['!', filter];\n}\n","// @flow\n\nimport {isExpressionFilter} from './index';\n\nimport type {FilterSpecification} from '../types';\n\ntype ExpectedTypes = {[_: string]: 'string' | 'number' | 'boolean'};\n\n/**\n * Convert the given legacy filter to (the JSON representation of) an\n * equivalent expression\n * @private\n */\nexport default function convertFilter(filter: FilterSpecification): mixed {\n return _convertFilter(filter, {});\n}\n\n/*\n * Convert the given filter to an expression, storing the expected types for\n * any feature properties referenced in expectedTypes.\n *\n * These expected types are needed in order to construct preflight type checks\n * needed for handling 'any' filters. A preflight type check is necessary in\n * order to mimic legacy filters' semantics around expected type mismatches.\n * For example, consider the legacy filter:\n *\n * [\"any\", [\"all\", [\">\", \"y\", 0], [\">\", \"y\", 0]], [\">\", \"x\", 0]]\n *\n * Naively, we might convert this to the expression:\n *\n * [\"any\", [\"all\", [\">\", [\"get\", \"y\"], 0], [\">\", [\"get\", \"z\"], 0]], [\">\", [\"get\", \"x\"], 0]]\n *\n * But if we tried to evaluate this against, say `{x: 1, y: null, z: 0}`, the\n * [\">\", [\"get\", \"y\"], 0] would cause an evaluation error, leading to the\n * entire filter returning false. Legacy filter semantics, though, ask for\n * [\">\", \"y\", 0] to simply return `false` when `y` is of the wrong type,\n * allowing the subsequent terms of the outer \"any\" expression to be evaluated\n * (resulting, in this case, in a `true` value, because x > 0).\n *\n * We account for this by inserting a preflight type-checking expression before\n * each \"any\" term, allowing us to avoid evaluating the actual converted filter\n * if any type mismatches would cause it to produce an evalaution error:\n *\n * [\"any\",\n * [\"case\",\n * [\"all\", [\"==\", [\"typeof\", [\"get\", \"y\"]], \"number\"], [\"==\", [\"typeof\", [\"get\", \"z\"], \"number]],\n * [\"all\", [\">\", [\"get\", \"y\"], 0], [\">\", [\"get\", \"z\"], 0]],\n * false\n * ],\n * [\"case\",\n * [\"==\", [\"typeof\", [\"get\", \"x\"], \"number\"]],\n * [\">\", [\"get\", \"x\"], 0],\n * false\n * ]\n * ]\n *\n * An alternative, possibly more direct approach would be to use type checks\n * in the conversion of each comparison operator, so that the converted version\n * of each individual ==, >=, etc. would mimic the legacy filter semantics. The\n * downside of this approach is that it can lead to many more type checks than\n * would otherwise be necessary: outside the context of an \"any\" expression,\n * bailing out due to a runtime type error (expression semantics) and returning\n * false (legacy filter semantics) are equivalent: they cause the filter to\n * produce a `false` result.\n */\nfunction _convertFilter(filter: FilterSpecification, expectedTypes: ExpectedTypes): mixed {\n if (isExpressionFilter(filter)) { return filter; }\n\n if (!filter) return true;\n const op = filter[0];\n if (filter.length <= 1) return (op !== 'any');\n\n let converted;\n\n if (\n op === '==' ||\n op === '!=' ||\n op === '<' ||\n op === '>' ||\n op === '<=' ||\n op === '>='\n ) {\n const [, property, value] = (filter: any);\n converted = convertComparisonOp(property, value, op, expectedTypes);\n } else if (op === 'any') {\n const children = (filter: any).slice(1).map(f => {\n const types = {};\n const child = _convertFilter(f, types);\n const typechecks = runtimeTypeChecks(types);\n return typechecks === true ? child : ['case', typechecks, child, false];\n });\n return ['any'].concat(children);\n } else if (op === 'all') {\n const children = (filter: any).slice(1).map(f => _convertFilter(f, expectedTypes));\n return children.length > 1 ? ['all'].concat(children) : [].concat(...children);\n } else if (op === 'none') {\n return ['!', _convertFilter(['any'].concat(filter.slice(1)), {})];\n } else if (op === 'in') {\n converted = convertInOp((filter[1]: any), filter.slice(2));\n } else if (op === '!in') {\n converted = convertInOp((filter[1]: any), filter.slice(2), true);\n } else if (op === 'has') {\n converted = convertHasOp((filter[1]: any));\n } else if (op === '!has') {\n converted = ['!', convertHasOp((filter[1]: any))];\n } else {\n converted = true;\n }\n\n return converted;\n}\n\n// Given a set of feature properties and an expected type for each one,\n// construct an boolean expression that tests whether each property has the\n// right type.\n// E.g.: for {name: 'string', population: 'number'}, return\n// [ 'all',\n// ['==', ['typeof', ['get', 'name'], 'string']],\n// ['==', ['typeof', ['get', 'population'], 'number]]\n// ]\nfunction runtimeTypeChecks(expectedTypes: ExpectedTypes) {\n const conditions = [];\n for (const property in expectedTypes) {\n const get = property === '$id' ? ['id'] : ['get', property];\n conditions.push(['==', ['typeof', get], expectedTypes[property]]);\n }\n if (conditions.length === 0) return true;\n if (conditions.length === 1) return conditions[0];\n return ['all'].concat(conditions);\n}\n\nfunction convertComparisonOp(property: string, value: any, op: string, expectedTypes: ?ExpectedTypes) {\n let get;\n if (property === '$type') {\n return [op, ['geometry-type'], value];\n } else if (property === '$id') {\n get = ['id'];\n } else {\n get = ['get', property];\n }\n\n if (expectedTypes && value !== null) {\n const type = ((typeof value): any);\n expectedTypes[property] = type;\n }\n\n if (op === '==' && property !== '$id' && value === null) {\n return [\n 'all',\n ['has', property], // missing property != null for legacy filters\n ['==', get, null]\n ];\n } else if (op === '!=' && property !== '$id' && value === null) {\n return [\n 'any',\n ['!', ['has', property]], // missing property != null for legacy filters\n ['!=', get, null]\n ];\n }\n\n return [op, get, value];\n}\n\nfunction convertInOp(property: string, values: Array, negate = false) {\n if (values.length === 0) return negate;\n\n let get;\n if (property === '$type') {\n get = ['geometry-type'];\n } else if (property === '$id') {\n get = ['id'];\n } else {\n get = ['get', property];\n }\n\n // Determine if the list of values to be searched is homogenously typed.\n // If so (and if the type is string or number), then we can use a\n // [match, input, [...values], true, false] construction rather than a\n // bunch of `==` tests.\n let uniformTypes = true;\n const type = typeof values[0];\n for (const value of values) {\n if (typeof value !== type) {\n uniformTypes = false;\n break;\n }\n }\n\n if (uniformTypes && (type === 'string' || type === 'number')) {\n // Match expressions must have unique values.\n const uniqueValues = values.sort().filter((v, i) => i === 0 || values[i - 1] !== v);\n return ['match', get, uniqueValues, !negate, negate];\n }\n\n return [ negate ? 'all' : 'any' ].concat(\n values.map(v => [negate ? '!=' : '==', get, v])\n );\n}\n\nfunction convertHasOp(property: string) {\n if (property === '$type') {\n return true;\n } else if (property === '$id') {\n return ['!=', ['id'], null];\n } else {\n return ['has', property];\n }\n}\n","// @flow\n\nimport {\n eachLayer,\n eachProperty\n} from '../visit';\nimport {isExpression} from '../expression';\nimport convertFunction, {convertTokenString} from '../function/convert';\nimport convertFilter from '../feature_filter/convert';\n\nimport type {StyleSpecification} from '../types';\n\n/**\n * Migrate the given style object in place to use expressions. Specifically,\n * this will convert (a) \"stop\" functions, and (b) legacy filters to their\n * expression equivalents.\n */\nexport default function(style: StyleSpecification) {\n const converted = [];\n\n eachLayer(style, (layer) => {\n if (layer.filter) {\n layer.filter = (convertFilter(layer.filter): any);\n }\n });\n\n eachProperty(style, {paint: true, layout: true}, ({path, value, reference, set}) => {\n if (isExpression(value)) return;\n if (typeof value === 'object' && !Array.isArray(value)) {\n set(convertFunction(value, reference));\n converted.push(path.join('.'));\n } else if (reference.tokens && typeof value === 'string') {\n set(convertTokenString(value));\n }\n });\n\n return style;\n}\n\n","\nimport migrateToV8 from './migrate/v8';\nimport migrateToExpressions from './migrate/expressions';\n\n/**\n * Migrate a Mapbox GL Style to the latest version.\n *\n * @private\n * @alias migrate\n * @param {object} style a Mapbox GL Style\n * @returns {Object} a migrated style\n * @example\n * var fs = require('fs');\n * var migrate = require('mapbox-gl-style-spec').migrate;\n * var style = fs.readFileSync('./style.json', 'utf8');\n * fs.writeFileSync('./style.json', JSON.stringify(migrate(style)));\n */\nexport default function(style) {\n let migrated = false;\n\n if (style.version === 7) {\n style = migrateToV8(style);\n migrated = true;\n }\n\n if (style.version === 8) {\n migrated = migrateToExpressions(style);\n migrated = true;\n }\n\n if (!migrated) {\n throw new Error('cannot migrate from', style.version);\n }\n\n return style;\n}\n","\nexport default function (style) {\n const styleIDs = [];\n const sourceIDs = [];\n const compositedSourceLayers = [];\n\n for (const id in style.sources) {\n const source = style.sources[id];\n\n if (source.type !== \"vector\")\n continue;\n\n const match = /^mapbox:\\/\\/(.*)/.exec(source.url);\n if (!match)\n continue;\n\n styleIDs.push(id);\n sourceIDs.push(match[1]);\n }\n\n if (styleIDs.length < 2)\n return style;\n\n styleIDs.forEach((id) => {\n delete style.sources[id];\n });\n\n const compositeID = sourceIDs.join(\",\");\n\n style.sources[compositeID] = {\n \"type\": \"vector\",\n \"url\": `mapbox://${compositeID}`\n };\n\n style.layers.forEach((layer) => {\n if (styleIDs.indexOf(layer.source) >= 0) {\n layer.source = compositeID;\n\n if ('source-layer' in layer) {\n if (compositedSourceLayers.indexOf(layer['source-layer']) >= 0) {\n throw new Error('Conflicting source layer names');\n } else {\n compositedSourceLayers.push(layer['source-layer']);\n }\n }\n }\n });\n\n return style;\n}\n","\nexport default ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout'];\n","\nimport refProperties from './util/ref_properties';\n\nfunction deref(layer, parent) {\n const result = {};\n\n for (const k in layer) {\n if (k !== 'ref') {\n result[k] = layer[k];\n }\n }\n\n refProperties.forEach((k) => {\n if (k in parent) {\n result[k] = parent[k];\n }\n });\n\n return result;\n}\n\nexport default derefLayers;\n\n/**\n * Given an array of layers, some of which may contain `ref` properties\n * whose value is the `id` of another property, return a new array where\n * such layers have been augmented with the 'type', 'source', etc. properties\n * from the parent layer, and the `ref` property has been removed.\n *\n * The input is not modified. The output may contain references to portions\n * of the input.\n *\n * @private\n * @param {Array} layers\n * @returns {Array}\n */\nfunction derefLayers(layers) {\n layers = layers.slice();\n\n const map = Object.create(null);\n for (let i = 0; i < layers.length; i++) {\n map[layers[i].id] = layers[i];\n }\n\n for (let i = 0; i < layers.length; i++) {\n if ('ref' in layers[i]) {\n layers[i] = deref(layers[i], map[layers[i].ref]);\n }\n }\n\n return layers;\n}\n","// @flow\n\n/**\n * Deeply compares two object literals.\n *\n * @private\n */\nfunction deepEqual(a: ?mixed, b: ?mixed): boolean {\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) return false;\n }\n return true;\n }\n if (typeof a === 'object' && a !== null && b !== null) {\n if (!(typeof b === 'object')) return false;\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n for (const key in a) {\n if (!deepEqual(a[key], b[key])) return false;\n }\n return true;\n }\n return a === b;\n}\n\nexport default deepEqual;\n","\nimport isEqual from './util/deep_equal';\n\nconst operations = {\n\n /*\n * { command: 'setStyle', args: [stylesheet] }\n */\n setStyle: 'setStyle',\n\n /*\n * { command: 'addLayer', args: [layer, 'beforeLayerId'] }\n */\n addLayer: 'addLayer',\n\n /*\n * { command: 'removeLayer', args: ['layerId'] }\n */\n removeLayer: 'removeLayer',\n\n /*\n * { command: 'setPaintProperty', args: ['layerId', 'prop', value] }\n */\n setPaintProperty: 'setPaintProperty',\n\n /*\n * { command: 'setLayoutProperty', args: ['layerId', 'prop', value] }\n */\n setLayoutProperty: 'setLayoutProperty',\n\n /*\n * { command: 'setFilter', args: ['layerId', filter] }\n */\n setFilter: 'setFilter',\n\n /*\n * { command: 'addSource', args: ['sourceId', source] }\n */\n addSource: 'addSource',\n\n /*\n * { command: 'removeSource', args: ['sourceId'] }\n */\n removeSource: 'removeSource',\n\n /*\n * { command: 'setGeoJSONSourceData', args: ['sourceId', data] }\n */\n setGeoJSONSourceData: 'setGeoJSONSourceData',\n\n /*\n * { command: 'setLayerZoomRange', args: ['layerId', 0, 22] }\n */\n setLayerZoomRange: 'setLayerZoomRange',\n\n /*\n * { command: 'setLayerProperty', args: ['layerId', 'prop', value] }\n */\n setLayerProperty: 'setLayerProperty',\n\n /*\n * { command: 'setCenter', args: [[lon, lat]] }\n */\n setCenter: 'setCenter',\n\n /*\n * { command: 'setZoom', args: [zoom] }\n */\n setZoom: 'setZoom',\n\n /*\n * { command: 'setBearing', args: [bearing] }\n */\n setBearing: 'setBearing',\n\n /*\n * { command: 'setPitch', args: [pitch] }\n */\n setPitch: 'setPitch',\n\n /*\n * { command: 'setSprite', args: ['spriteUrl'] }\n */\n setSprite: 'setSprite',\n\n /*\n * { command: 'setGlyphs', args: ['glyphsUrl'] }\n */\n setGlyphs: 'setGlyphs',\n\n /*\n * { command: 'setTransition', args: [transition] }\n */\n setTransition: 'setTransition',\n\n /*\n * { command: 'setLighting', args: [lightProperties] }\n */\n setLight: 'setLight'\n\n};\n\nfunction addSource(sourceId, after, commands) {\n commands.push({command: operations.addSource, args: [sourceId, after[sourceId]]});\n}\n\nfunction removeSource(sourceId, commands, sourcesRemoved) {\n commands.push({command: operations.removeSource, args: [sourceId]});\n sourcesRemoved[sourceId] = true;\n}\n\nfunction updateSource(sourceId, after, commands, sourcesRemoved) {\n removeSource(sourceId, commands, sourcesRemoved);\n addSource(sourceId, after, commands);\n}\n\nfunction canUpdateGeoJSON(before, after, sourceId) {\n let prop;\n for (prop in before[sourceId]) {\n if (!before[sourceId].hasOwnProperty(prop)) continue;\n if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) {\n return false;\n }\n }\n for (prop in after[sourceId]) {\n if (!after[sourceId].hasOwnProperty(prop)) continue;\n if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) {\n return false;\n }\n }\n return true;\n}\n\nfunction diffSources(before, after, commands, sourcesRemoved) {\n before = before || {};\n after = after || {};\n\n let sourceId;\n\n // look for sources to remove\n for (sourceId in before) {\n if (!before.hasOwnProperty(sourceId)) continue;\n if (!after.hasOwnProperty(sourceId)) {\n removeSource(sourceId, commands, sourcesRemoved);\n }\n }\n\n // look for sources to add/update\n for (sourceId in after) {\n if (!after.hasOwnProperty(sourceId)) continue;\n if (!before.hasOwnProperty(sourceId)) {\n addSource(sourceId, after, commands);\n } else if (!isEqual(before[sourceId], after[sourceId])) {\n if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) {\n commands.push({command: operations.setGeoJSONSourceData, args: [sourceId, after[sourceId].data]});\n } else {\n // no update command, must remove then add\n updateSource(sourceId, after, commands, sourcesRemoved);\n }\n }\n }\n}\n\nfunction diffLayerPropertyChanges(before, after, commands, layerId, klass, command) {\n before = before || {};\n after = after || {};\n\n let prop;\n\n for (prop in before) {\n if (!before.hasOwnProperty(prop)) continue;\n if (!isEqual(before[prop], after[prop])) {\n commands.push({command, args: [layerId, prop, after[prop], klass]});\n }\n }\n for (prop in after) {\n if (!after.hasOwnProperty(prop) || before.hasOwnProperty(prop)) continue;\n if (!isEqual(before[prop], after[prop])) {\n commands.push({command, args: [layerId, prop, after[prop], klass]});\n }\n }\n}\n\nfunction pluckId(layer) {\n return layer.id;\n}\nfunction indexById(group, layer) {\n group[layer.id] = layer;\n return group;\n}\n\nfunction diffLayers(before, after, commands) {\n before = before || [];\n after = after || [];\n\n // order of layers by id\n const beforeOrder = before.map(pluckId);\n const afterOrder = after.map(pluckId);\n\n // index of layer by id\n const beforeIndex = before.reduce(indexById, {});\n const afterIndex = after.reduce(indexById, {});\n\n // track order of layers as if they have been mutated\n const tracker = beforeOrder.slice();\n\n // layers that have been added do not need to be diffed\n const clean = Object.create(null);\n\n let i, d, layerId, beforeLayer, afterLayer, insertBeforeLayerId, prop;\n\n // remove layers\n for (i = 0, d = 0; i < beforeOrder.length; i++) {\n layerId = beforeOrder[i];\n if (!afterIndex.hasOwnProperty(layerId)) {\n commands.push({command: operations.removeLayer, args: [layerId]});\n tracker.splice(tracker.indexOf(layerId, d), 1);\n } else {\n // limit where in tracker we need to look for a match\n d++;\n }\n }\n\n // add/reorder layers\n for (i = 0, d = 0; i < afterOrder.length; i++) {\n // work backwards as insert is before an existing layer\n layerId = afterOrder[afterOrder.length - 1 - i];\n\n if (tracker[tracker.length - 1 - i] === layerId) continue;\n\n if (beforeIndex.hasOwnProperty(layerId)) {\n // remove the layer before we insert at the correct position\n commands.push({command: operations.removeLayer, args: [layerId]});\n tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1);\n } else {\n // limit where in tracker we need to look for a match\n d++;\n }\n\n // add layer at correct position\n insertBeforeLayerId = tracker[tracker.length - i];\n commands.push({command: operations.addLayer, args: [afterIndex[layerId], insertBeforeLayerId]});\n tracker.splice(tracker.length - i, 0, layerId);\n clean[layerId] = true;\n }\n\n // update layers\n for (i = 0; i < afterOrder.length; i++) {\n layerId = afterOrder[i];\n beforeLayer = beforeIndex[layerId];\n afterLayer = afterIndex[layerId];\n\n // no need to update if previously added (new or moved)\n if (clean[layerId] || isEqual(beforeLayer, afterLayer)) continue;\n\n // If source, source-layer, or type have changes, then remove the layer\n // and add it back 'from scratch'.\n if (!isEqual(beforeLayer.source, afterLayer.source) || !isEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !isEqual(beforeLayer.type, afterLayer.type)) {\n commands.push({command: operations.removeLayer, args: [layerId]});\n // we add the layer back at the same position it was already in, so\n // there's no need to update the `tracker`\n insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1];\n commands.push({command: operations.addLayer, args: [afterLayer, insertBeforeLayerId]});\n continue;\n }\n\n // layout, paint, filter, minzoom, maxzoom\n diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, operations.setLayoutProperty);\n diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, operations.setPaintProperty);\n if (!isEqual(beforeLayer.filter, afterLayer.filter)) {\n commands.push({command: operations.setFilter, args: [layerId, afterLayer.filter]});\n }\n if (!isEqual(beforeLayer.minzoom, afterLayer.minzoom) || !isEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) {\n commands.push({command: operations.setLayerZoomRange, args: [layerId, afterLayer.minzoom, afterLayer.maxzoom]});\n }\n\n // handle all other layer props, including paint.*\n for (prop in beforeLayer) {\n if (!beforeLayer.hasOwnProperty(prop)) continue;\n if (prop === 'layout' || prop === 'paint' || prop === 'filter' ||\n prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue;\n if (prop.indexOf('paint.') === 0) {\n diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);\n } else if (!isEqual(beforeLayer[prop], afterLayer[prop])) {\n commands.push({command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]]});\n }\n }\n for (prop in afterLayer) {\n if (!afterLayer.hasOwnProperty(prop) || beforeLayer.hasOwnProperty(prop)) continue;\n if (prop === 'layout' || prop === 'paint' || prop === 'filter' ||\n prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue;\n if (prop.indexOf('paint.') === 0) {\n diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);\n } else if (!isEqual(beforeLayer[prop], afterLayer[prop])) {\n commands.push({command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]]});\n }\n }\n }\n}\n\n/**\n * Diff two stylesheet\n *\n * Creates semanticly aware diffs that can easily be applied at runtime.\n * Operations produced by the diff closely resemble the mapbox-gl-js API. Any\n * error creating the diff will fall back to the 'setStyle' operation.\n *\n * Example diff:\n * [\n * { command: 'setConstant', args: ['@water', '#0000FF'] },\n * { command: 'setPaintProperty', args: ['background', 'background-color', 'black'] }\n * ]\n *\n * @private\n * @param {*} [before] stylesheet to compare from\n * @param {*} after stylesheet to compare to\n * @returns Array list of changes\n */\nfunction diffStyles(before, after) {\n if (!before) return [{command: operations.setStyle, args: [after]}];\n\n let commands = [];\n\n try {\n // Handle changes to top-level properties\n if (!isEqual(before.version, after.version)) {\n return [{command: operations.setStyle, args: [after]}];\n }\n if (!isEqual(before.center, after.center)) {\n commands.push({command: operations.setCenter, args: [after.center]});\n }\n if (!isEqual(before.zoom, after.zoom)) {\n commands.push({command: operations.setZoom, args: [after.zoom]});\n }\n if (!isEqual(before.bearing, after.bearing)) {\n commands.push({command: operations.setBearing, args: [after.bearing]});\n }\n if (!isEqual(before.pitch, after.pitch)) {\n commands.push({command: operations.setPitch, args: [after.pitch]});\n }\n if (!isEqual(before.sprite, after.sprite)) {\n commands.push({command: operations.setSprite, args: [after.sprite]});\n }\n if (!isEqual(before.glyphs, after.glyphs)) {\n commands.push({command: operations.setGlyphs, args: [after.glyphs]});\n }\n if (!isEqual(before.transition, after.transition)) {\n commands.push({command: operations.setTransition, args: [after.transition]});\n }\n if (!isEqual(before.light, after.light)) {\n commands.push({command: operations.setLight, args: [after.light]});\n }\n\n // Handle changes to `sources`\n // If a source is to be removed, we also--before the removeSource\n // command--need to remove all the style layers that depend on it.\n const sourcesRemoved = {};\n\n // First collect the {add,remove}Source commands\n const removeOrAddSourceCommands = [];\n diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved);\n\n // Push a removeLayer command for each style layer that depends on a\n // source that's being removed.\n // Also, exclude any such layers them from the input to `diffLayers`\n // below, so that diffLayers produces the appropriate `addLayers`\n // command\n const beforeLayers = [];\n if (before.layers) {\n before.layers.forEach((layer) => {\n if (sourcesRemoved[layer.source]) {\n commands.push({command: operations.removeLayer, args: [layer.id]});\n } else {\n beforeLayers.push(layer);\n }\n });\n }\n commands = commands.concat(removeOrAddSourceCommands);\n\n // Handle changes to `layers`\n diffLayers(beforeLayers, after.layers, commands);\n\n } catch (e) {\n // fall back to setStyle\n console.warn('Unable to compute style diff:', e);\n commands = [{command: operations.setStyle, args: [after]}];\n }\n\n return commands;\n}\n\nexport default diffStyles;\nexport {operations};\n","// @flow\n\n// Note: Do not inherit from Error. It breaks when transpiling to ES5.\n\nexport default class ValidationError {\n message: string;\n identifier: ?string;\n line: ?number;\n\n constructor(key: ?string, value: ?{ __line__: number }, message: string, identifier: ?string) {\n this.message = (key ? `${key}: ` : '') + message;\n if (identifier) this.identifier = identifier;\n\n if (value !== null && value !== undefined && value.__line__) {\n this.line = value.__line__;\n }\n }\n}\n","// @flow\n\n// Note: Do not inherit from Error. It breaks when transpiling to ES5.\n\nexport default class ParsingError {\n message: string;\n error: Error;\n line: number;\n\n constructor(error: Error) {\n this.error = error;\n this.message = error.message;\n const match = error.message.match(/line (\\d+)/);\n this.line = match ? parseInt(match[1], 10) : 0;\n }\n}\n","\nimport ValidationError from '../error/validation_error';\n\nexport default function validateConstants(options) {\n const key = options.key;\n const constants = options.value;\n\n if (constants) {\n return [new ValidationError(key, constants, 'constants have been deprecated as of v8')];\n } else {\n return [];\n }\n}\n","// @flow\n\n// Turn jsonlint-lines-primitives objects into primitive objects\nexport function unbundle(value: mixed) {\n if (value instanceof Number || value instanceof String || value instanceof Boolean) {\n return value.valueOf();\n } else {\n return value;\n }\n}\n\nexport function deepUnbundle(value: mixed): mixed {\n if (Array.isArray(value)) {\n return value.map(deepUnbundle);\n } else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) {\n const unbundledValue: { [key: string]: mixed } = {};\n for (const key in value) {\n unbundledValue[key] = deepUnbundle(value[key]);\n }\n return unbundledValue;\n }\n\n return unbundle(value);\n}\n","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport validateSpec from './validate';\n\nexport default function validateObject(options) {\n const key = options.key;\n const object = options.value;\n const elementSpecs = options.valueSpec || {};\n const elementValidators = options.objectElementValidators || {};\n const style = options.style;\n const styleSpec = options.styleSpec;\n let errors = [];\n\n const type = getType(object);\n if (type !== 'object') {\n return [new ValidationError(key, object, `object expected, ${type} found`)];\n }\n\n for (const objectKey in object) {\n const elementSpecKey = objectKey.split('.')[0]; // treat 'paint.*' as 'paint'\n const elementSpec = elementSpecs[elementSpecKey] || elementSpecs['*'];\n\n let validateElement;\n if (elementValidators[elementSpecKey]) {\n validateElement = elementValidators[elementSpecKey];\n } else if (elementSpecs[elementSpecKey]) {\n validateElement = validateSpec;\n } else if (elementValidators['*']) {\n validateElement = elementValidators['*'];\n } else if (elementSpecs['*']) {\n validateElement = validateSpec;\n } else {\n errors.push(new ValidationError(key, object[objectKey], `unknown property \"${objectKey}\"`));\n continue;\n }\n\n errors = errors.concat(validateElement({\n key: (key ? `${key}.` : key) + objectKey,\n value: object[objectKey],\n valueSpec: elementSpec,\n style,\n styleSpec,\n object,\n objectKey\n }, object));\n }\n\n for (const elementSpecKey in elementSpecs) {\n // Don't check `required` when there's a custom validator for that property.\n if (elementValidators[elementSpecKey]) {\n continue;\n }\n\n if (elementSpecs[elementSpecKey].required && elementSpecs[elementSpecKey]['default'] === undefined && object[elementSpecKey] === undefined) {\n errors.push(new ValidationError(key, object, `missing required property \"${elementSpecKey}\"`));\n }\n }\n\n return errors;\n}\n","\nimport getType from '../util/get_type';\nimport validate from './validate';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateArray(options) {\n const array = options.value;\n const arraySpec = options.valueSpec;\n const style = options.style;\n const styleSpec = options.styleSpec;\n const key = options.key;\n const validateArrayElement = options.arrayElementValidator || validate;\n\n if (getType(array) !== 'array') {\n return [new ValidationError(key, array, `array expected, ${getType(array)} found`)];\n }\n\n if (arraySpec.length && array.length !== arraySpec.length) {\n return [new ValidationError(key, array, `array length ${arraySpec.length} expected, length ${array.length} found`)];\n }\n\n if (arraySpec['min-length'] && array.length < arraySpec['min-length']) {\n return [new ValidationError(key, array, `array length at least ${arraySpec['min-length']} expected, length ${array.length} found`)];\n }\n\n let arrayElementSpec = {\n \"type\": arraySpec.value,\n \"values\": arraySpec.values\n };\n\n if (styleSpec.$version < 7) {\n arrayElementSpec.function = arraySpec.function;\n }\n\n if (getType(arraySpec.value) === 'object') {\n arrayElementSpec = arraySpec.value;\n }\n\n let errors = [];\n for (let i = 0; i < array.length; i++) {\n errors = errors.concat(validateArrayElement({\n array,\n arrayIndex: i,\n value: array[i],\n valueSpec: arrayElementSpec,\n style,\n styleSpec,\n key: `${key}[${i}]`\n }));\n }\n return errors;\n}\n","\nimport getType from '../util/get_type';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateNumber(options) {\n const key = options.key;\n const value = options.value;\n const valueSpec = options.valueSpec;\n let type = getType(value);\n\n // eslint-disable-next-line no-self-compare\n if (type === 'number' && value !== value) {\n type = 'NaN';\n }\n\n if (type !== 'number') {\n return [new ValidationError(key, value, `number expected, ${type} found`)];\n }\n\n if ('minimum' in valueSpec && value < valueSpec.minimum) {\n return [new ValidationError(key, value, `${value} is less than the minimum value ${valueSpec.minimum}`)];\n }\n\n if ('maximum' in valueSpec && value > valueSpec.maximum) {\n return [new ValidationError(key, value, `${value} is greater than the maximum value ${valueSpec.maximum}`)];\n }\n\n return [];\n}\n","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport validate from './validate';\nimport validateObject from './validate_object';\nimport validateArray from './validate_array';\nimport validateNumber from './validate_number';\nimport {isExpression} from '../expression';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint';\nimport {\n supportsPropertyExpression,\n supportsZoomExpression,\n supportsInterpolation\n} from '../util/properties';\n\nexport default function validateFunction(options) {\n const functionValueSpec = options.valueSpec;\n const functionType = unbundle(options.value.type);\n let stopKeyType;\n let stopDomainValues = {};\n let previousStopDomainValue;\n let previousStopDomainZoom;\n\n const isZoomFunction = functionType !== 'categorical' && options.value.property === undefined;\n const isPropertyFunction = !isZoomFunction;\n const isZoomAndPropertyFunction =\n getType(options.value.stops) === 'array' &&\n getType(options.value.stops[0]) === 'array' &&\n getType(options.value.stops[0][0]) === 'object';\n\n const errors = validateObject({\n key: options.key,\n value: options.value,\n valueSpec: options.styleSpec.function,\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {\n stops: validateFunctionStops,\n default: validateFunctionDefault\n }\n });\n\n if (functionType === 'identity' && isZoomFunction) {\n errors.push(new ValidationError(options.key, options.value, 'missing required property \"property\"'));\n }\n\n if (functionType !== 'identity' && !options.value.stops) {\n errors.push(new ValidationError(options.key, options.value, 'missing required property \"stops\"'));\n }\n\n if (functionType === 'exponential' && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) {\n errors.push(new ValidationError(options.key, options.value, 'exponential functions not supported'));\n }\n\n if (options.styleSpec.$version >= 8) {\n if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) {\n errors.push(new ValidationError(options.key, options.value, 'property functions not supported'));\n } else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) {\n errors.push(new ValidationError(options.key, options.value, 'zoom functions not supported'));\n }\n }\n\n if ((functionType === 'categorical' || isZoomAndPropertyFunction) && options.value.property === undefined) {\n errors.push(new ValidationError(options.key, options.value, '\"property\" property is required'));\n }\n\n return errors;\n\n function validateFunctionStops(options) {\n if (functionType === 'identity') {\n return [new ValidationError(options.key, options.value, 'identity function may not have a \"stops\" property')];\n }\n\n let errors = [];\n const value = options.value;\n\n errors = errors.concat(validateArray({\n key: options.key,\n value,\n valueSpec: options.valueSpec,\n style: options.style,\n styleSpec: options.styleSpec,\n arrayElementValidator: validateFunctionStop\n }));\n\n if (getType(value) === 'array' && value.length === 0) {\n errors.push(new ValidationError(options.key, value, 'array must have at least one stop'));\n }\n\n return errors;\n }\n\n function validateFunctionStop(options) {\n let errors = [];\n const value = options.value;\n const key = options.key;\n\n if (getType(value) !== 'array') {\n return [new ValidationError(key, value, `array expected, ${getType(value)} found`)];\n }\n\n if (value.length !== 2) {\n return [new ValidationError(key, value, `array length 2 expected, length ${value.length} found`)];\n }\n\n if (isZoomAndPropertyFunction) {\n if (getType(value[0]) !== 'object') {\n return [new ValidationError(key, value, `object expected, ${getType(value[0])} found`)];\n }\n if (value[0].zoom === undefined) {\n return [new ValidationError(key, value, 'object stop key must have zoom')];\n }\n if (value[0].value === undefined) {\n return [new ValidationError(key, value, 'object stop key must have value')];\n }\n if (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) {\n return [new ValidationError(key, value[0].zoom, 'stop zoom values must appear in ascending order')];\n }\n if (unbundle(value[0].zoom) !== previousStopDomainZoom) {\n previousStopDomainZoom = unbundle(value[0].zoom);\n previousStopDomainValue = undefined;\n stopDomainValues = {};\n }\n errors = errors.concat(validateObject({\n key: `${key}[0]`,\n value: value[0],\n valueSpec: {zoom: {}},\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {zoom: validateNumber, value: validateStopDomainValue}\n }));\n } else {\n errors = errors.concat(validateStopDomainValue({\n key: `${key}[0]`,\n value: value[0],\n valueSpec: {},\n style: options.style,\n styleSpec: options.styleSpec\n }, value));\n }\n\n if (isExpression(deepUnbundle(value[1]))) {\n return errors.concat([new ValidationError(`${key}[1]`, value[1], 'expressions are not allowed in function stops.')]);\n }\n\n return errors.concat(validate({\n key: `${key}[1]`,\n value: value[1],\n valueSpec: functionValueSpec,\n style: options.style,\n styleSpec: options.styleSpec\n }));\n }\n\n function validateStopDomainValue(options, stop) {\n const type = getType(options.value);\n const value = unbundle(options.value);\n\n const reportValue = options.value !== null ? options.value : stop;\n\n if (!stopKeyType) {\n stopKeyType = type;\n } else if (type !== stopKeyType) {\n return [new ValidationError(options.key, reportValue, `${type} stop domain type must match previous stop domain type ${stopKeyType}`)];\n }\n\n if (type !== 'number' && type !== 'string' && type !== 'boolean') {\n return [new ValidationError(options.key, reportValue, 'stop domain value must be a number, string, or boolean')];\n }\n\n if (type !== 'number' && functionType !== 'categorical') {\n let message = `number expected, ${type} found`;\n if (supportsPropertyExpression(functionValueSpec) && functionType === undefined) {\n message += '\\nIf you intended to use a categorical function, specify `\"type\": \"categorical\"`.';\n }\n return [new ValidationError(options.key, reportValue, message)];\n }\n\n if (functionType === 'categorical' && type === 'number' && (!isFinite(value) || Math.floor(value) !== value)) {\n return [new ValidationError(options.key, reportValue, `integer expected, found ${value}`)];\n }\n\n if (functionType !== 'categorical' && type === 'number' && previousStopDomainValue !== undefined && value < previousStopDomainValue) {\n return [new ValidationError(options.key, reportValue, 'stop domain values must appear in ascending order')];\n } else {\n previousStopDomainValue = value;\n }\n\n if (functionType === 'categorical' && value in stopDomainValues) {\n return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')];\n } else {\n stopDomainValues[value] = true;\n }\n\n return [];\n }\n\n function validateFunctionDefault(options) {\n return validate({\n key: options.key,\n value: options.value,\n valueSpec: functionValueSpec,\n style: options.style,\n styleSpec: options.styleSpec\n });\n }\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error';\n\nimport {createExpression, createPropertyExpression} from '../expression';\nimport {deepUnbundle} from '../util/unbundle_jsonlint';\nimport {isStateConstant, isGlobalPropertyConstant, isFeatureConstant} from '../expression/is_constant';\n\nexport default function validateExpression(options: any): Array {\n const expression = (options.expressionContext === 'property' ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec);\n if (expression.result === 'error') {\n return expression.value.map((error) => {\n return new ValidationError(`${options.key}${error.key}`, options.value, error.message);\n });\n }\n\n const expressionObj = (expression.value: any).expression || (expression.value: any)._styleExpression.expression;\n\n if (options.expressionContext === 'property' && (options.propertyKey === 'text-font') &&\n !expressionObj.outputDefined()) {\n return [new ValidationError(options.key, options.value, `Invalid data expression for \"${options.propertyKey}\". Output values must be contained as literals within the expression.`)];\n }\n\n if (options.expressionContext === 'property' && options.propertyType === 'layout' &&\n (!isStateConstant(expressionObj))) {\n return [new ValidationError(options.key, options.value, '\"feature-state\" data expressions are not supported with layout properties.')];\n }\n\n if (options.expressionContext === 'filter' && !isStateConstant(expressionObj)) {\n return [new ValidationError(options.key, options.value, '\"feature-state\" data expressions are not supported with filters.')];\n }\n\n if (options.expressionContext && options.expressionContext.indexOf('cluster') === 0) {\n if (!isGlobalPropertyConstant(expressionObj, ['zoom', 'feature-state'])) {\n return [new ValidationError(options.key, options.value, '\"zoom\" and \"feature-state\" expressions are not supported with cluster properties.')];\n }\n if (options.expressionContext === 'cluster-initial' && !isFeatureConstant(expressionObj)) {\n return [new ValidationError(options.key, options.value, 'Feature data expressions are not supported with initial expression part of cluster properties.')];\n }\n }\n\n return [];\n}\n","\nimport getType from '../util/get_type';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateBoolean(options) {\n const value = options.value;\n const key = options.key;\n const type = getType(value);\n\n if (type !== 'boolean') {\n return [new ValidationError(key, value, `boolean expected, ${type} found`)];\n }\n\n return [];\n}\n","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport {parseCSSColor} from 'csscolorparser';\n\nexport default function validateColor(options) {\n const key = options.key;\n const value = options.value;\n const type = getType(value);\n\n if (type !== 'string') {\n return [new ValidationError(key, value, `color expected, ${type} found`)];\n }\n\n if (parseCSSColor(value) === null) {\n return [new ValidationError(key, value, `color expected, \"${value}\" found`)];\n }\n\n return [];\n}\n","\nimport ValidationError from '../error/validation_error';\nimport {unbundle} from '../util/unbundle_jsonlint';\n\nexport default function validateEnum(options) {\n const key = options.key;\n const value = options.value;\n const valueSpec = options.valueSpec;\n const errors = [];\n\n if (Array.isArray(valueSpec.values)) { // <=v7\n if (valueSpec.values.indexOf(unbundle(value)) === -1) {\n errors.push(new ValidationError(key, value, `expected one of [${valueSpec.values.join(', ')}], ${JSON.stringify(value)} found`));\n }\n } else { // >=v8\n if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) {\n errors.push(new ValidationError(key, value, `expected one of [${Object.keys(valueSpec.values).join(', ')}], ${JSON.stringify(value)} found`));\n }\n }\n return errors;\n}\n","\nimport ValidationError from '../error/validation_error';\nimport validateExpression from './validate_expression';\nimport validateEnum from './validate_enum';\nimport getType from '../util/get_type';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint';\nimport extend from '../util/extend';\nimport {isExpressionFilter} from '../feature_filter';\n\nexport default function validateFilter(options) {\n if (isExpressionFilter(deepUnbundle(options.value))) {\n return validateExpression(extend({}, options, {\n expressionContext: 'filter',\n valueSpec: {value: 'boolean'}\n }));\n } else {\n return validateNonExpressionFilter(options);\n }\n}\n\nfunction validateNonExpressionFilter(options) {\n const value = options.value;\n const key = options.key;\n\n if (getType(value) !== 'array') {\n return [new ValidationError(key, value, `array expected, ${getType(value)} found`)];\n }\n\n const styleSpec = options.styleSpec;\n let type;\n\n let errors = [];\n\n if (value.length < 1) {\n return [new ValidationError(key, value, 'filter array must have at least 1 element')];\n }\n\n errors = errors.concat(validateEnum({\n key: `${key}[0]`,\n value: value[0],\n valueSpec: styleSpec.filter_operator,\n style: options.style,\n styleSpec: options.styleSpec\n }));\n\n switch (unbundle(value[0])) {\n case '<':\n case '<=':\n case '>':\n case '>=':\n if (value.length >= 2 && unbundle(value[1]) === '$type') {\n errors.push(new ValidationError(key, value, `\"$type\" cannot be use with operator \"${value[0]}\"`));\n }\n /* falls through */\n case '==':\n case '!=':\n if (value.length !== 3) {\n errors.push(new ValidationError(key, value, `filter array for operator \"${value[0]}\" must have 3 elements`));\n }\n /* falls through */\n case 'in':\n case '!in':\n if (value.length >= 2) {\n type = getType(value[1]);\n if (type !== 'string') {\n errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`));\n }\n }\n for (let i = 2; i < value.length; i++) {\n type = getType(value[i]);\n if (unbundle(value[1]) === '$type') {\n errors = errors.concat(validateEnum({\n key: `${key}[${i}]`,\n value: value[i],\n valueSpec: styleSpec.geometry_type,\n style: options.style,\n styleSpec: options.styleSpec\n }));\n } else if (type !== 'string' && type !== 'number' && type !== 'boolean') {\n errors.push(new ValidationError(`${key}[${i}]`, value[i], `string, number, or boolean expected, ${type} found`));\n }\n }\n break;\n\n case 'any':\n case 'all':\n case 'none':\n for (let i = 1; i < value.length; i++) {\n errors = errors.concat(validateNonExpressionFilter({\n key: `${key}[${i}]`,\n value: value[i],\n style: options.style,\n styleSpec: options.styleSpec\n }));\n }\n break;\n\n case 'has':\n case '!has':\n type = getType(value[1]);\n if (value.length !== 2) {\n errors.push(new ValidationError(key, value, `filter array for \"${value[0]}\" operator must have 2 elements`));\n } else if (type !== 'string') {\n errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`));\n }\n break;\n case 'within':\n type = getType(value[1]);\n if (value.length !== 2) {\n errors.push(new ValidationError(key, value, `filter array for \"${value[0]}\" operator must have 2 elements`));\n } else if (type !== 'object') {\n errors.push(new ValidationError(`${key}[1]`, value[1], `object expected, ${type} found`));\n }\n break;\n }\n return errors;\n}\n","\nimport validate from './validate';\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport {isFunction} from '../function';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint';\nimport {supportsPropertyExpression} from '../util/properties';\n\nexport default function validateProperty(options, propertyType) {\n const key = options.key;\n const style = options.style;\n const styleSpec = options.styleSpec;\n const value = options.value;\n const propertyKey = options.objectKey;\n const layerSpec = styleSpec[`${propertyType}_${options.layerType}`];\n\n if (!layerSpec) return [];\n\n const transitionMatch = propertyKey.match(/^(.*)-transition$/);\n if (propertyType === 'paint' && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) {\n return validate({\n key,\n value,\n valueSpec: styleSpec.transition,\n style,\n styleSpec\n });\n }\n\n const valueSpec = options.valueSpec || layerSpec[propertyKey];\n if (!valueSpec) {\n return [new ValidationError(key, value, `unknown property \"${propertyKey}\"`)];\n }\n\n let tokenMatch;\n if (getType(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) {\n return [new ValidationError(\n key, value,\n `\"${propertyKey}\" does not support interpolation syntax\\n` +\n `Use an identity property function instead: \\`{ \"type\": \"identity\", \"property\": ${JSON.stringify(tokenMatch[1])} }\\`.`)];\n }\n\n const errors = [];\n\n if (options.layerType === 'symbol') {\n if (propertyKey === 'text-field' && style && !style.glyphs) {\n errors.push(new ValidationError(key, value, 'use of \"text-field\" requires a style \"glyphs\" property'));\n }\n if (propertyKey === 'text-font' && isFunction(deepUnbundle(value)) && unbundle(value.type) === 'identity') {\n errors.push(new ValidationError(key, value, '\"text-font\" does not support identity functions'));\n }\n }\n\n return errors.concat(validate({\n key: options.key,\n value,\n valueSpec,\n style,\n styleSpec,\n expressionContext: 'property',\n propertyType,\n propertyKey\n }));\n}\n","\nimport validateProperty from './validate_property';\n\nexport default function validatePaintProperty(options) {\n return validateProperty(options, 'paint');\n}\n","\nimport validateProperty from './validate_property';\n\nexport default function validateLayoutProperty(options) {\n return validateProperty(options, 'layout');\n}\n","\nimport ValidationError from '../error/validation_error';\nimport {unbundle} from '../util/unbundle_jsonlint';\nimport validateObject from './validate_object';\nimport validateFilter from './validate_filter';\nimport validatePaintProperty from './validate_paint_property';\nimport validateLayoutProperty from './validate_layout_property';\nimport validateSpec from './validate';\nimport extend from '../util/extend';\n\nexport default function validateLayer(options) {\n let errors = [];\n\n const layer = options.value;\n const key = options.key;\n const style = options.style;\n const styleSpec = options.styleSpec;\n\n if (!layer.type && !layer.ref) {\n errors.push(new ValidationError(key, layer, 'either \"type\" or \"ref\" is required'));\n }\n let type = unbundle(layer.type);\n const ref = unbundle(layer.ref);\n\n if (layer.id) {\n const layerId = unbundle(layer.id);\n for (let i = 0; i < options.arrayIndex; i++) {\n const otherLayer = style.layers[i];\n if (unbundle(otherLayer.id) === layerId) {\n errors.push(new ValidationError(key, layer.id, `duplicate layer id \"${layer.id}\", previously used at line ${otherLayer.id.__line__}`));\n }\n }\n }\n\n if ('ref' in layer) {\n ['type', 'source', 'source-layer', 'filter', 'layout'].forEach((p) => {\n if (p in layer) {\n errors.push(new ValidationError(key, layer[p], `\"${p}\" is prohibited for ref layers`));\n }\n });\n\n let parent;\n\n style.layers.forEach((layer) => {\n if (unbundle(layer.id) === ref) parent = layer;\n });\n\n if (!parent) {\n errors.push(new ValidationError(key, layer.ref, `ref layer \"${ref}\" not found`));\n } else if (parent.ref) {\n errors.push(new ValidationError(key, layer.ref, 'ref cannot reference another ref layer'));\n } else {\n type = unbundle(parent.type);\n }\n } else if (type !== 'background') {\n if (!layer.source) {\n errors.push(new ValidationError(key, layer, 'missing required property \"source\"'));\n } else {\n const source = style.sources && style.sources[layer.source];\n const sourceType = source && unbundle(source.type);\n if (!source) {\n errors.push(new ValidationError(key, layer.source, `source \"${layer.source}\" not found`));\n } else if (sourceType === 'vector' && type === 'raster') {\n errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a raster source`));\n } else if (sourceType === 'raster' && type !== 'raster') {\n errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a vector source`));\n } else if (sourceType === 'vector' && !layer['source-layer']) {\n errors.push(new ValidationError(key, layer, `layer \"${layer.id}\" must specify a \"source-layer\"`));\n } else if (sourceType === 'raster-dem' && type !== 'hillshade') {\n errors.push(new ValidationError(key, layer.source, 'raster-dem source can only be used with layer type \\'hillshade\\'.'));\n } else if (type === 'line' && layer.paint && layer.paint['line-gradient'] &&\n (sourceType !== 'geojson' || !source.lineMetrics)) {\n errors.push(new ValidationError(key, layer, `layer \"${layer.id}\" specifies a line-gradient, which requires a GeoJSON source with \\`lineMetrics\\` enabled.`));\n }\n }\n }\n\n errors = errors.concat(validateObject({\n key,\n value: layer,\n valueSpec: styleSpec.layer,\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {\n '*'() {\n return [];\n },\n // We don't want to enforce the spec's `\"requires\": true` for backward compatibility with refs;\n // the actual requirement is validated above. See https://github.com/mapbox/mapbox-gl-js/issues/5772.\n type() {\n return validateSpec({\n key: `${key}.type`,\n value: layer.type,\n valueSpec: styleSpec.layer.type,\n style: options.style,\n styleSpec: options.styleSpec,\n object: layer,\n objectKey: 'type'\n });\n },\n filter: validateFilter,\n layout(options) {\n return validateObject({\n layer,\n key: options.key,\n value: options.value,\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {\n '*'(options) {\n return validateLayoutProperty(extend({layerType: type}, options));\n }\n }\n });\n },\n paint(options) {\n return validateObject({\n layer,\n key: options.key,\n value: options.value,\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {\n '*'(options) {\n return validatePaintProperty(extend({layerType: type}, options));\n }\n }\n });\n }\n }\n }));\n\n return errors;\n}\n","\nimport getType from '../util/get_type';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateString(options) {\n const value = options.value;\n const key = options.key;\n const type = getType(value);\n\n if (type !== 'string') {\n return [new ValidationError(key, value, `string expected, ${type} found`)];\n }\n\n return [];\n}\n","\nimport ValidationError from '../error/validation_error';\nimport {unbundle} from '../util/unbundle_jsonlint';\nimport validateObject from './validate_object';\nimport validateEnum from './validate_enum';\nimport validateExpression from './validate_expression';\nimport validateString from './validate_string';\nimport getType from '../util/get_type';\n\nconst objectElementValidators = {\n promoteId: validatePromoteId\n};\n\nexport default function validateSource(options) {\n const value = options.value;\n const key = options.key;\n const styleSpec = options.styleSpec;\n const style = options.style;\n\n if (!value.type) {\n return [new ValidationError(key, value, '\"type\" is required')];\n }\n\n const type = unbundle(value.type);\n let errors;\n\n switch (type) {\n case 'vector':\n case 'raster':\n case 'raster-dem':\n errors = validateObject({\n key,\n value,\n valueSpec: styleSpec[`source_${type.replace('-', '_')}`],\n style: options.style,\n styleSpec,\n objectElementValidators\n });\n return errors;\n\n case 'geojson':\n errors = validateObject({\n key,\n value,\n valueSpec: styleSpec.source_geojson,\n style,\n styleSpec,\n objectElementValidators\n });\n if (value.cluster) {\n for (const prop in value.clusterProperties) {\n const [operator, mapExpr] = value.clusterProperties[prop];\n const reduceExpr = typeof operator === 'string' ? [operator, ['accumulated'], ['get', prop]] : operator;\n\n errors.push(...validateExpression({\n key: `${key}.${prop}.map`,\n value: mapExpr,\n expressionContext: 'cluster-map'\n }));\n errors.push(...validateExpression({\n key: `${key}.${prop}.reduce`,\n value: reduceExpr,\n expressionContext: 'cluster-reduce'\n }));\n }\n }\n return errors;\n\n case 'video':\n return validateObject({\n key,\n value,\n valueSpec: styleSpec.source_video,\n style,\n styleSpec\n });\n\n case 'image':\n return validateObject({\n key,\n value,\n valueSpec: styleSpec.source_image,\n style,\n styleSpec\n });\n\n case 'canvas':\n return [new ValidationError(key, null, `Please use runtime APIs to add canvas sources, rather than including them in stylesheets.`, 'source.canvas')];\n\n default:\n return validateEnum({\n key: `${key}.type`,\n value: value.type,\n valueSpec: {values: ['vector', 'raster', 'raster-dem', 'geojson', 'video', 'image']},\n style,\n styleSpec\n });\n }\n}\n\nfunction validatePromoteId({key, value}) {\n if (getType(value) === 'string') {\n return validateString({key, value});\n } else {\n const errors = [];\n for (const prop in value) {\n errors.push(...validateString({key: `${key}.${prop}`, value: value[prop]}));\n }\n return errors;\n }\n}\n","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport validate from './validate';\n\nexport default function validateLight(options) {\n const light = options.value;\n const styleSpec = options.styleSpec;\n const lightSpec = styleSpec.light;\n const style = options.style;\n\n let errors = [];\n\n const rootType = getType(light);\n if (light === undefined) {\n return errors;\n } else if (rootType !== 'object') {\n errors = errors.concat([new ValidationError('light', light, `object expected, ${rootType} found`)]);\n return errors;\n }\n\n for (const key in light) {\n const transitionMatch = key.match(/^(.*)-transition$/);\n\n if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) {\n errors = errors.concat(validate({\n key,\n value: light[key],\n valueSpec: styleSpec.transition,\n style,\n styleSpec\n }));\n } else if (lightSpec[key]) {\n errors = errors.concat(validate({\n key,\n value: light[key],\n valueSpec: lightSpec[key],\n style,\n styleSpec\n }));\n } else {\n errors = errors.concat([new ValidationError(key, light[key], `unknown property \"${key}\"`)]);\n }\n }\n\n return errors;\n}\n","// @flow\nimport validateExpression from './validate_expression';\nimport validateString from './validate_string';\n\nexport default function validateFormatted(options: any) {\n if (validateString(options).length === 0) {\n return [];\n }\n\n return validateExpression(options);\n}\n","// @flow\nimport validateExpression from './validate_expression';\nimport validateString from './validate_string';\n\nexport default function validateImage(options: any) {\n if (validateString(options).length === 0) {\n return [];\n }\n\n return validateExpression(options);\n}\n","\nimport extend from '../util/extend';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint';\nimport {isExpression} from '../expression';\nimport {isFunction} from '../function';\n\nimport validateFunction from './validate_function';\nimport validateExpression from './validate_expression';\nimport validateObject from './validate_object';\nimport validateArray from './validate_array';\nimport validateBoolean from './validate_boolean';\nimport validateNumber from './validate_number';\nimport validateColor from './validate_color';\nimport validateConstants from './validate_constants';\nimport validateEnum from './validate_enum';\nimport validateFilter from './validate_filter';\nimport validateLayer from './validate_layer';\nimport validateSource from './validate_source';\nimport validateLight from './validate_light';\nimport validateString from './validate_string';\nimport validateFormatted from './validate_formatted';\nimport validateImage from './validate_image';\n\nconst VALIDATORS = {\n '*'() {\n return [];\n },\n 'array': validateArray,\n 'boolean': validateBoolean,\n 'number': validateNumber,\n 'color': validateColor,\n 'constants': validateConstants,\n 'enum': validateEnum,\n 'filter': validateFilter,\n 'function': validateFunction,\n 'layer': validateLayer,\n 'object': validateObject,\n 'source': validateSource,\n 'light': validateLight,\n 'string': validateString,\n 'formatted': validateFormatted,\n 'resolvedImage': validateImage\n};\n\n// Main recursive validation function. Tracks:\n//\n// - key: string representing location of validation in style tree. Used only\n// for more informative error reporting.\n// - value: current value from style being evaluated. May be anything from a\n// high level object that needs to be descended into deeper or a simple\n// scalar value.\n// - valueSpec: current spec being evaluated. Tracks value.\n// - styleSpec: current full spec being evaluated.\n\nexport default function validate(options) {\n const value = options.value;\n const valueSpec = options.valueSpec;\n const styleSpec = options.styleSpec;\n\n if (valueSpec.expression && isFunction(unbundle(value))) {\n return validateFunction(options);\n\n } else if (valueSpec.expression && isExpression(deepUnbundle(value))) {\n return validateExpression(options);\n\n } else if (valueSpec.type && VALIDATORS[valueSpec.type]) {\n return VALIDATORS[valueSpec.type](options);\n\n } else {\n const valid = validateObject(extend({}, options, {\n valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec\n }));\n return valid;\n }\n}\n","\nimport ValidationError from '../error/validation_error';\nimport validateString from './validate_string';\n\nexport default function(options) {\n const value = options.value;\n const key = options.key;\n\n const errors = validateString(options);\n if (errors.length) return errors;\n\n if (value.indexOf('{fontstack}') === -1) {\n errors.push(new ValidationError(key, value, '\"glyphs\" url must include a \"{fontstack}\" token'));\n }\n\n if (value.indexOf('{range}') === -1) {\n errors.push(new ValidationError(key, value, '\"glyphs\" url must include a \"{range}\" token'));\n }\n\n return errors;\n}\n","\nimport validateConstants from './validate/validate_constants';\nimport validate from './validate/validate';\nimport latestStyleSpec from './reference/latest';\nimport validateGlyphsURL from './validate/validate_glyphs_url';\n\nimport validateSource from './validate/validate_source';\nimport validateLight from './validate/validate_light';\nimport validateLayer from './validate/validate_layer';\nimport validateFilter from './validate/validate_filter';\nimport validatePaintProperty from './validate/validate_paint_property';\nimport validateLayoutProperty from './validate/validate_layout_property';\n\n/**\n * Validate a Mapbox GL style against the style specification. This entrypoint,\n * `mapbox-gl-style-spec/lib/validate_style.min`, is designed to produce as\n * small a browserify bundle as possible by omitting unnecessary functionality\n * and legacy style specifications.\n *\n * @private\n * @param {Object} style The style to be validated.\n * @param {Object} [styleSpec] The style specification to validate against.\n * If omitted, the latest style spec is used.\n * @returns {Array}\n * @example\n * var validate = require('mapbox-gl-style-spec/lib/validate_style.min');\n * var errors = validate(style);\n */\nfunction validateStyleMin(style, styleSpec = latestStyleSpec) {\n\n let errors = [];\n\n errors = errors.concat(validate({\n key: '',\n value: style,\n valueSpec: styleSpec.$root,\n styleSpec,\n style,\n objectElementValidators: {\n glyphs: validateGlyphsURL,\n '*'() {\n return [];\n }\n }\n }));\n\n if (style.constants) {\n errors = errors.concat(validateConstants({\n key: 'constants',\n value: style.constants,\n style,\n styleSpec\n }));\n }\n\n return sortErrors(errors);\n}\n\nvalidateStyleMin.source = wrapCleanErrors(validateSource);\nvalidateStyleMin.light = wrapCleanErrors(validateLight);\nvalidateStyleMin.layer = wrapCleanErrors(validateLayer);\nvalidateStyleMin.filter = wrapCleanErrors(validateFilter);\nvalidateStyleMin.paintProperty = wrapCleanErrors(validatePaintProperty);\nvalidateStyleMin.layoutProperty = wrapCleanErrors(validateLayoutProperty);\n\nfunction sortErrors(errors) {\n return [].concat(errors).sort((a, b) => {\n return a.line - b.line;\n });\n}\n\nfunction wrapCleanErrors(inner) {\n return function(...args) {\n return sortErrors(inner.apply(this, args));\n };\n}\n\nexport default validateStyleMin;\n","/* parser generated by jison 0.4.15 */\n/*\n Returns a Parser object of the following structure:\n\n Parser: {\n yy: {}\n }\n\n Parser.prototype: {\n yy: {},\n trace: function(),\n symbols_: {associative list: name ==> number},\n terminals_: {associative list: number ==> name},\n productions_: [...],\n performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$),\n table: [...],\n defaultActions: {...},\n parseError: function(str, hash),\n parse: function(input),\n\n lexer: {\n EOF: 1,\n parseError: function(str, hash),\n setInput: function(input),\n input: function(),\n unput: function(str),\n more: function(),\n less: function(n),\n pastInput: function(),\n upcomingInput: function(),\n showPosition: function(),\n test_match: function(regex_match_array, rule_index),\n next: function(),\n lex: function(),\n begin: function(condition),\n popState: function(),\n _currentRules: function(),\n topState: function(),\n pushState: function(condition),\n\n options: {\n ranges: boolean (optional: true ==> token location info will include a .range[] member)\n flex: boolean (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match)\n backtrack_lexer: boolean (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code)\n },\n\n performAction: function(yy, yy_, $avoiding_name_collisions, YY_START),\n rules: [...],\n conditions: {associative list: name ==> set},\n }\n }\n\n\n token location info (@$, _$, etc.): {\n first_line: n,\n last_line: n,\n first_column: n,\n last_column: n,\n range: [start_number, end_number] (where the numbers are indexes into the input string, regular zero-based)\n }\n\n\n the parseError function receives a 'hash' object with these members for lexer and parser errors: {\n text: (matched text)\n token: (the produced terminal token, if any)\n line: (yylineno)\n }\n while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: {\n loc: (yylloc)\n expected: (string describing the set of expected tokens)\n recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error)\n }\n*/\nvar parser = (function(){\nvar o=function(k,v,o,l){for(o=o||{},l=k.length;l--;o[k[l]]=v);return o},$V0=[1,12],$V1=[1,13],$V2=[1,9],$V3=[1,10],$V4=[1,11],$V5=[1,14],$V6=[1,15],$V7=[14,18,22,24],$V8=[18,22],$V9=[22,24];\nvar parser = {trace: function trace() { },\nyy: {},\nsymbols_: {\"error\":2,\"JSONString\":3,\"STRING\":4,\"JSONNumber\":5,\"NUMBER\":6,\"JSONNullLiteral\":7,\"NULL\":8,\"JSONBooleanLiteral\":9,\"TRUE\":10,\"FALSE\":11,\"JSONText\":12,\"JSONValue\":13,\"EOF\":14,\"JSONObject\":15,\"JSONArray\":16,\"{\":17,\"}\":18,\"JSONMemberList\":19,\"JSONMember\":20,\":\":21,\",\":22,\"[\":23,\"]\":24,\"JSONElementList\":25,\"$accept\":0,\"$end\":1},\nterminals_: {2:\"error\",4:\"STRING\",6:\"NUMBER\",8:\"NULL\",10:\"TRUE\",11:\"FALSE\",14:\"EOF\",17:\"{\",18:\"}\",21:\":\",22:\",\",23:\"[\",24:\"]\"},\nproductions_: [0,[3,1],[5,1],[7,1],[9,1],[9,1],[12,2],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[15,2],[15,3],[20,3],[19,1],[19,3],[16,2],[16,3],[25,1],[25,3]],\nperformAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */) {\n/* this == yyval */\n\nvar $0 = $$.length - 1;\nswitch (yystate) {\ncase 1:\n // replace escaped characters with actual character\n this.$ = new String(yytext.replace(/\\\\(\\\\|\")/g, \"$\"+\"1\")\n .replace(/\\\\n/g,'\\n')\n .replace(/\\\\r/g,'\\r')\n .replace(/\\\\t/g,'\\t')\n .replace(/\\\\v/g,'\\v')\n .replace(/\\\\f/g,'\\f')\n .replace(/\\\\b/g,'\\b'));\n this.$.__line__ = this._$.first_line;\n \nbreak;\ncase 2:\n\n this.$ = new Number(yytext);\n this.$.__line__ = this._$.first_line;\n \nbreak;\ncase 3:\n\n this.$ = null;\n \nbreak;\ncase 4:\n\n this.$ = new Boolean(true);\n this.$.__line__ = this._$.first_line;\n \nbreak;\ncase 5:\n\n this.$ = new Boolean(false);\n this.$.__line__ = this._$.first_line;\n \nbreak;\ncase 6:\nreturn this.$ = $$[$0-1];\nbreak;\ncase 13:\nthis.$ = {}; Object.defineProperty(this.$, '__line__', {\n value: this._$.first_line,\n enumerable: false\n })\nbreak;\ncase 14: case 19:\nthis.$ = $$[$0-1]; Object.defineProperty(this.$, '__line__', {\n value: this._$.first_line,\n enumerable: false\n })\nbreak;\ncase 15:\nthis.$ = [$$[$0-2], $$[$0]];\nbreak;\ncase 16:\nthis.$ = {}; this.$[$$[$0][0]] = $$[$0][1];\nbreak;\ncase 17:\nthis.$ = $$[$0-2]; $$[$0-2][$$[$0][0]] = $$[$0][1];\nbreak;\ncase 18:\nthis.$ = []; Object.defineProperty(this.$, '__line__', {\n value: this._$.first_line,\n enumerable: false\n })\nbreak;\ncase 20:\nthis.$ = [$$[$0]];\nbreak;\ncase 21:\nthis.$ = $$[$0-2]; $$[$0-2].push($$[$0]);\nbreak;\n}\n},\ntable: [{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,12:1,13:2,15:7,16:8,17:$V5,23:$V6},{1:[3]},{14:[1,16]},o($V7,[2,7]),o($V7,[2,8]),o($V7,[2,9]),o($V7,[2,10]),o($V7,[2,11]),o($V7,[2,12]),o($V7,[2,3]),o($V7,[2,4]),o($V7,[2,5]),o([14,18,21,22,24],[2,1]),o($V7,[2,2]),{3:20,4:$V0,18:[1,17],19:18,20:19},{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,13:23,15:7,16:8,17:$V5,23:$V6,24:[1,21],25:22},{1:[2,6]},o($V7,[2,13]),{18:[1,24],22:[1,25]},o($V8,[2,16]),{21:[1,26]},o($V7,[2,18]),{22:[1,28],24:[1,27]},o($V9,[2,20]),o($V7,[2,14]),{3:20,4:$V0,20:29},{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,13:30,15:7,16:8,17:$V5,23:$V6},o($V7,[2,19]),{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,13:31,15:7,16:8,17:$V5,23:$V6},o($V8,[2,17]),o($V8,[2,15]),o($V9,[2,21])],\ndefaultActions: {16:[2,6]},\nparseError: function parseError(str, hash) {\n if (hash.recoverable) {\n this.trace(str);\n } else {\n throw new Error(str);\n }\n},\nparse: function parse(input) {\n var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = '', yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;\n var args = lstack.slice.call(arguments, 1);\n var lexer = Object.create(this.lexer);\n var sharedState = { yy: {} };\n for (var k in this.yy) {\n if (Object.prototype.hasOwnProperty.call(this.yy, k)) {\n sharedState.yy[k] = this.yy[k];\n }\n }\n lexer.setInput(input, sharedState.yy);\n sharedState.yy.lexer = lexer;\n sharedState.yy.parser = this;\n if (typeof lexer.yylloc == 'undefined') {\n lexer.yylloc = {};\n }\n var yyloc = lexer.yylloc;\n lstack.push(yyloc);\n var ranges = lexer.options && lexer.options.ranges;\n if (typeof sharedState.yy.parseError === 'function') {\n this.parseError = sharedState.yy.parseError;\n } else {\n this.parseError = Object.getPrototypeOf(this).parseError;\n }\n function popStack(n) {\n stack.length = stack.length - 2 * n;\n vstack.length = vstack.length - n;\n lstack.length = lstack.length - n;\n }\n _token_stack:\n function lex() {\n var token;\n token = lexer.lex() || EOF;\n if (typeof token !== 'number') {\n token = self.symbols_[token] || token;\n }\n return token;\n }\n var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;\n while (true) {\n state = stack[stack.length - 1];\n if (this.defaultActions[state]) {\n action = this.defaultActions[state];\n } else {\n if (symbol === null || typeof symbol == 'undefined') {\n symbol = lex();\n }\n action = table[state] && table[state][symbol];\n }\n if (typeof action === 'undefined' || !action.length || !action[0]) {\n var errStr = '';\n expected = [];\n for (p in table[state]) {\n if (this.terminals_[p] && p > TERROR) {\n expected.push('\\'' + this.terminals_[p] + '\\'');\n }\n }\n if (lexer.showPosition) {\n errStr = 'Parse error on line ' + (yylineno + 1) + ':\\n' + lexer.showPosition() + '\\nExpecting ' + expected.join(', ') + ', got \\'' + (this.terminals_[symbol] || symbol) + '\\'';\n } else {\n errStr = 'Parse error on line ' + (yylineno + 1) + ': Unexpected ' + (symbol == EOF ? 'end of input' : '\\'' + (this.terminals_[symbol] || symbol) + '\\'');\n }\n this.parseError(errStr, {\n text: lexer.match,\n token: this.terminals_[symbol] || symbol,\n line: lexer.yylineno,\n loc: yyloc,\n expected: expected\n });\n }\n if (action[0] instanceof Array && action.length > 1) {\n throw new Error('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol);\n }\n switch (action[0]) {\n case 1:\n stack.push(symbol);\n vstack.push(lexer.yytext);\n lstack.push(lexer.yylloc);\n stack.push(action[1]);\n symbol = null;\n if (!preErrorSymbol) {\n yyleng = lexer.yyleng;\n yytext = lexer.yytext;\n yylineno = lexer.yylineno;\n yyloc = lexer.yylloc;\n if (recovering > 0) {\n recovering--;\n }\n } else {\n symbol = preErrorSymbol;\n preErrorSymbol = null;\n }\n break;\n case 2:\n len = this.productions_[action[1]][1];\n yyval.$ = vstack[vstack.length - len];\n yyval._$ = {\n first_line: lstack[lstack.length - (len || 1)].first_line,\n last_line: lstack[lstack.length - 1].last_line,\n first_column: lstack[lstack.length - (len || 1)].first_column,\n last_column: lstack[lstack.length - 1].last_column\n };\n if (ranges) {\n yyval._$.range = [\n lstack[lstack.length - (len || 1)].range[0],\n lstack[lstack.length - 1].range[1]\n ];\n }\n r = this.performAction.apply(yyval, [\n yytext,\n yyleng,\n yylineno,\n sharedState.yy,\n action[1],\n vstack,\n lstack\n ].concat(args));\n if (typeof r !== 'undefined') {\n return r;\n }\n if (len) {\n stack = stack.slice(0, -1 * len * 2);\n vstack = vstack.slice(0, -1 * len);\n lstack = lstack.slice(0, -1 * len);\n }\n stack.push(this.productions_[action[1]][0]);\n vstack.push(yyval.$);\n lstack.push(yyval._$);\n newState = table[stack[stack.length - 2]][stack[stack.length - 1]];\n stack.push(newState);\n break;\n case 3:\n return true;\n }\n }\n return true;\n}};\n/* generated by jison-lex 0.3.4 */\nvar lexer = (function(){\nvar lexer = ({\n\nEOF:1,\n\nparseError:function parseError(str, hash) {\n if (this.yy.parser) {\n this.yy.parser.parseError(str, hash);\n } else {\n throw new Error(str);\n }\n },\n\n// resets the lexer, sets new input\nsetInput:function (input, yy) {\n this.yy = yy || this.yy || {};\n this._input = input;\n this._more = this._backtrack = this.done = false;\n this.yylineno = this.yyleng = 0;\n this.yytext = this.matched = this.match = '';\n this.conditionStack = ['INITIAL'];\n this.yylloc = {\n first_line: 1,\n first_column: 0,\n last_line: 1,\n last_column: 0\n };\n if (this.options.ranges) {\n this.yylloc.range = [0,0];\n }\n this.offset = 0;\n return this;\n },\n\n// consumes and returns one char from the input\ninput:function () {\n var ch = this._input[0];\n this.yytext += ch;\n this.yyleng++;\n this.offset++;\n this.match += ch;\n this.matched += ch;\n var lines = ch.match(/(?:\\r\\n?|\\n).*/g);\n if (lines) {\n this.yylineno++;\n this.yylloc.last_line++;\n } else {\n this.yylloc.last_column++;\n }\n if (this.options.ranges) {\n this.yylloc.range[1]++;\n }\n\n this._input = this._input.slice(1);\n return ch;\n },\n\n// unshifts one char (or a string) into the input\nunput:function (ch) {\n var len = ch.length;\n var lines = ch.split(/(?:\\r\\n?|\\n)/g);\n\n this._input = ch + this._input;\n this.yytext = this.yytext.substr(0, this.yytext.length - len);\n //this.yyleng -= len;\n this.offset -= len;\n var oldLines = this.match.split(/(?:\\r\\n?|\\n)/g);\n this.match = this.match.substr(0, this.match.length - 1);\n this.matched = this.matched.substr(0, this.matched.length - 1);\n\n if (lines.length - 1) {\n this.yylineno -= lines.length - 1;\n }\n var r = this.yylloc.range;\n\n this.yylloc = {\n first_line: this.yylloc.first_line,\n last_line: this.yylineno + 1,\n first_column: this.yylloc.first_column,\n last_column: lines ?\n (lines.length === oldLines.length ? this.yylloc.first_column : 0)\n + oldLines[oldLines.length - lines.length].length - lines[0].length :\n this.yylloc.first_column - len\n };\n\n if (this.options.ranges) {\n this.yylloc.range = [r[0], r[0] + this.yyleng - len];\n }\n this.yyleng = this.yytext.length;\n return this;\n },\n\n// When called from action, caches matched text and appends it on next action\nmore:function () {\n this._more = true;\n return this;\n },\n\n// When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead.\nreject:function () {\n if (this.options.backtrack_lexer) {\n this._backtrack = true;\n } else {\n return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\\n' + this.showPosition(), {\n text: \"\",\n token: null,\n line: this.yylineno\n });\n\n }\n return this;\n },\n\n// retain first n characters of the match\nless:function (n) {\n this.unput(this.match.slice(n));\n },\n\n// displays already matched input, i.e. for error messages\npastInput:function () {\n var past = this.matched.substr(0, this.matched.length - this.match.length);\n return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\\n/g, \"\");\n },\n\n// displays upcoming input, i.e. for error messages\nupcomingInput:function () {\n var next = this.match;\n if (next.length < 20) {\n next += this._input.substr(0, 20-next.length);\n }\n return (next.substr(0,20) + (next.length > 20 ? '...' : '')).replace(/\\n/g, \"\");\n },\n\n// displays the character position where the lexing error occurred, i.e. for error messages\nshowPosition:function () {\n var pre = this.pastInput();\n var c = new Array(pre.length + 1).join(\"-\");\n return pre + this.upcomingInput() + \"\\n\" + c + \"^\";\n },\n\n// test the lexed token: return FALSE when not a match, otherwise return token\ntest_match:function (match, indexed_rule) {\n var token,\n lines,\n backup;\n\n if (this.options.backtrack_lexer) {\n // save context\n backup = {\n yylineno: this.yylineno,\n yylloc: {\n first_line: this.yylloc.first_line,\n last_line: this.last_line,\n first_column: this.yylloc.first_column,\n last_column: this.yylloc.last_column\n },\n yytext: this.yytext,\n match: this.match,\n matches: this.matches,\n matched: this.matched,\n yyleng: this.yyleng,\n offset: this.offset,\n _more: this._more,\n _input: this._input,\n yy: this.yy,\n conditionStack: this.conditionStack.slice(0),\n done: this.done\n };\n if (this.options.ranges) {\n backup.yylloc.range = this.yylloc.range.slice(0);\n }\n }\n\n lines = match[0].match(/(?:\\r\\n?|\\n).*/g);\n if (lines) {\n this.yylineno += lines.length;\n }\n this.yylloc = {\n first_line: this.yylloc.last_line,\n last_line: this.yylineno + 1,\n first_column: this.yylloc.last_column,\n last_column: lines ?\n lines[lines.length - 1].length - lines[lines.length - 1].match(/\\r?\\n?/)[0].length :\n this.yylloc.last_column + match[0].length\n };\n this.yytext += match[0];\n this.match += match[0];\n this.matches = match;\n this.yyleng = this.yytext.length;\n if (this.options.ranges) {\n this.yylloc.range = [this.offset, this.offset += this.yyleng];\n }\n this._more = false;\n this._backtrack = false;\n this._input = this._input.slice(match[0].length);\n this.matched += match[0];\n token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]);\n if (this.done && this._input) {\n this.done = false;\n }\n if (token) {\n return token;\n } else if (this._backtrack) {\n // recover context\n for (var k in backup) {\n this[k] = backup[k];\n }\n return false; // rule action called reject() implying the next rule should be tested instead.\n }\n return false;\n },\n\n// return next match in input\nnext:function () {\n if (this.done) {\n return this.EOF;\n }\n if (!this._input) {\n this.done = true;\n }\n\n var token,\n match,\n tempMatch,\n index;\n if (!this._more) {\n this.yytext = '';\n this.match = '';\n }\n var rules = this._currentRules();\n for (var i = 0; i < rules.length; i++) {\n tempMatch = this._input.match(this.rules[rules[i]]);\n if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {\n match = tempMatch;\n index = i;\n if (this.options.backtrack_lexer) {\n token = this.test_match(tempMatch, rules[i]);\n if (token !== false) {\n return token;\n } else if (this._backtrack) {\n match = false;\n continue; // rule action called reject() implying a rule MISmatch.\n } else {\n // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)\n return false;\n }\n } else if (!this.options.flex) {\n break;\n }\n }\n }\n if (match) {\n token = this.test_match(match, rules[index]);\n if (token !== false) {\n return token;\n }\n // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)\n return false;\n }\n if (this._input === \"\") {\n return this.EOF;\n } else {\n return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\\n' + this.showPosition(), {\n text: \"\",\n token: null,\n line: this.yylineno\n });\n }\n },\n\n// return next match that has a token\nlex:function lex() {\n var r = this.next();\n if (r) {\n return r;\n } else {\n return this.lex();\n }\n },\n\n// activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)\nbegin:function begin(condition) {\n this.conditionStack.push(condition);\n },\n\n// pop the previously active lexer condition state off the condition stack\npopState:function popState() {\n var n = this.conditionStack.length - 1;\n if (n > 0) {\n return this.conditionStack.pop();\n } else {\n return this.conditionStack[0];\n }\n },\n\n// produce the lexer rule set which is active for the currently active lexer condition state\n_currentRules:function _currentRules() {\n if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) {\n return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;\n } else {\n return this.conditions[\"INITIAL\"].rules;\n }\n },\n\n// return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available\ntopState:function topState(n) {\n n = this.conditionStack.length - 1 - Math.abs(n || 0);\n if (n >= 0) {\n return this.conditionStack[n];\n } else {\n return \"INITIAL\";\n }\n },\n\n// alias for begin(condition)\npushState:function pushState(condition) {\n this.begin(condition);\n },\n\n// return the number of states currently on the stack\nstateStackSize:function stateStackSize() {\n return this.conditionStack.length;\n },\noptions: {},\nperformAction: function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) {\nvar YYSTATE=YY_START;\nswitch($avoiding_name_collisions) {\ncase 0:/* skip whitespace */\nbreak;\ncase 1:return 6\nbreak;\ncase 2:yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2); return 4\nbreak;\ncase 3:return 17\nbreak;\ncase 4:return 18\nbreak;\ncase 5:return 23\nbreak;\ncase 6:return 24\nbreak;\ncase 7:return 22\nbreak;\ncase 8:return 21\nbreak;\ncase 9:return 10\nbreak;\ncase 10:return 11\nbreak;\ncase 11:return 8\nbreak;\ncase 12:return 14\nbreak;\ncase 13:return 'INVALID'\nbreak;\n}\n},\nrules: [/^(?:\\s+)/,/^(?:(-?([0-9]|[1-9][0-9]+))(\\.[0-9]+)?([eE][-+]?[0-9]+)?\\b)/,/^(?:\"(?:\\\\[\\\\\"bfnrt/]|\\\\u[a-fA-F0-9]{4}|[^\\\\\\0-\\x09\\x0a-\\x1f\"])*\")/,/^(?:\\{)/,/^(?:\\})/,/^(?:\\[)/,/^(?:\\])/,/^(?:,)/,/^(?::)/,/^(?:true\\b)/,/^(?:false\\b)/,/^(?:null\\b)/,/^(?:$)/,/^(?:.)/],\nconditions: {\"INITIAL\":{\"rules\":[0,1,2,3,4,5,6,7,8,9,10,11,12,13],\"inclusive\":true}}\n});\nreturn lexer;\n})();\nparser.lexer = lexer;\nfunction Parser () {\n this.yy = {};\n}\nParser.prototype = parser;parser.Parser = Parser;\nreturn new Parser;\n})();\n\n\nif (typeof require !== 'undefined' && typeof exports !== 'undefined') {\nexports.parser = parser;\nexports.Parser = parser.Parser;\nexports.parse = function () { return parser.parse.apply(parser, arguments); };\n}\n","import ParsingError from './error/parsing_error';\nimport jsonlint from '@mapbox/jsonlint-lines-primitives';\n\nexport default function readStyle(style) {\n if (style instanceof String || typeof style === 'string' || style instanceof Buffer) {\n try {\n return jsonlint.parse(style.toString());\n } catch (e) {\n throw new ParsingError(e);\n }\n }\n\n return style;\n}\n","\nimport validateStyleMin from './validate_style.min';\nimport {v8} from './style-spec';\nimport readStyle from './read_style';\n\n/**\n * Validate a Mapbox GL style against the style specification.\n *\n * @private\n * @alias validate\n * @param {Object|String|Buffer} style The style to be validated. If a `String`\n * or `Buffer` is provided, the returned errors will contain line numbers.\n * @param {Object} [styleSpec] The style specification to validate against.\n * If omitted, the spec version is inferred from the stylesheet.\n * @returns {Array}\n * @example\n * var validate = require('mapbox-gl-style-spec').validate;\n * var style = fs.readFileSync('./style.json', 'utf8');\n * var errors = validate(style);\n */\n\nexport default function validateStyle(style, styleSpec = v8) {\n let s = style;\n\n try {\n s = readStyle(s);\n } catch (e) {\n return [e];\n }\n\n return validateStyleMin(s, styleSpec);\n}\n\nexport const source = validateStyleMin.source;\nexport const light = validateStyleMin.light;\nexport const layer = validateStyleMin.layer;\nexport const filter = validateStyleMin.filter;\nexport const paintProperty = validateStyleMin.paintProperty;\nexport const layoutProperty = validateStyleMin.layoutProperty;\n","// @flow\n\nimport validateStyle from './validate_style.min';\nimport {v8} from './style-spec';\nimport readStyle from './read_style';\nimport ValidationError from './error/validation_error';\nimport getType from './util/get_type';\n\nconst SUPPORTED_SPEC_VERSION = 8;\nconst MAX_SOURCES_IN_STYLE = 15;\n\nfunction isValid(value: ?string, regex: RegExp): boolean {\n if (!value || getType(value) !== 'string') return true;\n return !!value.match(regex);\n}\n\nfunction getSourceCount(source: Object): number {\n if (source.url) {\n return source.url.split(',').length;\n } else {\n return 0;\n }\n}\n\nfunction getAllowedKeyErrors(obj: Object, keys: Array<*>, path: ?string): Array {\n const allowed = new Set(keys);\n const errors = [];\n Object.keys(obj).forEach(k => {\n if (!allowed.has(k)) {\n const prop = path ? `${path}.${k}` : null;\n errors.push(new ValidationError(prop, obj[k], `Unsupported property \"${k}\"`));\n }\n });\n return errors;\n}\n\nfunction getSourceErrors(source: Object, i: number): Array {\n const errors = [];\n\n /*\n * Inlined sources are not supported by the Mapbox Styles API, so only\n * \"type\", \"url\", and \"tileSize\" properties are valid\n */\n const sourceKeys = ['type', 'url', 'tileSize'];\n errors.push(...getAllowedKeyErrors(source, sourceKeys, 'source'));\n\n /*\n * \"source\" is required. Valid examples:\n * mapbox://mapbox.abcd1234\n * mapbox://penny.abcd1234\n * mapbox://mapbox.abcd1234,penny.abcd1234\n */\n const sourceUrlPattern = /^mapbox:\\/\\/([^/]*)$/;\n if (!isValid(source.url, sourceUrlPattern)) {\n errors.push(new ValidationError(`sources[${i}]`, source.url, 'Source url must be a valid Mapbox tileset url'));\n }\n\n return errors;\n}\n\nfunction getSourcesErrors(sources: Object): Array {\n const errors = [];\n let count = 0;\n\n Object.keys(sources).forEach((s: string, i: number) => {\n const sourceErrors = getSourceErrors(sources[s], i);\n\n // If source has errors, skip counting\n if (!sourceErrors.length) {\n count = count + getSourceCount(sources[s]);\n }\n\n errors.push(...sourceErrors);\n });\n\n if (count > MAX_SOURCES_IN_STYLE) {\n errors.push(new ValidationError('sources', null, `Styles must contain ${MAX_SOURCES_IN_STYLE} or fewer sources`));\n }\n\n return errors;\n}\n\nfunction getRootErrors(style: Object, specKeys: Array): Array {\n const errors = [];\n\n /*\n * The following keys are optional but fully managed by the Mapbox Styles\n * API. Values on stylesheet on POST or PATCH will be ignored: \"owner\",\n * \"id\", \"cacheControl\", \"draft\", \"created\", \"modified\"\n *\n * The following keys are optional. The Mapbox Styles API respects value on\n * stylesheet on PATCH, but ignores the value on POST: \"visibility\"\n */\n const optionalRootProperties = [\n 'owner',\n 'id',\n 'cacheControl',\n 'draft',\n 'created',\n 'modified',\n 'visibility'\n ];\n\n const allowedKeyErrors = getAllowedKeyErrors(style, [...specKeys, ...optionalRootProperties]);\n errors.push(...allowedKeyErrors);\n\n if (style.version > SUPPORTED_SPEC_VERSION || style.version < SUPPORTED_SPEC_VERSION) {\n errors.push(new ValidationError('version', style.version, `Style version must be ${SUPPORTED_SPEC_VERSION}`));\n }\n\n /*\n * \"glyphs\" is optional. If present, valid examples:\n * mapbox://fonts/penny/{fontstack}/{range}.pbf\n * mapbox://fonts/mapbox/{fontstack}/{range}.pbf\n */\n const glyphUrlPattern = /^mapbox:\\/\\/fonts\\/([^/]*)\\/{fontstack}\\/{range}.pbf$/;\n if (!isValid(style.glyphs, glyphUrlPattern)) {\n errors.push(new ValidationError('glyphs', style.glyphs, 'Styles must reference glyphs hosted by Mapbox'));\n }\n\n /*\n * \"sprite\" is optional. If present, valid examples:\n * mapbox://sprites/penny/abcd1234\n * mapbox://sprites/mapbox/abcd1234/draft\n * mapbox://sprites/cyrus/abcd1234/abcd1234\n */\n const spriteUrlPattern = /^mapbox:\\/\\/sprites\\/([^/]*)\\/([^/]*)\\/?([^/]*)?$/;\n if (!isValid(style.sprite, spriteUrlPattern)) {\n errors.push(new ValidationError('sprite', style.sprite, 'Styles must reference sprites hosted by Mapbox'));\n }\n\n /*\n * \"visibility\" is optional. If present, valid examples:\n * \"private\"\n * \"public\"\n */\n const visibilityPattern = /^(public|private)$/;\n if (!isValid(style.visibility, visibilityPattern)) {\n errors.push(new ValidationError('visibility', style.visibility, 'Style visibility must be public or private'));\n }\n\n return errors;\n}\n\n/**\n * Validate a Mapbox GL style against the style specification and check for\n * compatibility with the Mapbox Styles API.\n *\n * @param {Object} style The style to be validated.\n * @returns {Array}\n * @example\n * var validateMapboxApiSupported = require('mapbox-gl-style-spec/lib/validate_style_mapbox_api_supported.js');\n * var errors = validateMapboxApiSupported(style);\n */\nexport default function validateMapboxApiSupported(style: Object): Array {\n let s = style;\n try {\n s = readStyle(s);\n } catch (e) {\n return [e];\n }\n\n let errors = validateStyle(s, v8)\n .concat(getRootErrors(s, Object.keys(v8.$root)));\n\n if (s.sources) {\n errors = errors.concat(getSourcesErrors(s.sources));\n }\n\n return errors;\n}\n","// @flow\n\ntype ExpressionType = 'data-driven' | 'cross-faded' | 'cross-faded-data-driven' | 'color-ramp' | 'data-constant' | 'constant';\ntype ExpressionParameters = Array<'zoom' | 'feature' | 'feature-state' | 'heatmap-density' | 'line-progress'>;\n\ntype ExpressionSpecification = {\n interpolated: boolean,\n parameters: ExpressionParameters\n}\n\nexport type StylePropertySpecification = {\n type: 'number',\n 'property-type': ExpressionType,\n expression?: ExpressionSpecification,\n transition: boolean,\n default?: number\n} | {\n type: 'string',\n 'property-type': ExpressionType,\n expression?: ExpressionSpecification,\n transition: boolean,\n default?: string,\n tokens?: boolean\n} | {\n type: 'boolean',\n 'property-type': ExpressionType,\n expression?: ExpressionSpecification,\n transition: boolean,\n default?: boolean\n} | {\n type: 'enum',\n 'property-type': ExpressionType,\n expression?: ExpressionSpecification,\n values: {[_: string]: {}},\n transition: boolean,\n default?: string\n} | {\n type: 'color',\n 'property-type': ExpressionType,\n expression?: ExpressionSpecification,\n transition: boolean,\n default?: string,\n overridable: boolean\n} | {\n type: 'array',\n value: 'number',\n 'property-type': ExpressionType,\n expression?: ExpressionSpecification,\n length?: number,\n transition: boolean,\n default?: Array\n} | {\n type: 'array',\n value: 'string',\n 'property-type': ExpressionType,\n expression?: ExpressionSpecification,\n length?: number,\n transition: boolean,\n default?: Array\n};\n\nimport v8 from './reference/v8.json';\nimport latest from './reference/latest';\nimport format from './format';\nimport migrate from './migrate';\nimport composite from './composite';\nimport derefLayers from './deref';\nimport diff from './diff';\nimport ValidationError from './error/validation_error';\nimport ParsingError from './error/parsing_error';\nimport {StyleExpression, isExpression, createExpression, createPropertyExpression, normalizePropertyExpression, ZoomConstantExpression, ZoomDependentExpression, StylePropertyFunction} from './expression';\nimport featureFilter, {isExpressionFilter} from './feature_filter';\n\nimport convertFilter from './feature_filter/convert';\nimport Color from './util/color';\nimport {createFunction, isFunction} from './function';\nimport convertFunction from './function/convert';\nimport {eachSource, eachLayer, eachProperty} from './visit';\n\nimport validate from './validate_style';\nimport validateMapboxApiSupported from './validate_mapbox_api_supported';\n\nconst expression = {\n StyleExpression,\n isExpression,\n isExpressionFilter,\n createExpression,\n createPropertyExpression,\n normalizePropertyExpression,\n ZoomConstantExpression,\n ZoomDependentExpression,\n StylePropertyFunction\n};\n\nconst styleFunction = {\n convertFunction,\n createFunction,\n isFunction\n};\n\nconst visit = {eachSource, eachLayer, eachProperty};\n\nexport {\n v8,\n latest,\n format,\n migrate,\n composite,\n derefLayers,\n diff,\n ValidationError,\n ParsingError,\n expression,\n featureFilter,\n convertFilter,\n Color,\n styleFunction as function,\n validate,\n validateMapboxApiSupported,\n visit\n};\n\nvalidate.parsed = validate;\nvalidate.latest = validate;\n"],"names":["sortKeysBy","obj","reference","const","result","key","undefined","format","style","space","$root","layers","map","layer","stringifyPretty","indent","global","this","require$$0","require$$1","getPropertyReference","propertyName","let","i","Reference","layout","length","paint","eachSource","callback","k","sources","eachLayer","eachProperty","options","inner","propertyType","properties","Object","keys","forEach","path","id","value","set","x","eachLayout","indexOf","eachPaint","resolveConstant","constants","isFunction","Array","isArray","stops","renameProperty","from","to","version","source","type","url","coordinates","coord","reverse","property","stop","migrateFontstackURL","input","inputParsed","URL","parse","inputPathnameParts","pathname","split","protocol","hostname","glyphs","migrateFontStack","font","splitAndTrim","string","s","trim","Error","firstSymbolLayer","symbolLayers","splice","concat","output","inputs","ParsingError","message","super","Scope","parent","bindings","name","expression","get","has","NullType","kind","NumberType","StringType","BooleanType","ColorType","ObjectType","ValueType","ErrorType","CollatorType","FormattedType","ResolvedImageType","array","itemType","N","toString","valueMemberTypes","checkSubtype","expected","t","memberType","isValidType","provided","allowedTypes","some","isValidNativeType","Color","r","g","b","a","rgba","parseCSSColor","toArray","Math","round","black","white","transparent","red","Collator","caseSensitive","diacriticSensitive","locale","sensitivity","collator","Intl","usage","compare","lhs","rhs","resolvedLocale","resolvedOptions","FormattedSection","text","image","scale","fontStack","textColor","Formatted","sections","fromString","unformatted","isEmpty","section","factory","join","serialize","serialized","push","ResolvedImage","available","validateRGBA","isValue","mixed","item","typeOf","String","JSON","stringify","Literal","args","context","error","expectedType","evaluate","eachChild","outputDefined","RuntimeError","toJSON","types","number","boolean","object","Assertion","floor","parsed","ctx","fn","every","arg","FormatExpression","firstArg","nextTokenMayBeObject","lastExpression","content","evaluateSection","evaluatedContent","ImageExpression","evaluatedImageName","availableImages","Coercion","Boolean","c","parseColor","num","Number","isNaN","valueToString","child","geometryTypes","EvaluationContext","globals","feature","featureState","formattedSection","_parseColorCache","canonical","geometryType","geometry","canonicalID","cached","CompoundExpression","_evaluate","op","definition","definitions","availableOverloads","overloads","filter","signature","signatureContext","ParsingContext","registry","scope","parsedArgs","argParseFailed","params","errors","signatures","stringifySignature","actualTypes","register","CollatorExpression","EXTENT","updateBBox","bbox","min","max","mercatorXfromLng","lng","mercatorYfromLat","lat","PI","log","tan","boxWithinBox","bbox1","bbox2","getTileCoordinates","p","y","tilesAtZoom","pow","z","onBoundary","p1","p2","x1","y1","x2","y2","rayIntersect","pointWithinPolygon","point","rings","inside","len","ring","j","len2","pointWithinPolygons","polygons","perp","v1","v2","twoSided","q1","q2","x3","y3","det1","det2","lineIntersectLine","d","vectorP","vectorQ","lineIntersectPolygon","polygon","lineStringWithinPolygon","line","lineStringWithinPolygons","getTilePolygon","getTilePolygons","updatePoint","polyBBox","worldSize","halfWorldSize","shift","resetBBox","Infinity","getTilePoints","pointBBox","shifts","tilePoints","points","getTileLines","lineBBox","tileLines","tileLine","pointsWithinPolygons","polygonGeometry","tilePolygon","tilePolygons","linesWithinPolygons","Within","geojson","geometries","features","isFeatureConstant","e","test","isStateConstant","isGlobalPropertyConstant","Var","boundExpression","part","expr","index","_parse","annotate","typeAnnotation","Expr","actual","isConstant","ec","isTypeAnnotation","childrenConstant","findStopLessThanOrEqualTo","lastIndex","lowerIndex","upperIndex","currentIndex","currentValue","nextValue","Step","labels","outputs","label","outputType","labelKey","valueKey","stopCount","out","color","Xn","Yn","Zn","t0","t1","t2","t3","deg2rad","rad2deg","xyz2lab","lab2xyz","xyz2rgb","rgb2xyz","rgbToLab","rgbColor","l","alpha","labToRgb","labColor","interpolateLab","interpolateNumber","rgbToHcl","h","atan2","sqrt","hclToRgb","hclColor","cos","sin","interpolateHue","interpolateHcl","lab","forward","interpolate","hcl","Interpolate","operator","interpolation","interpolationFactor","lower","upper","exponentialInterpolation","base","controlPoints","ub","UnitBezier","solve","slice","rest","outputLower","outputUpper","toLowerCase","lowerValue","upperValue","difference","progress","Coalesce","needsAnnotation","argCount","requestedImageName","Let","binding","At","In","needle","haystack","IndexOf","fromIndex","Match","inputType","cases","otherwise","labelContext","abs","MAX_SAFE_INTEGER","sortedLabels","sort","groupedByOutput","outputLookup","outputIndex","coerceLabel","Case","branches","Slice","beginIndex","endIndex","isComparableType","eq","neq","lt","gt","lteq","gteq","eqCollate","neqCollate","ltCollate","gtCollate","lteqCollate","gteqCollate","makeComparison","compareBasic","compareWithCollator","isOrderComparison","hasUntypedArgument","Comparison","rt","Equals","NotEquals","LessThan","GreaterThan","LessThanOrEqual","GreaterThanOrEqual","NumberFormat","currency","minFractionDigits","maxFractionDigits","minimumFractionDigits","maximumFractionDigits","Length","expressions","v","binarySearch","m","varargs","typeToString","zoom","heatmapDensity","lineProgress","accumulated","LN2","E","n","LN10","asin","acos","atan","ceil","isSupportedScript","toUpperCase","success","supportsPropertyExpression","spec","supportsZoomExpression","parameters","supportsInterpolation","interpolated","getType","val","identityFunction","createFunction","propertySpec","isColor","zoomAndFeatureDependent","featureDependent","zoomDependent","extend","default","colorSpace","colorSpaces","innerFun","hashedStops","categoricalKeyType","evaluateExponentialFunction","evaluateIntervalFunction","evaluateCategoricalFunction","create","evaluateIdentityFunction","featureFunctions","zoomStops","featureFunctionStops","interpolationType","bind","_","coalesce","keyType","evaluated","interp","colorspace","evaluatedLower","apply","evaluatedUpper","values","StyleExpression","_warningHistory","_evaluator","_defaultValue","getDefaultValue","_enumValues","evaluateWithoutErrorHandling","console","warn","isExpression","createExpression","parser","getExpectedType","ZoomConstantExpression","_styleExpression","isStateDependent","ZoomDependentExpression","createPropertyExpression","isZoomConstant","zoomCurve","findZoomCurve","StylePropertyFunction","specification","_parameters","_specification","deserialize","normalizePropertyExpression","err","constant","childResult","enum","formatted","resolvedImage","convertLiteral","convertFunction","convertIdentityFunction","tokens","convertTokenString","convertZoomAndPropertyFunction","convertZoomFunction","convertPropertyFunction","getInterpolateOperator","featureFunctionParameters","functionType","getFunctionType","appendStopPair","fixupDegenerateStepCurve","getFallback","defaultValue","isStep","curve","re","pos","match","exec","literal","isExpressionFilter","f","filterSpec","createFilter","needGeometry","convertFilter","compiled","geometryNeeded","globalProperties","converted","convertComparisonOp","convertNegation","convertDisjunctionOp","convertInOp","convertHasOp","filters","_convertFilter","expectedTypes","children","typechecks","runtimeTypeChecks","conditions","negate","uniformTypes","uniqueValues","migrated","migrateToV8","migrateToExpressions","styleIDs","sourceIDs","compositedSourceLayers","compositeID","deref","refProperties","derefLayers","ref","deepEqual","operations","setStyle","addLayer","removeLayer","setPaintProperty","setLayoutProperty","setFilter","addSource","removeSource","setGeoJSONSourceData","setLayerZoomRange","setLayerProperty","setCenter","setZoom","setBearing","setPitch","setSprite","setGlyphs","setTransition","setLight","sourceId","after","commands","command","sourcesRemoved","updateSource","canUpdateGeoJSON","before","prop","hasOwnProperty","isEqual","diffSources","data","diffLayerPropertyChanges","layerId","klass","pluckId","indexById","group","diffLayers","beforeOrder","afterOrder","beforeIndex","reduce","afterIndex","tracker","clean","beforeLayer","afterLayer","insertBeforeLayerId","lastIndexOf","minzoom","maxzoom","diffStyles","center","bearing","pitch","sprite","transition","light","removeOrAddSourceCommands","beforeLayers","ValidationError","identifier","__line__","parseInt","validateConstants","unbundle","valueOf","deepUnbundle","unbundledValue","validateObject","elementSpecs","valueSpec","elementValidators","objectElementValidators","styleSpec","objectKey","elementSpecKey","elementSpec","validateElement","validateSpec","required","validateArray","arraySpec","validateArrayElement","arrayElementValidator","validate","arrayElementSpec","$version","function","arrayIndex","validateNumber","minimum","maximum","validateFunction","functionValueSpec","stopKeyType","stopDomainValues","previousStopDomainValue","previousStopDomainZoom","isZoomFunction","isPropertyFunction","isZoomAndPropertyFunction","validateFunctionStops","validateFunctionDefault","validateFunctionStop","validateStopDomainValue","reportValue","isFinite","validateExpression","expressionContext","expressionObj","propertyKey","validateBoolean","validateColor","validateEnum","validateFilter","validateNonExpressionFilter","filter_operator","geometry_type","validateProperty","layerSpec","layerType","transitionMatch","tokenMatch","validatePaintProperty","validateLayoutProperty","validateLayer","otherLayer","sourceType","lineMetrics","validateString","promoteId","validatePromoteId","validateSource","replace","source_geojson","cluster","clusterProperties","reduceExpr","mapExpr","source_video","source_image","validateLight","lightSpec","rootType","validateFormatted","validateImage","VALIDATORS","valid","validateStyleMin","latestStyleSpec","validateGlyphsURL","sortErrors","wrapCleanErrors","paintProperty","layoutProperty","require","readStyle","Buffer","jsonlint","validateStyle","v8","SUPPORTED_SPEC_VERSION","MAX_SOURCES_IN_STYLE","isValid","regex","getSourceCount","getAllowedKeyErrors","allowed","Set","getSourceErrors","sourceKeys","sourceUrlPattern","getSourcesErrors","count","sourceErrors","getRootErrors","specKeys","optionalRootProperties","allowedKeyErrors","glyphUrlPattern","spriteUrlPattern","visibilityPattern","visibility","validateMapboxApiSupported","styleFunction","visit","latest"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAA,gBAGlB1d,YAHkB;AAAA,CAAtBhD,CA9FA;AAoGAA,IAAMo0B,KAAA,GAAQ;AAAA,gBAAC3yB,UAAD;AAAA,eAAaI,SAAb;AAAA,kBAAwBC,YAAxB;AAAA,CAAd9B,CApGA;AAsGA,AAoBA+tB,aAAA,CAAS7hB,MAAT,GAAkB6hB,aAAlB,CA1HA;AA2HAA,aAAA,CAASsG,MAAT,GAAkBtG,aAAlB;;;;"} \ No newline at end of file diff --git a/node_modules/mapbox-gl/src/style-spec/dist/index.js b/node_modules/mapbox-gl/src/style-spec/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a41f39c9abab728f6f4537432b253293701cffb1 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/dist/index.js @@ -0,0 +1,15058 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = global || self, factory(global.mapboxGlStyleSpecification = {})); +}(this, (function (exports) { 'use strict'; + + var $version = 8; + var $root = { + version: { + required: true, + type: "enum", + values: [ + 8 + ], + doc: "Style specification version number. Must be 8.", + example: 8 + }, + name: { + type: "string", + doc: "A human-readable name for the style.", + example: "Bright" + }, + metadata: { + type: "*", + doc: "Arbitrary properties useful to track with the stylesheet, but do not influence rendering. Properties should be prefixed to avoid collisions, like 'mapbox:'." + }, + center: { + type: "array", + value: "number", + doc: "Default map center in longitude and latitude. The style center will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + example: [ + -73.9749, + 40.7736 + ] + }, + zoom: { + type: "number", + doc: "Default zoom level. The style zoom will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + example: 12.5 + }, + bearing: { + type: "number", + "default": 0, + period: 360, + units: "degrees", + doc: "Default bearing, in degrees. The bearing is the compass direction that is \"up\"; for example, a bearing of 90° orients the map so that east is up. This value will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + example: 29 + }, + pitch: { + type: "number", + "default": 0, + units: "degrees", + doc: "Default pitch, in degrees. Zero is perpendicular to the surface, for a look straight down at the map, while a greater value like 60 looks ahead towards the horizon. The style pitch will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + example: 50 + }, + light: { + type: "light", + doc: "The global light source.", + example: { + anchor: "viewport", + color: "white", + intensity: 0.4 + } + }, + sources: { + required: true, + type: "sources", + doc: "Data source specifications.", + example: { + "mapbox-streets": { + type: "vector", + url: "mapbox://mapbox.mapbox-streets-v6" + } + } + }, + sprite: { + type: "string", + doc: "A base URL for retrieving the sprite image and metadata. The extensions `.png`, `.json` and scale factor `@2x.png` will be automatically appended. This property is required if any layer uses the `background-pattern`, `fill-pattern`, `line-pattern`, `fill-extrusion-pattern`, or `icon-image` properties. The URL must be absolute, containing the [scheme, authority and path components](https://en.wikipedia.org/wiki/URL#Syntax).", + example: "mapbox://sprites/mapbox/bright-v8" + }, + glyphs: { + type: "string", + doc: "A URL template for loading signed-distance-field glyph sets in PBF format. The URL must include `{fontstack}` and `{range}` tokens. This property is required if any layer uses the `text-field` layout property. The URL must be absolute, containing the [scheme, authority and path components](https://en.wikipedia.org/wiki/URL#Syntax).", + example: "mapbox://fonts/mapbox/{fontstack}/{range}.pbf" + }, + transition: { + type: "transition", + doc: "A global transition definition to use as a default across properties, to be used for timing transitions between one value and the next when no property-specific transition is set. Collision-based symbol fading is controlled independently of the style's `transition` property.", + example: { + duration: 300, + delay: 0 + } + }, + layers: { + required: true, + type: "array", + value: "layer", + doc: "Layers will be drawn in the order of this array.", + example: [ + { + id: "water", + source: "mapbox-streets", + "source-layer": "water", + type: "fill", + paint: { + "fill-color": "#00ffff" + } + } + ] + } + }; + var sources = { + "*": { + type: "source", + doc: "Specification of a data source. For vector and raster sources, either TileJSON or a URL to a TileJSON must be provided. For image and video sources, a URL must be provided. For GeoJSON sources, a URL or inline GeoJSON must be provided." + } + }; + var source = [ + "source_vector", + "source_raster", + "source_raster_dem", + "source_geojson", + "source_video", + "source_image" + ]; + var source_vector = { + type: { + required: true, + type: "enum", + values: { + vector: { + doc: "A vector tile source." + } + }, + doc: "The type of the source." + }, + url: { + type: "string", + doc: "A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://`." + }, + tiles: { + type: "array", + value: "string", + doc: "An array of one or more tile source URLs, as in the TileJSON spec." + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ], + doc: "An array containing the longitude and latitude of the southwest and northeast corners of the source's bounding box in the following order: `[sw.lng, sw.lat, ne.lng, ne.lat]`. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL." + }, + scheme: { + type: "enum", + values: { + xyz: { + doc: "Slippy map tilenames scheme." + }, + tms: { + doc: "OSGeo spec scheme." + } + }, + "default": "xyz", + doc: "Influences the y direction of the tile coordinates. The global-mercator (aka Spherical Mercator) profile is assumed." + }, + minzoom: { + type: "number", + "default": 0, + doc: "Minimum zoom level for which tiles are available, as in the TileJSON spec." + }, + maxzoom: { + type: "number", + "default": 22, + doc: "Maximum zoom level for which tiles are available, as in the TileJSON spec. Data from tiles at the maxzoom are used when displaying the map at higher zoom levels." + }, + attribution: { + type: "string", + doc: "Contains an attribution to be displayed when the map is shown to a user." + }, + promoteId: { + type: "promoteId", + doc: "A property to use as a feature id (for feature state). Either a property name, or an object of the form `{: }`. If specified as a string for a vector tile source, the same property is used across all its source layers." + }, + volatile: { + type: "boolean", + "default": false, + doc: "A setting to determine whether a source's tiles are cached locally.", + "sdk-support": { + "basic functionality": { + android: "9.3.0", + ios: "5.10.0" + } + } + }, + "*": { + type: "*", + doc: "Other keys to configure the data source." + } + }; + var source_raster = { + type: { + required: true, + type: "enum", + values: { + raster: { + doc: "A raster tile source." + } + }, + doc: "The type of the source." + }, + url: { + type: "string", + doc: "A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://`." + }, + tiles: { + type: "array", + value: "string", + doc: "An array of one or more tile source URLs, as in the TileJSON spec." + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ], + doc: "An array containing the longitude and latitude of the southwest and northeast corners of the source's bounding box in the following order: `[sw.lng, sw.lat, ne.lng, ne.lat]`. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL." + }, + minzoom: { + type: "number", + "default": 0, + doc: "Minimum zoom level for which tiles are available, as in the TileJSON spec." + }, + maxzoom: { + type: "number", + "default": 22, + doc: "Maximum zoom level for which tiles are available, as in the TileJSON spec. Data from tiles at the maxzoom are used when displaying the map at higher zoom levels." + }, + tileSize: { + type: "number", + "default": 512, + units: "pixels", + doc: "The minimum visual size to display tiles for this layer. Only configurable for raster layers." + }, + scheme: { + type: "enum", + values: { + xyz: { + doc: "Slippy map tilenames scheme." + }, + tms: { + doc: "OSGeo spec scheme." + } + }, + "default": "xyz", + doc: "Influences the y direction of the tile coordinates. The global-mercator (aka Spherical Mercator) profile is assumed." + }, + attribution: { + type: "string", + doc: "Contains an attribution to be displayed when the map is shown to a user." + }, + volatile: { + type: "boolean", + "default": false, + doc: "A setting to determine whether a source's tiles are cached locally.", + "sdk-support": { + "basic functionality": { + android: "9.3.0", + ios: "5.10.0" + } + } + }, + "*": { + type: "*", + doc: "Other keys to configure the data source." + } + }; + var source_raster_dem = { + type: { + required: true, + type: "enum", + values: { + "raster-dem": { + doc: "A RGB-encoded raster DEM source" + } + }, + doc: "The type of the source." + }, + url: { + type: "string", + doc: "A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://`." + }, + tiles: { + type: "array", + value: "string", + doc: "An array of one or more tile source URLs, as in the TileJSON spec." + }, + bounds: { + type: "array", + value: "number", + length: 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ], + doc: "An array containing the longitude and latitude of the southwest and northeast corners of the source's bounding box in the following order: `[sw.lng, sw.lat, ne.lng, ne.lat]`. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL." + }, + minzoom: { + type: "number", + "default": 0, + doc: "Minimum zoom level for which tiles are available, as in the TileJSON spec." + }, + maxzoom: { + type: "number", + "default": 22, + doc: "Maximum zoom level for which tiles are available, as in the TileJSON spec. Data from tiles at the maxzoom are used when displaying the map at higher zoom levels." + }, + tileSize: { + type: "number", + "default": 512, + units: "pixels", + doc: "The minimum visual size to display tiles for this layer. Only configurable for raster layers." + }, + attribution: { + type: "string", + doc: "Contains an attribution to be displayed when the map is shown to a user." + }, + encoding: { + type: "enum", + values: { + terrarium: { + doc: "Terrarium format PNG tiles. See https://aws.amazon.com/es/public-datasets/terrain/ for more info." + }, + mapbox: { + doc: "Mapbox Terrain RGB tiles. See https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb for more info." + } + }, + "default": "mapbox", + doc: "The encoding used by this source. Mapbox Terrain RGB is used by default" + }, + volatile: { + type: "boolean", + "default": false, + doc: "A setting to determine whether a source's tiles are cached locally.", + "sdk-support": { + "basic functionality": { + android: "9.3.0", + ios: "5.10.0" + } + } + }, + "*": { + type: "*", + doc: "Other keys to configure the data source." + } + }; + var source_geojson = { + type: { + required: true, + type: "enum", + values: { + geojson: { + doc: "A GeoJSON data source." + } + }, + doc: "The data type of the GeoJSON source." + }, + data: { + type: "*", + doc: "A URL to a GeoJSON file, or inline GeoJSON." + }, + maxzoom: { + type: "number", + "default": 18, + doc: "Maximum zoom level at which to create vector tiles (higher means greater detail at high zoom levels)." + }, + attribution: { + type: "string", + doc: "Contains an attribution to be displayed when the map is shown to a user." + }, + buffer: { + type: "number", + "default": 128, + maximum: 512, + minimum: 0, + doc: "Size of the tile buffer on each side. A value of 0 produces no buffer. A value of 512 produces a buffer as wide as the tile itself. Larger values produce fewer rendering artifacts near tile edges and slower performance." + }, + filter: { + type: "*", + doc: "An expression for filtering features prior to processing them for rendering." + }, + tolerance: { + type: "number", + "default": 0.375, + doc: "Douglas-Peucker simplification tolerance (higher means simpler geometries and faster performance)." + }, + cluster: { + type: "boolean", + "default": false, + doc: "If the data is a collection of point features, setting this to true clusters the points by radius into groups. Cluster groups become new `Point` features in the source with additional properties:\n * `cluster` Is `true` if the point is a cluster \n * `cluster_id` A unqiue id for the cluster to be used in conjunction with the [cluster inspection methods](https://www.mapbox.com/mapbox-gl-js/api/#geojsonsource#getclusterexpansionzoom)\n * `point_count` Number of original points grouped into this cluster\n * `point_count_abbreviated` An abbreviated point count" + }, + clusterRadius: { + type: "number", + "default": 50, + minimum: 0, + doc: "Radius of each cluster if clustering is enabled. A value of 512 indicates a radius equal to the width of a tile." + }, + clusterMaxZoom: { + type: "number", + doc: "Max zoom on which to cluster points if clustering is enabled. Defaults to one zoom less than maxzoom (so that last zoom features are not clustered). Clusters are re-evaluated at integer zoom levels so setting clusterMaxZoom to 14 means the clusters will be displayed until z15." + }, + clusterMinPoints: { + type: "number", + doc: "Minimum number of points necessary to form a cluster if clustering is enabled. Defaults to `2`." + }, + clusterProperties: { + type: "*", + doc: "An object defining custom properties on the generated clusters if clustering is enabled, aggregating values from clustered points. Has the form `{\"property_name\": [operator, map_expression]}`. `operator` is any expression function that accepts at least 2 operands (e.g. `\"+\"` or `\"max\"`) — it accumulates the property value from clusters/points the cluster contains; `map_expression` produces the value of a single point.\n\nExample: `{\"sum\": [\"+\", [\"get\", \"scalerank\"]]}`.\n\nFor more advanced use cases, in place of `operator`, you can use a custom reduce expression that references a special `[\"accumulated\"]` value, e.g.:\n`{\"sum\": [[\"+\", [\"accumulated\"], [\"get\", \"sum\"]], [\"get\", \"scalerank\"]]}`" + }, + lineMetrics: { + type: "boolean", + "default": false, + doc: "Whether to calculate line distance metrics. This is required for line layers that specify `line-gradient` values." + }, + generateId: { + type: "boolean", + "default": false, + doc: "Whether to generate ids for the geojson features. When enabled, the `feature.id` property will be auto assigned based on its index in the `features` array, over-writing any previous values." + }, + promoteId: { + type: "promoteId", + doc: "A property to use as a feature id (for feature state). Either a property name, or an object of the form `{: }`." + } + }; + var source_video = { + type: { + required: true, + type: "enum", + values: { + video: { + doc: "A video data source." + } + }, + doc: "The data type of the video source." + }, + urls: { + required: true, + type: "array", + value: "string", + doc: "URLs to video content in order of preferred format." + }, + coordinates: { + required: true, + doc: "Corners of video specified in longitude, latitude pairs.", + type: "array", + length: 4, + value: { + type: "array", + length: 2, + value: "number", + doc: "A single longitude, latitude pair." + } + } + }; + var source_image = { + type: { + required: true, + type: "enum", + values: { + image: { + doc: "An image data source." + } + }, + doc: "The data type of the image source." + }, + url: { + required: true, + type: "string", + doc: "URL that points to an image." + }, + coordinates: { + required: true, + doc: "Corners of image specified in longitude, latitude pairs.", + type: "array", + length: 4, + value: { + type: "array", + length: 2, + value: "number", + doc: "A single longitude, latitude pair." + } + } + }; + var layer = { + id: { + type: "string", + doc: "Unique layer name.", + required: true + }, + type: { + type: "enum", + values: { + fill: { + doc: "A filled polygon with an optional stroked border.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + } + }, + line: { + doc: "A stroked line.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + } + }, + symbol: { + doc: "An icon or a text label.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + } + }, + circle: { + doc: "A filled circle.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + } + }, + heatmap: { + doc: "A heatmap.", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "fill-extrusion": { + doc: "An extruded (3D) polygon.", + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + } + }, + raster: { + doc: "Raster map textures such as satellite imagery.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + } + }, + hillshade: { + doc: "Client-side hillshading visualization based on DEM data. Currently, the implementation only supports Mapbox Terrain RGB and Mapzen Terrarium tiles.", + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + background: { + doc: "The background color or pattern of the map.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + } + } + }, + doc: "Rendering type of this layer.", + required: true + }, + metadata: { + type: "*", + doc: "Arbitrary properties useful to track with the layer, but do not influence rendering. Properties should be prefixed to avoid collisions, like 'mapbox:'." + }, + source: { + type: "string", + doc: "Name of a source description to be used for this layer. Required for all layer types except `background`." + }, + "source-layer": { + type: "string", + doc: "Layer to use from a vector tile source. Required for vector tile sources; prohibited for all other source types, including GeoJSON sources." + }, + minzoom: { + type: "number", + minimum: 0, + maximum: 24, + doc: "The minimum zoom level for the layer. At zoom levels less than the minzoom, the layer will be hidden." + }, + maxzoom: { + type: "number", + minimum: 0, + maximum: 24, + doc: "The maximum zoom level for the layer. At zoom levels equal to or greater than the maxzoom, the layer will be hidden." + }, + filter: { + type: "filter", + doc: "A expression specifying conditions on source features. Only features that match the filter are displayed. Zoom expressions in filters are only evaluated at integer zoom levels. The `feature-state` expression is not supported in filter expressions." + }, + layout: { + type: "layout", + doc: "Layout properties for the layer." + }, + paint: { + type: "paint", + doc: "Default paint properties for this layer." + } + }; + var layout = [ + "layout_fill", + "layout_line", + "layout_circle", + "layout_heatmap", + "layout_fill-extrusion", + "layout_symbol", + "layout_raster", + "layout_hillshade", + "layout_background" + ]; + var layout_background = { + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + "property-type": "constant" + } + }; + var layout_fill = { + "fill-sort-key": { + type: "number", + doc: "Sorts features in ascending order based on this value. Features with a higher sort key will appear above features with a lower sort key.", + "sdk-support": { + "basic functionality": { + js: "1.2.0", + android: "9.1.0", + ios: "5.8.0", + macos: "0.15.0" + }, + "data-driven styling": { + js: "1.2.0", + android: "9.1.0", + ios: "5.8.0", + macos: "0.15.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + "property-type": "constant" + } + }; + var layout_circle = { + "circle-sort-key": { + type: "number", + doc: "Sorts features in ascending order based on this value. Features with a higher sort key will appear above features with a lower sort key.", + "sdk-support": { + "basic functionality": { + js: "1.2.0", + android: "9.2.0", + ios: "5.9.0", + macos: "0.16.0" + }, + "data-driven styling": { + js: "1.2.0", + android: "9.2.0", + ios: "5.9.0", + macos: "0.16.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + "property-type": "constant" + } + }; + var layout_heatmap = { + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + "property-type": "constant" + } + }; + var layout_line = { + "line-cap": { + type: "enum", + values: { + butt: { + doc: "A cap with a squared-off end which is drawn to the exact endpoint of the line." + }, + round: { + doc: "A cap with a rounded end which is drawn beyond the endpoint of the line at a radius of one-half of the line's width and centered on the endpoint of the line." + }, + square: { + doc: "A cap with a squared-off end which is drawn beyond the endpoint of the line at a distance of one-half of the line's width." + } + }, + "default": "butt", + doc: "The display of line endings.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-join": { + type: "enum", + values: { + bevel: { + doc: "A join with a squared-off end which is drawn beyond the endpoint of the line at a distance of one-half of the line's width." + }, + round: { + doc: "A join with a rounded end which is drawn beyond the endpoint of the line at a radius of one-half of the line's width and centered on the endpoint of the line." + }, + miter: { + doc: "A join with a sharp, angled corner which is drawn with the outer sides beyond the endpoint of the path until they meet." + } + }, + "default": "miter", + doc: "The display of lines when joining.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.40.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "line-miter-limit": { + type: "number", + "default": 2, + doc: "Used to automatically convert miter joins to bevel joins for sharp angles.", + requires: [ + { + "line-join": "miter" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-round-limit": { + type: "number", + "default": 1.05, + doc: "Used to automatically convert round joins to miter joins for shallow angles.", + requires: [ + { + "line-join": "round" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-sort-key": { + type: "number", + doc: "Sorts features in ascending order based on this value. Features with a higher sort key will appear above features with a lower sort key.", + "sdk-support": { + "basic functionality": { + js: "1.2.0", + android: "9.1.0", + ios: "5.8.0", + macos: "0.15.0" + }, + "data-driven styling": { + js: "1.2.0", + android: "9.1.0", + ios: "5.8.0", + macos: "0.15.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + "property-type": "constant" + } + }; + var layout_symbol = { + "symbol-placement": { + type: "enum", + values: { + point: { + doc: "The label is placed at the point where the geometry is located." + }, + line: { + doc: "The label is placed along the line of the geometry. Can only be used on `LineString` and `Polygon` geometries." + }, + "line-center": { + doc: "The label is placed at the center of the line of the geometry. Can only be used on `LineString` and `Polygon` geometries. Note that a single feature in a vector tile may contain multiple line geometries." + } + }, + "default": "point", + doc: "Label placement relative to its geometry.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "`line-center` value": { + js: "0.47.0", + android: "6.4.0", + ios: "4.3.0", + macos: "0.10.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-spacing": { + type: "number", + "default": 250, + minimum: 1, + units: "pixels", + doc: "Distance between two symbol anchors.", + requires: [ + { + "symbol-placement": "line" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-avoid-edges": { + type: "boolean", + "default": false, + doc: "If true, the symbols will not cross tile edges to avoid mutual collisions. Recommended in layers that don't have enough padding in the vector tile to prevent collisions, or if it is a point symbol layer placed after a line symbol layer. When using a client that supports global collision detection, like Mapbox GL JS version 0.42.0 or greater, enabling this property is not needed to prevent clipped labels at tile boundaries.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-sort-key": { + type: "number", + doc: "Sorts features in ascending order based on this value. Features with lower sort keys are drawn and placed first. When `icon-allow-overlap` or `text-allow-overlap` is `false`, features with a lower sort key will have priority during placement. When `icon-allow-overlap` or `text-allow-overlap` is set to `true`, features with a higher sort key will overlap over features with a lower sort key.", + "sdk-support": { + "basic functionality": { + js: "0.53.0", + android: "7.4.0", + ios: "4.11.0", + macos: "0.14.0" + }, + "data-driven styling": { + js: "0.53.0", + android: "7.4.0", + ios: "4.11.0", + macos: "0.14.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "symbol-z-order": { + type: "enum", + values: { + auto: { + doc: "Sorts symbols by `symbol-sort-key` if set. Otherwise, sorts symbols by their y-position relative to the viewport if `icon-allow-overlap` or `text-allow-overlap` is set to `true` or `icon-ignore-placement` or `text-ignore-placement` is `false`." + }, + "viewport-y": { + doc: "Sorts symbols by their y-position relative to the viewport if `icon-allow-overlap` or `text-allow-overlap` is set to `true` or `icon-ignore-placement` or `text-ignore-placement` is `false`." + }, + source: { + doc: "Sorts symbols by `symbol-sort-key` if set. Otherwise, no sorting is applied; symbols are rendered in the same order as the source data." + } + }, + "default": "auto", + doc: "Determines whether overlapping symbols in the same layer are rendered in the order that they appear in the data source or by their y-position relative to the viewport. To control the order and prioritization of symbols otherwise, use `symbol-sort-key`.", + "sdk-support": { + "basic functionality": { + js: "0.49.0", + android: "6.6.0", + ios: "4.5.0", + macos: "0.12.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-allow-overlap": { + type: "boolean", + "default": false, + doc: "If true, the icon will be visible even if it collides with other previously drawn symbols.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-ignore-placement": { + type: "boolean", + "default": false, + doc: "If true, other symbols can be visible even if they collide with the icon.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-optional": { + type: "boolean", + "default": false, + doc: "If true, text will display without their corresponding icons when the icon collides with other symbols and the text does not.", + requires: [ + "icon-image", + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-rotation-alignment": { + type: "enum", + values: { + map: { + doc: "When `symbol-placement` is set to `point`, aligns icons east-west. When `symbol-placement` is set to `line` or `line-center`, aligns icon x-axes with the line." + }, + viewport: { + doc: "Produces icons whose x-axes are aligned with the x-axis of the viewport, regardless of the value of `symbol-placement`." + }, + auto: { + doc: "When `symbol-placement` is set to `point`, this is equivalent to `viewport`. When `symbol-placement` is set to `line` or `line-center`, this is equivalent to `map`." + } + }, + "default": "auto", + doc: "In combination with `symbol-placement`, determines the rotation behavior of icons.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "`auto` value": { + js: "0.25.0", + android: "4.2.0", + ios: "3.4.0", + macos: "0.3.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-size": { + type: "number", + "default": 1, + minimum: 0, + units: "factor of the original icon size", + doc: "Scales the original size of the icon by the provided factor. The new pixel size of the image will be the original pixel size multiplied by `icon-size`. 1 is the original size; 3 triples the size of the image.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.35.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-text-fit": { + type: "enum", + values: { + none: { + doc: "The icon is displayed at its intrinsic aspect ratio." + }, + width: { + doc: "The icon is scaled in the x-dimension to fit the width of the text." + }, + height: { + doc: "The icon is scaled in the y-dimension to fit the height of the text." + }, + both: { + doc: "The icon is scaled in both x- and y-dimensions." + } + }, + "default": "none", + doc: "Scales the icon to fit around the associated text.", + requires: [ + "icon-image", + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.21.0", + android: "4.2.0", + ios: "3.4.0", + macos: "0.2.1" + }, + "stretchable icons": { + js: "1.6.0", + android: "9.2.0", + ios: "5.8.0", + macos: "0.15.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-text-fit-padding": { + type: "array", + value: "number", + length: 4, + "default": [ + 0, + 0, + 0, + 0 + ], + units: "pixels", + doc: "Size of the additional area added to dimensions determined by `icon-text-fit`, in clockwise order: top, right, bottom, left.", + requires: [ + "icon-image", + "text-field", + { + "icon-text-fit": [ + "both", + "width", + "height" + ] + } + ], + "sdk-support": { + "basic functionality": { + js: "0.21.0", + android: "4.2.0", + ios: "3.4.0", + macos: "0.2.1" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-image": { + type: "resolvedImage", + doc: "Name of image in sprite to use for drawing an image background.", + tokens: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.35.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-rotate": { + type: "number", + "default": 0, + period: 360, + units: "degrees", + doc: "Rotates the icon clockwise.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.21.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-padding": { + type: "number", + "default": 2, + minimum: 0, + units: "pixels", + doc: "Size of the additional area around the icon bounding box used for detecting symbol collisions.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-keep-upright": { + type: "boolean", + "default": false, + doc: "If true, the icon may be flipped to prevent it from being rendered upside-down.", + requires: [ + "icon-image", + { + "icon-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-offset": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + doc: "Offset distance of icon from its anchor. Positive values indicate right and down, while negative values indicate left and up. Each component is multiplied by the value of `icon-size` to obtain the final offset in pixels. When combined with `icon-rotate` the offset will be as if the rotated direction was up.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-anchor": { + type: "enum", + values: { + center: { + doc: "The center of the icon is placed closest to the anchor." + }, + left: { + doc: "The left side of the icon is placed closest to the anchor." + }, + right: { + doc: "The right side of the icon is placed closest to the anchor." + }, + top: { + doc: "The top of the icon is placed closest to the anchor." + }, + bottom: { + doc: "The bottom of the icon is placed closest to the anchor." + }, + "top-left": { + doc: "The top left corner of the icon is placed closest to the anchor." + }, + "top-right": { + doc: "The top right corner of the icon is placed closest to the anchor." + }, + "bottom-left": { + doc: "The bottom left corner of the icon is placed closest to the anchor." + }, + "bottom-right": { + doc: "The bottom right corner of the icon is placed closest to the anchor." + } + }, + "default": "center", + doc: "Part of the icon placed closest to the anchor.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.40.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + }, + "data-driven styling": { + js: "0.40.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-pitch-alignment": { + type: "enum", + values: { + map: { + doc: "The icon is aligned to the plane of the map." + }, + viewport: { + doc: "The icon is aligned to the plane of the viewport." + }, + auto: { + doc: "Automatically matches the value of `icon-rotation-alignment`." + } + }, + "default": "auto", + doc: "Orientation of icon when map is pitched.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.39.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-pitch-alignment": { + type: "enum", + values: { + map: { + doc: "The text is aligned to the plane of the map." + }, + viewport: { + doc: "The text is aligned to the plane of the viewport." + }, + auto: { + doc: "Automatically matches the value of `text-rotation-alignment`." + } + }, + "default": "auto", + doc: "Orientation of text when map is pitched.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.21.0", + android: "4.2.0", + ios: "3.4.0", + macos: "0.2.1" + }, + "`auto` value": { + js: "0.25.0", + android: "4.2.0", + ios: "3.4.0", + macos: "0.3.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotation-alignment": { + type: "enum", + values: { + map: { + doc: "When `symbol-placement` is set to `point`, aligns text east-west. When `symbol-placement` is set to `line` or `line-center`, aligns text x-axes with the line." + }, + viewport: { + doc: "Produces glyphs whose x-axes are aligned with the x-axis of the viewport, regardless of the value of `symbol-placement`." + }, + auto: { + doc: "When `symbol-placement` is set to `point`, this is equivalent to `viewport`. When `symbol-placement` is set to `line` or `line-center`, this is equivalent to `map`." + } + }, + "default": "auto", + doc: "In combination with `symbol-placement`, determines the rotation behavior of the individual glyphs forming the text.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "`auto` value": { + js: "0.25.0", + android: "4.2.0", + ios: "3.4.0", + macos: "0.3.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-field": { + type: "formatted", + "default": "", + tokens: true, + doc: "Value to use for a text label. If a plain `string` is provided, it will be treated as a `formatted` with default/inherited formatting options.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-font": { + type: "array", + value: "string", + "default": [ + "Open Sans Regular", + "Arial Unicode MS Regular" + ], + doc: "Font stack to use for displaying text.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-size": { + type: "number", + "default": 16, + minimum: 0, + units: "pixels", + doc: "Font size.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.35.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-width": { + type: "number", + "default": 10, + minimum: 0, + units: "ems", + doc: "The maximum line width for text wrapping.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.40.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-line-height": { + type: "number", + "default": 1.2, + units: "ems", + doc: "Text leading value for multi-line text.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-letter-spacing": { + type: "number", + "default": 0, + units: "ems", + doc: "Text tracking amount.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.40.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-justify": { + type: "enum", + values: { + auto: { + doc: "The text is aligned towards the anchor position." + }, + left: { + doc: "The text is aligned to the left." + }, + center: { + doc: "The text is centered." + }, + right: { + doc: "The text is aligned to the right." + } + }, + "default": "center", + doc: "Text justification options.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.39.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + }, + auto: { + js: "0.54.0", + android: "7.4.0", + ios: "4.10.0", + macos: "0.14.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-radial-offset": { + type: "number", + units: "ems", + "default": 0, + doc: "Radial offset of text, in the direction of the symbol's anchor. Useful in combination with `text-variable-anchor`, which defaults to using the two-dimensional `text-offset` if present.", + "sdk-support": { + "basic functionality": { + js: "0.54.0", + android: "7.4.0", + ios: "4.10.0", + macos: "0.14.0" + }, + "data-driven styling": { + js: "0.54.0", + android: "7.4.0", + ios: "4.10.0", + macos: "0.14.0" + } + }, + requires: [ + "text-field" + ], + "property-type": "data-driven", + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + } + }, + "text-variable-anchor": { + type: "array", + value: "enum", + values: { + center: { + doc: "The center of the text is placed closest to the anchor." + }, + left: { + doc: "The left side of the text is placed closest to the anchor." + }, + right: { + doc: "The right side of the text is placed closest to the anchor." + }, + top: { + doc: "The top of the text is placed closest to the anchor." + }, + bottom: { + doc: "The bottom of the text is placed closest to the anchor." + }, + "top-left": { + doc: "The top left corner of the text is placed closest to the anchor." + }, + "top-right": { + doc: "The top right corner of the text is placed closest to the anchor." + }, + "bottom-left": { + doc: "The bottom left corner of the text is placed closest to the anchor." + }, + "bottom-right": { + doc: "The bottom right corner of the text is placed closest to the anchor." + } + }, + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + doc: "To increase the chance of placing high-priority labels on the map, you can provide an array of `text-anchor` locations: the renderer will attempt to place the label at each location, in order, before moving onto the next label. Use `text-justify: auto` to choose justification based on anchor position. To apply an offset, use the `text-radial-offset` or the two-dimensional `text-offset`.", + "sdk-support": { + "basic functionality": { + js: "0.54.0", + android: "7.4.0", + ios: "4.10.0", + macos: "0.14.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-anchor": { + type: "enum", + values: { + center: { + doc: "The center of the text is placed closest to the anchor." + }, + left: { + doc: "The left side of the text is placed closest to the anchor." + }, + right: { + doc: "The right side of the text is placed closest to the anchor." + }, + top: { + doc: "The top of the text is placed closest to the anchor." + }, + bottom: { + doc: "The bottom of the text is placed closest to the anchor." + }, + "top-left": { + doc: "The top left corner of the text is placed closest to the anchor." + }, + "top-right": { + doc: "The top right corner of the text is placed closest to the anchor." + }, + "bottom-left": { + doc: "The bottom left corner of the text is placed closest to the anchor." + }, + "bottom-right": { + doc: "The bottom right corner of the text is placed closest to the anchor." + } + }, + "default": "center", + doc: "Part of the text placed closest to the anchor.", + requires: [ + "text-field", + { + "!": "text-variable-anchor" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.39.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-angle": { + type: "number", + "default": 45, + units: "degrees", + doc: "Maximum angle change between adjacent characters.", + requires: [ + "text-field", + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-writing-mode": { + type: "array", + value: "enum", + values: { + horizontal: { + doc: "If a text's language supports horizontal writing mode, symbols with point placement would be laid out horizontally." + }, + vertical: { + doc: "If a text's language supports vertical writing mode, symbols with point placement would be laid out vertically." + } + }, + doc: "The property allows control over a symbol's orientation. Note that the property values act as a hint, so that a symbol whose language doesn’t support the provided orientation will be laid out in its natural orientation. Example: English point symbol will be rendered horizontally even if array value contains single 'vertical' enum value. The order of elements in an array define priority order for the placement of an orientation variant.", + requires: [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + "sdk-support": { + "basic functionality": { + js: "1.3.0", + android: "8.3.0", + ios: "5.3.0", + macos: "0.15.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotate": { + type: "number", + "default": 0, + period: 360, + units: "degrees", + doc: "Rotates the text clockwise.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.35.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-padding": { + type: "number", + "default": 2, + minimum: 0, + units: "pixels", + doc: "Size of the additional area around the text bounding box used for detecting symbol collisions.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-keep-upright": { + type: "boolean", + "default": true, + doc: "If true, the text may be flipped vertically to prevent it from being rendered upside-down.", + requires: [ + "text-field", + { + "text-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-transform": { + type: "enum", + values: { + none: { + doc: "The text is not altered." + }, + uppercase: { + doc: "Forces all letters to be displayed in uppercase." + }, + lowercase: { + doc: "Forces all letters to be displayed in lowercase." + } + }, + "default": "none", + doc: "Specifies how to capitalize text, similar to the CSS `text-transform` property.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-offset": { + type: "array", + doc: "Offset distance of text from its anchor. Positive values indicate right and down, while negative values indicate left and up. If used with text-variable-anchor, input values will be taken as absolute values. Offsets along the x- and y-axis will be applied automatically based on the anchor position.", + value: "number", + units: "ems", + length: 2, + "default": [ + 0, + 0 + ], + requires: [ + "text-field", + { + "!": "text-radial-offset" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.35.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-allow-overlap": { + type: "boolean", + "default": false, + doc: "If true, the text will be visible even if it collides with other previously drawn symbols.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-ignore-placement": { + type: "boolean", + "default": false, + doc: "If true, other symbols can be visible even if they collide with the text.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-optional": { + type: "boolean", + "default": false, + doc: "If true, icons will display without their corresponding text when the text collides with other symbols and the icon does not.", + requires: [ + "text-field", + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + "property-type": "constant" + } + }; + var layout_raster = { + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + "property-type": "constant" + } + }; + var layout_hillshade = { + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + "property-type": "constant" + } + }; + var filter = { + type: "array", + value: "*", + doc: "A filter selects specific features from a layer." + }; + var filter_operator = { + type: "enum", + values: { + "==": { + doc: "`[\"==\", key, value]` equality: `feature[key] = value`" + }, + "!=": { + doc: "`[\"!=\", key, value]` inequality: `feature[key] ≠ value`" + }, + ">": { + doc: "`[\">\", key, value]` greater than: `feature[key] > value`" + }, + ">=": { + doc: "`[\">=\", key, value]` greater than or equal: `feature[key] ≥ value`" + }, + "<": { + doc: "`[\"<\", key, value]` less than: `feature[key] < value`" + }, + "<=": { + doc: "`[\"<=\", key, value]` less than or equal: `feature[key] ≤ value`" + }, + "in": { + doc: "`[\"in\", key, v0, ..., vn]` set inclusion: `feature[key] ∈ {v0, ..., vn}`" + }, + "!in": { + doc: "`[\"!in\", key, v0, ..., vn]` set exclusion: `feature[key] ∉ {v0, ..., vn}`" + }, + all: { + doc: "`[\"all\", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`" + }, + any: { + doc: "`[\"any\", f0, ..., fn]` logical `OR`: `f0 ∨ ... ∨ fn`" + }, + none: { + doc: "`[\"none\", f0, ..., fn]` logical `NOR`: `¬f0 ∧ ... ∧ ¬fn`" + }, + has: { + doc: "`[\"has\", key]` `feature[key]` exists" + }, + "!has": { + doc: "`[\"!has\", key]` `feature[key]` does not exist" + }, + within: { + doc: "`[\"within\", object]` feature geometry is within object geometry" + } + }, + doc: "The filter operator." + }; + var geometry_type = { + type: "enum", + values: { + Point: { + doc: "Filter to point geometries." + }, + LineString: { + doc: "Filter to line geometries." + }, + Polygon: { + doc: "Filter to polygon geometries." + } + }, + doc: "The geometry type for the filter to select." + }; + var function_stop = { + type: "array", + minimum: 0, + maximum: 24, + value: [ + "number", + "color" + ], + length: 2, + doc: "Zoom level and value pair." + }; + var expression = { + type: "array", + value: "*", + minimum: 1, + doc: "An expression defines a function that can be used for data-driven style properties or feature filters." + }; + var expression_name = { + doc: "", + type: "enum", + values: { + "let": { + doc: "Binds expressions to named variables, which can then be referenced in the result expression using [\"var\", \"variable_name\"].", + group: "Variable binding", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "var": { + doc: "References variable bound using \"let\".", + group: "Variable binding", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + literal: { + doc: "Provides a literal array or object value.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + array: { + doc: "Asserts that the input is an array (optionally with a specific item type and length). If, when the input expression is evaluated, it is not of the asserted type, then this assertion will cause the whole expression to be aborted.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + at: { + doc: "Retrieves an item from an array.", + group: "Lookup", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "in": { + doc: "Determines whether an item exists in an array or a substring exists in a string.", + group: "Lookup", + "sdk-support": { + "basic functionality": { + js: "1.6.0", + android: "9.1.0", + ios: "5.8.0", + macos: "0.15.0" + } + } + }, + "index-of": { + doc: "Returns the first position at which an item can be found in an array or a substring can be found in a string, or `-1` if the input cannot be found. Accepts an optional index from where to begin the search.", + group: "Lookup", + "sdk-support": { + "basic functionality": { + js: "1.10.0" + } + } + }, + slice: { + doc: "Returns an item from an array or a substring from a string from a specified start index, or between a start index and an end index if set. The return value is inclusive of the start index but not of the end index.", + group: "Lookup", + "sdk-support": { + "basic functionality": { + js: "1.10.0" + } + } + }, + "case": { + doc: "Selects the first output whose corresponding test condition evaluates to true, or the fallback value otherwise.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + match: { + doc: "Selects the output whose label value matches the input value, or the fallback value if no match is found. The input can be any expression (e.g. `[\"get\", \"building_type\"]`). Each label must be either:\n - a single literal value; or\n - an array of literal values, whose values must be all strings or all numbers (e.g. `[100, 101]` or `[\"c\", \"b\"]`). The input matches if any of the values in the array matches, similar to the `\"in\"` operator.\nEach label must be unique. If the input type does not match the type of the labels, the result will be the fallback value.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + coalesce: { + doc: "Evaluates each expression in turn until the first non-null value is obtained, and returns that value.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + step: { + doc: "Produces discrete, stepped results by evaluating a piecewise-constant function defined by pairs of input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). Stop inputs must be numeric literals in strictly ascending order. Returns the output value of the stop just less than the input, or the first output if the input is less than the first stop.", + group: "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + js: "0.42.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + interpolate: { + doc: "Produces continuous, smooth results by interpolating between pairs of input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). Stop inputs must be numeric literals in strictly ascending order. The output type must be `number`, `array`, or `color`.\n\nInterpolation types:\n- `[\"linear\"]`: Interpolates linearly between the pair of stops just less than and just greater than the input.\n- `[\"exponential\", base]`: Interpolates exponentially between the stops just less than and just greater than the input. `base` controls the rate at which the output increases: higher values make the output increase more towards the high end of the range. With values close to 1 the output increases linearly.\n- `[\"cubic-bezier\", x1, y1, x2, y2]`: Interpolates using the cubic bezier curve defined by the given control points.", + group: "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + js: "0.42.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "interpolate-hcl": { + doc: "Produces continuous, smooth results by interpolating between pairs of input and output values (\"stops\"). Works like `interpolate`, but the output type must be `color`, and the interpolation is performed in the Hue-Chroma-Luminance color space.", + group: "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + js: "0.49.0" + } + } + }, + "interpolate-lab": { + doc: "Produces continuous, smooth results by interpolating between pairs of input and output values (\"stops\"). Works like `interpolate`, but the output type must be `color`, and the interpolation is performed in the CIELAB color space.", + group: "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + js: "0.49.0" + } + } + }, + ln2: { + doc: "Returns mathematical constant ln(2).", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + pi: { + doc: "Returns the mathematical constant pi.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + e: { + doc: "Returns the mathematical constant e.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "typeof": { + doc: "Returns a string describing the type of the given value.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + string: { + doc: "Asserts that the input value is a string. If multiple values are provided, each one is evaluated in order until a string is obtained. If none of the inputs are strings, the expression is an error.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + number: { + doc: "Asserts that the input value is a number. If multiple values are provided, each one is evaluated in order until a number is obtained. If none of the inputs are numbers, the expression is an error.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + boolean: { + doc: "Asserts that the input value is a boolean. If multiple values are provided, each one is evaluated in order until a boolean is obtained. If none of the inputs are booleans, the expression is an error.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + object: { + doc: "Asserts that the input value is an object. If multiple values are provided, each one is evaluated in order until an object is obtained. If none of the inputs are objects, the expression is an error.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + collator: { + doc: "Returns a `collator` for use in locale-dependent comparison operations. The `case-sensitive` and `diacritic-sensitive` options default to `false`. The `locale` argument specifies the IETF language tag of the locale to use. If none is provided, the default locale is used. If the requested locale is not available, the `collator` will use a system-defined fallback locale. Use `resolved-locale` to test the results of locale fallback behavior.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + }, + format: { + doc: "Returns a `formatted` string for displaying mixed-format text in the `text-field` property. The input may contain a string literal or expression, including an [`'image'`](#types-image) expression. Strings may be followed by a style override object that supports the following properties:\n- `\"text-font\"`: Overrides the font stack specified by the root layout property.\n- `\"text-color\"`: Overrides the color specified by the root paint property.\n- `\"font-scale\"`: Applies a scaling factor on `text-size` as specified by the root layout property.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.48.0", + android: "6.7.0", + ios: "4.6.0", + macos: "0.12.0" + }, + "text-font": { + js: "0.48.0", + android: "6.7.0", + ios: "4.6.0", + macos: "0.12.0" + }, + "font-scale": { + js: "0.48.0", + android: "6.7.0", + ios: "4.6.0", + macos: "0.12.0" + }, + "text-color": { + js: "1.3.0", + android: "7.3.0", + ios: "4.10.0", + macos: "0.14.0" + }, + image: { + js: "1.6.0", + android: "8.6.0", + ios: "5.7.0", + macos: "0.15.0" + } + } + }, + image: { + doc: "Returns an `image` type for use in `icon-image`, `*-pattern` entries and as a section in the `format` expression. If set, the `image` argument will check that the requested image exists in the style and will return either the resolved image name or `null`, depending on whether or not the image is currently in the style. This validation process is synchronous and requires the image to have been added to the style before requesting it in the `image` argument.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "1.4.0", + android: "8.6.0", + ios: "5.7.0", + macos: "0.15.0" + } + } + }, + "number-format": { + doc: "Converts the input number into a string representation using the providing formatting rules. If set, the `locale` argument specifies the locale to use, as a BCP 47 language tag. If set, the `currency` argument specifies an ISO 4217 code to use for currency-style formatting. If set, the `min-fraction-digits` and `max-fraction-digits` arguments specify the minimum and maximum number of fractional digits to include.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.54.0" + } + } + }, + "to-string": { + doc: "Converts the input value to a string. If the input is `null`, the result is `\"\"`. If the input is a boolean, the result is `\"true\"` or `\"false\"`. If the input is a number, it is converted to a string as specified by the [\"NumberToString\" algorithm](https://tc39.github.io/ecma262/#sec-tostring-applied-to-the-number-type) of the ECMAScript Language Specification. If the input is a color, it is converted to a string of the form `\"rgba(r,g,b,a)\"`, where `r`, `g`, and `b` are numerals ranging from 0 to 255, and `a` ranges from 0 to 1. Otherwise, the input is converted to a string in the format specified by the [`JSON.stringify`](https://tc39.github.io/ecma262/#sec-json.stringify) function of the ECMAScript Language Specification.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "to-number": { + doc: "Converts the input value to a number, if possible. If the input is `null` or `false`, the result is 0. If the input is `true`, the result is 1. If the input is a string, it is converted to a number as specified by the [\"ToNumber Applied to the String Type\" algorithm](https://tc39.github.io/ecma262/#sec-tonumber-applied-to-the-string-type) of the ECMAScript Language Specification. If multiple values are provided, each one is evaluated in order until the first successful conversion is obtained. If none of the inputs can be converted, the expression is an error.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "to-boolean": { + doc: "Converts the input value to a boolean. The result is `false` when then input is an empty string, 0, `false`, `null`, or `NaN`; otherwise it is `true`.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "to-rgba": { + doc: "Returns a four-element array containing the input color's red, green, blue, and alpha components, in that order.", + group: "Color", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "to-color": { + doc: "Converts the input value to a color. If multiple values are provided, each one is evaluated in order until the first successful conversion is obtained. If none of the inputs can be converted, the expression is an error.", + group: "Types", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + rgb: { + doc: "Creates a color value from red, green, and blue components, which must range between 0 and 255, and an alpha component of 1. If any component is out of range, the expression is an error.", + group: "Color", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + rgba: { + doc: "Creates a color value from red, green, blue components, which must range between 0 and 255, and an alpha component which must range between 0 and 1. If any component is out of range, the expression is an error.", + group: "Color", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + get: { + doc: "Retrieves a property value from the current feature's properties, or from another object if a second argument is provided. Returns null if the requested property is missing.", + group: "Lookup", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + has: { + doc: "Tests for the presence of an property value in the current feature's properties, or from another object if a second argument is provided.", + group: "Lookup", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + length: { + doc: "Gets the length of an array or string.", + group: "Lookup", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + properties: { + doc: "Gets the feature properties object. Note that in some cases, it may be more efficient to use [\"get\", \"property_name\"] directly.", + group: "Feature data", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "feature-state": { + doc: "Retrieves a property value from the current feature's state. Returns null if the requested property is not present on the feature's state. A feature's state is not part of the GeoJSON or vector tile data, and must be set programmatically on each feature. Features are identified by their `id` attribute, which must be an integer or a string that can be cast to an integer. Note that [\"feature-state\"] can only be used with paint properties that support data-driven styling.", + group: "Feature data", + "sdk-support": { + "basic functionality": { + js: "0.46.0" + } + } + }, + "geometry-type": { + doc: "Gets the feature's geometry type: `Point`, `MultiPoint`, `LineString`, `MultiLineString`, `Polygon`, `MultiPolygon`.", + group: "Feature data", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + id: { + doc: "Gets the feature's id, if it has one.", + group: "Feature data", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + zoom: { + doc: "Gets the current zoom level. Note that in style layout and paint properties, [\"zoom\"] may only appear as the input to a top-level \"step\" or \"interpolate\" expression.", + group: "Zoom", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "heatmap-density": { + doc: "Gets the kernel density estimation of a pixel in a heatmap layer, which is a relative measure of how many data points are crowded around a particular pixel. Can only be used in the `heatmap-color` property.", + group: "Heatmap", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "line-progress": { + doc: "Gets the progress along a gradient line. Can only be used in the `line-gradient` property.", + group: "Feature data", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.5.0", + ios: "4.6.0", + macos: "0.12.0" + } + } + }, + accumulated: { + doc: "Gets the value of a cluster property accumulated so far. Can only be used in the `clusterProperties` option of a clustered GeoJSON source.", + group: "Feature data", + "sdk-support": { + "basic functionality": { + js: "0.53.0" + } + } + }, + "+": { + doc: "Returns the sum of the inputs.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "*": { + doc: "Returns the product of the inputs.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "-": { + doc: "For two inputs, returns the result of subtracting the second input from the first. For a single input, returns the result of subtracting it from 0.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "/": { + doc: "Returns the result of floating point division of the first input by the second.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "%": { + doc: "Returns the remainder after integer division of the first input by the second.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "^": { + doc: "Returns the result of raising the first input to the power specified by the second.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + sqrt: { + doc: "Returns the square root of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.42.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + log10: { + doc: "Returns the base-ten logarithm of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + ln: { + doc: "Returns the natural logarithm of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + log2: { + doc: "Returns the base-two logarithm of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + sin: { + doc: "Returns the sine of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + cos: { + doc: "Returns the cosine of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + tan: { + doc: "Returns the tangent of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + asin: { + doc: "Returns the arcsine of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + acos: { + doc: "Returns the arccosine of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + atan: { + doc: "Returns the arctangent of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + min: { + doc: "Returns the minimum value of the inputs.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + max: { + doc: "Returns the maximum value of the inputs.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + round: { + doc: "Rounds the input to the nearest integer. Halfway values are rounded away from zero. For example, `[\"round\", -1.5]` evaluates to -2.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + abs: { + doc: "Returns the absolute value of the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + ceil: { + doc: "Returns the smallest integer that is greater than or equal to the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + floor: { + doc: "Returns the largest integer that is less than or equal to the input.", + group: "Math", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + distance: { + doc: "Returns the shortest distance in meters between the evaluated feature and the input geometry. The input value can be a valid GeoJSON of type `Point`, `MultiPoint`, `LineString`, `MultiLineString`, `Polygon`, `MultiPolygon`, `Feature`, or `FeatureCollection`. Distance values returned may vary in precision due to loss in precision from encoding geometries, particularly below zoom level 13.", + group: "Math", + "sdk-support": { + "basic functionality": { + android: "9.2.0", + ios: "5.9.0", + macos: "0.16.0" + } + } + }, + "==": { + doc: "Returns `true` if the input values are equal, `false` otherwise. The comparison is strictly typed: values of different runtime types are always considered unequal. Cases where the types are known to be different at parse time are considered invalid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + collator: { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + }, + "!=": { + doc: "Returns `true` if the input values are not equal, `false` otherwise. The comparison is strictly typed: values of different runtime types are always considered unequal. Cases where the types are known to be different at parse time are considered invalid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + collator: { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + }, + ">": { + doc: "Returns `true` if the first input is strictly greater than the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + collator: { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + }, + "<": { + doc: "Returns `true` if the first input is strictly less than the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + collator: { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + }, + ">=": { + doc: "Returns `true` if the first input is greater than or equal to the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + collator: { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + }, + "<=": { + doc: "Returns `true` if the first input is less than or equal to the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + collator: { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + }, + all: { + doc: "Returns `true` if all the inputs are `true`, `false` otherwise. The inputs are evaluated in order, and evaluation is short-circuiting: once an input expression evaluates to `false`, the result is `false` and no further input expressions are evaluated.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + any: { + doc: "Returns `true` if any of the inputs are `true`, `false` otherwise. The inputs are evaluated in order, and evaluation is short-circuiting: once an input expression evaluates to `true`, the result is `true` and no further input expressions are evaluated.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "!": { + doc: "Logical negation. Returns `true` if the input is `false`, and `false` if the input is `true`.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + within: { + doc: "Returns `true` if the evaluated feature is fully contained inside a boundary of the input geometry, `false` otherwise. The input value can be a valid GeoJSON of type `Polygon`, `MultiPolygon`, `Feature`, or `FeatureCollection`. Supported features for evaluation:\n- `Point`: Returns `false` if a point is on the boundary or falls outside the boundary.\n- `LineString`: Returns `false` if any part of a line falls outside the boundary, the line intersects the boundary, or a line's endpoint is on the boundary.", + group: "Decision", + "sdk-support": { + "basic functionality": { + js: "1.9.0", + android: "9.1.0", + ios: "5.8.0", + macos: "0.15.0" + } + } + }, + "is-supported-script": { + doc: "Returns `true` if the input string is expected to render legibly. Returns `false` if the input string contains sections that cannot be rendered without potential loss of meaning (e.g. Indic scripts that require complex text shaping, or right-to-left scripts if the the `mapbox-gl-rtl-text` plugin is not in use in Mapbox GL JS).", + group: "String", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.6.0" + } + } + }, + upcase: { + doc: "Returns the input string converted to uppercase. Follows the Unicode Default Case Conversion algorithm and the locale-insensitive case mappings in the Unicode Character Database.", + group: "String", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + downcase: { + doc: "Returns the input string converted to lowercase. Follows the Unicode Default Case Conversion algorithm and the locale-insensitive case mappings in the Unicode Character Database.", + group: "String", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + concat: { + doc: "Returns a `string` consisting of the concatenation of the inputs. Each input is converted to a string as if by `to-string`.", + group: "String", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + } + }, + "resolved-locale": { + doc: "Returns the IETF language tag of the locale being used by the provided `collator`. This can be used to determine the default system locale, or to determine if a requested locale was successfully loaded.", + group: "String", + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.5.0", + ios: "4.2.0", + macos: "0.9.0" + } + } + } + } + }; + var light = { + anchor: { + type: "enum", + "default": "viewport", + values: { + map: { + doc: "The position of the light source is aligned to the rotation of the map." + }, + viewport: { + doc: "The position of the light source is aligned to the rotation of the viewport." + } + }, + "property-type": "data-constant", + transition: false, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + doc: "Whether extruded geometries are lit relative to the map or viewport.", + example: "map", + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + } + }, + position: { + type: "array", + "default": [ + 1.15, + 210, + 30 + ], + length: 3, + value: "number", + "property-type": "data-constant", + transition: true, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + doc: "Position of the light source relative to lit (extruded) geometries, in [r radial coordinate, a azimuthal angle, p polar angle] where r indicates the distance from the center of the base of an object to its light, a indicates the position of the light relative to 0° (0° when `light.anchor` is set to `viewport` corresponds to the top of the viewport, or 0° when `light.anchor` is set to `map` corresponds to due north, and degrees proceed clockwise), and p indicates the height of the light (from 0°, directly above, to 180°, directly below).", + example: [ + 1.5, + 90, + 80 + ], + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + } + }, + color: { + type: "color", + "property-type": "data-constant", + "default": "#ffffff", + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true, + doc: "Color tint for lighting extruded geometries.", + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + } + }, + intensity: { + type: "number", + "property-type": "data-constant", + "default": 0.5, + minimum: 0, + maximum: 1, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + transition: true, + doc: "Intensity of lighting (on a scale from 0 to 1). Higher numbers will present as more extreme contrast.", + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + } + } + }; + var paint = [ + "paint_fill", + "paint_line", + "paint_circle", + "paint_heatmap", + "paint_fill-extrusion", + "paint_symbol", + "paint_raster", + "paint_hillshade", + "paint_background" + ]; + var paint_fill = { + "fill-antialias": { + type: "boolean", + "default": true, + doc: "Whether or not the fill should be antialiased.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + doc: "The opacity of the entire fill layer. In contrast to the `fill-color`, this value will also affect the 1px stroke around the fill, if the stroke is used.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.21.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-color": { + type: "color", + "default": "#000000", + doc: "The color of the filled part of this layer. This color can be specified as `rgba` with an alpha component and the color's opacity will not affect the opacity of the 1px stroke, if it is used.", + transition: true, + requires: [ + { + "!": "fill-pattern" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.19.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-outline-color": { + type: "color", + doc: "The outline color of the fill. Matches the value of `fill-color` if unspecified.", + transition: true, + requires: [ + { + "!": "fill-pattern" + }, + { + "fill-antialias": true + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.19.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + doc: "The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-translate-anchor": { + type: "enum", + values: { + map: { + doc: "The fill is translated relative to the map." + }, + viewport: { + doc: "The fill is translated relative to the viewport." + } + }, + doc: "Controls the frame of reference for `fill-translate`.", + "default": "map", + requires: [ + "fill-translate" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-pattern": { + type: "resolvedImage", + transition: true, + doc: "Name of image in sprite to use for drawing image fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.49.0", + android: "6.5.0", + macos: "0.11.0", + ios: "4.4.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + } + }; + var paint_line = { + "line-opacity": { + type: "number", + doc: "The opacity at which the line will be drawn.", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-color": { + type: "color", + doc: "The color with which the line will be drawn.", + "default": "#000000", + transition: true, + requires: [ + { + "!": "line-pattern" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.23.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + doc: "The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-translate-anchor": { + type: "enum", + values: { + map: { + doc: "The line is translated relative to the map." + }, + viewport: { + doc: "The line is translated relative to the viewport." + } + }, + doc: "Controls the frame of reference for `line-translate`.", + "default": "map", + requires: [ + "line-translate" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-width": { + type: "number", + "default": 1, + minimum: 0, + transition: true, + units: "pixels", + doc: "Stroke thickness.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.39.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-gap-width": { + type: "number", + "default": 0, + minimum: 0, + doc: "Draws a line casing outside of a line's actual path. Value indicates the width of the inner gap.", + transition: true, + units: "pixels", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-offset": { + type: "number", + "default": 0, + doc: "The line's offset. For linear features, a positive value offsets the line to the right, relative to the direction of the line, and a negative value to the left. For polygon features, a positive value results in an inset, and a negative value results in an outset.", + transition: true, + units: "pixels", + "sdk-support": { + "basic functionality": { + js: "0.12.1", + android: "3.0.0", + ios: "3.1.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + doc: "Blur applied to the line, in pixels.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-dasharray": { + type: "array", + value: "number", + doc: "Specifies the lengths of the alternating dashes and gaps that form the dash pattern. The lengths are later scaled by the line width. To convert a dash length to pixels, multiply the length by the current line width. Note that GeoJSON sources with `lineMetrics: true` specified won't render dashed lines to the expected scale. Also note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + minimum: 0, + transition: true, + units: "line widths", + requires: [ + { + "!": "line-pattern" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "line-pattern": { + type: "resolvedImage", + transition: true, + doc: "Name of image in sprite to use for drawing image lines. For seamless patterns, image width must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.49.0", + android: "6.5.0", + macos: "0.11.0", + ios: "4.4.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "line-gradient": { + type: "color", + doc: "Defines a gradient with which to color a line feature. Can only be used with GeoJSON sources that specify `\"lineMetrics\": true`.", + transition: false, + requires: [ + { + "!": "line-dasharray" + }, + { + "!": "line-pattern" + }, + { + source: "geojson", + has: { + lineMetrics: true + } + } + ], + "sdk-support": { + "basic functionality": { + js: "0.45.0", + android: "6.5.0", + ios: "4.4.0", + macos: "0.11.0" + }, + "data-driven styling": { + } + }, + expression: { + interpolated: true, + parameters: [ + "line-progress" + ] + }, + "property-type": "color-ramp" + } + }; + var paint_circle = { + "circle-radius": { + type: "number", + "default": 5, + minimum: 0, + transition: true, + units: "pixels", + doc: "Circle radius.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.18.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-color": { + type: "color", + "default": "#000000", + doc: "The fill color of the circle.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.18.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-blur": { + type: "number", + "default": 0, + doc: "Amount to blur the circle. 1 blurs the circle such that only the centerpoint is full opacity.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.20.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-opacity": { + type: "number", + doc: "The opacity at which the circle will be drawn.", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.20.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + doc: "The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-translate-anchor": { + type: "enum", + values: { + map: { + doc: "The circle is translated relative to the map." + }, + viewport: { + doc: "The circle is translated relative to the viewport." + } + }, + doc: "Controls the frame of reference for `circle-translate`.", + "default": "map", + requires: [ + "circle-translate" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-scale": { + type: "enum", + values: { + map: { + doc: "Circles are scaled according to their apparent distance to the camera." + }, + viewport: { + doc: "Circles are not scaled." + } + }, + "default": "map", + doc: "Controls the scaling behavior of the circle when the map is pitched.", + "sdk-support": { + "basic functionality": { + js: "0.21.0", + android: "4.2.0", + ios: "3.4.0", + macos: "0.2.1" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-alignment": { + type: "enum", + values: { + map: { + doc: "The circle is aligned to the plane of the map." + }, + viewport: { + doc: "The circle is aligned to the plane of the viewport." + } + }, + "default": "viewport", + doc: "Orientation of circle when map is pitched.", + "sdk-support": { + "basic functionality": { + js: "0.39.0", + android: "5.2.0", + ios: "3.7.0", + macos: "0.6.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-stroke-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + doc: "The width of the circle's stroke. Strokes are placed outside of the `circle-radius`.", + "sdk-support": { + "basic functionality": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-color": { + type: "color", + "default": "#000000", + doc: "The stroke color of the circle.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-opacity": { + type: "number", + doc: "The opacity of the circle's stroke.", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + }, + "data-driven styling": { + js: "0.29.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + } + }; + var paint_heatmap = { + "heatmap-radius": { + type: "number", + "default": 30, + minimum: 1, + transition: true, + units: "pixels", + doc: "Radius of influence of one heatmap point in pixels. Increasing the value makes the heatmap smoother, but less detailed.", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + "data-driven styling": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-weight": { + type: "number", + "default": 1, + minimum: 0, + transition: false, + doc: "A measure of how much an individual point contributes to the heatmap. A value of 10 would be equivalent to having 10 points of weight 1 in the same spot. Especially useful when combined with clustering.", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + "data-driven styling": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-intensity": { + type: "number", + "default": 1, + minimum: 0, + transition: true, + doc: "Similar to `heatmap-weight` but controls the intensity of the heatmap globally. Primarily used for adjusting the heatmap based on zoom level.", + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "heatmap-color": { + type: "color", + "default": [ + "interpolate", + [ + "linear" + ], + [ + "heatmap-density" + ], + 0, + "rgba(0, 0, 255, 0)", + 0.1, + "royalblue", + 0.3, + "cyan", + 0.5, + "lime", + 0.7, + "yellow", + 1, + "red" + ], + doc: "Defines the color of each pixel based on its density value in a heatmap. Should be an expression that uses `[\"heatmap-density\"]` as input.", + transition: false, + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + }, + "data-driven styling": { + } + }, + expression: { + interpolated: true, + parameters: [ + "heatmap-density" + ] + }, + "property-type": "color-ramp" + }, + "heatmap-opacity": { + type: "number", + doc: "The global opacity at which the heatmap layer will be drawn.", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.41.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }; + var paint_symbol = { + "icon-opacity": { + doc: "The opacity at which the icon will be drawn.", + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-color": { + type: "color", + "default": "#000000", + transition: true, + doc: "The color of the icon. This can only be used with sdf icons.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-color": { + type: "color", + "default": "rgba(0, 0, 0, 0)", + transition: true, + doc: "The color of the icon's halo. Icon halos can only be used with SDF icons.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + doc: "Distance of halo to the icon outline.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + doc: "Fade out the halo towards the outside.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + doc: "Distance that the icon's anchor is moved from its original placement. Positive values indicate right and down, while negative values indicate left and up.", + requires: [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-translate-anchor": { + type: "enum", + values: { + map: { + doc: "Icons are translated relative to the map." + }, + viewport: { + doc: "Icons are translated relative to the viewport." + } + }, + doc: "Controls the frame of reference for `icon-translate`.", + "default": "map", + requires: [ + "icon-image", + "icon-translate" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-opacity": { + type: "number", + doc: "The opacity at which the text will be drawn.", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-color": { + type: "color", + doc: "The color with which the text will be drawn.", + "default": "#000000", + transition: true, + overridable: true, + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-color": { + type: "color", + "default": "rgba(0, 0, 0, 0)", + transition: true, + doc: "The color of the text's halo, which helps it stand out from backgrounds.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-width": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + doc: "Distance of halo to the font outline. Max text halo width is 1/4 of the font-size.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-blur": { + type: "number", + "default": 0, + minimum: 0, + transition: true, + units: "pixels", + doc: "The halo's fadeout distance towards the outside.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + js: "0.33.0", + android: "5.0.0", + ios: "3.5.0", + macos: "0.4.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + doc: "Distance that the text's anchor is moved from its original placement. Positive values indicate right and down, while negative values indicate left and up.", + requires: [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-translate-anchor": { + type: "enum", + values: { + map: { + doc: "The text is translated relative to the map." + }, + viewport: { + doc: "The text is translated relative to the viewport." + } + }, + doc: "Controls the frame of reference for `text-translate`.", + "default": "map", + requires: [ + "text-field", + "text-translate" + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }; + var paint_raster = { + "raster-opacity": { + type: "number", + doc: "The opacity at which the image will be drawn.", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-hue-rotate": { + type: "number", + "default": 0, + period: 360, + transition: true, + units: "degrees", + doc: "Rotates hues around the color wheel.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-min": { + type: "number", + doc: "Increase or reduce the brightness of the image. The value is the minimum brightness.", + "default": 0, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-max": { + type: "number", + doc: "Increase or reduce the brightness of the image. The value is the maximum brightness.", + "default": 1, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-saturation": { + type: "number", + doc: "Increase or reduce the saturation of the image.", + "default": 0, + minimum: -1, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-contrast": { + type: "number", + doc: "Increase or reduce the contrast of the image.", + "default": 0, + minimum: -1, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-resampling": { + type: "enum", + doc: "The resampling/interpolation method to use for overscaling, also known as texture magnification filter", + values: { + linear: { + doc: "(Bi)linear filtering interpolates pixel values using the weighted average of the four closest original source pixels creating a smooth but blurry look when overscaled" + }, + nearest: { + doc: "Nearest neighbor filtering interpolates pixel values using the nearest original source pixel creating a sharp but pixelated look when overscaled" + } + }, + "default": "linear", + "sdk-support": { + "basic functionality": { + js: "0.47.0", + android: "6.3.0", + ios: "4.2.0", + macos: "0.9.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-fade-duration": { + type: "number", + "default": 300, + minimum: 0, + transition: false, + units: "milliseconds", + doc: "Fade duration when a new tile is added.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }; + var paint_hillshade = { + "hillshade-illumination-direction": { + type: "number", + "default": 335, + minimum: 0, + maximum: 359, + doc: "The direction of the light source used to generate the hillshading with 0 as the top of the viewport if `hillshade-illumination-anchor` is set to `viewport` and due north if `hillshade-illumination-anchor` is set to `map`.", + transition: false, + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-illumination-anchor": { + type: "enum", + values: { + map: { + doc: "The hillshade illumination is relative to the north direction." + }, + viewport: { + doc: "The hillshade illumination is relative to the top of the viewport." + } + }, + "default": "viewport", + doc: "Direction of light source when map is rotated.", + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-exaggeration": { + type: "number", + doc: "Intensity of the hillshade", + "default": 0.5, + minimum: 0, + maximum: 1, + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-shadow-color": { + type: "color", + "default": "#000000", + doc: "The shading color of areas that face away from the light source.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-highlight-color": { + type: "color", + "default": "#FFFFFF", + doc: "The shading color of areas that faces towards the light source.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-accent-color": { + type: "color", + "default": "#000000", + doc: "The shading color used to accentuate rugged terrain like sharp cliffs and gorges.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.43.0", + android: "6.0.0", + ios: "4.0.0", + macos: "0.7.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }; + var paint_background = { + "background-color": { + type: "color", + "default": "#000000", + doc: "The color with which the background will be drawn.", + transition: true, + requires: [ + { + "!": "background-pattern" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "background-pattern": { + type: "resolvedImage", + transition: true, + doc: "Name of image in sprite to use for drawing an image background. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + }, + "data-driven styling": { + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "background-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + doc: "The opacity at which the background will be drawn.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.10.0", + android: "2.0.1", + ios: "2.0.0", + macos: "0.1.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }; + var transition = { + duration: { + type: "number", + "default": 300, + minimum: 0, + units: "milliseconds", + doc: "Time allotted for transitions to complete." + }, + delay: { + type: "number", + "default": 0, + minimum: 0, + units: "milliseconds", + doc: "Length of time before a transition begins." + } + }; + var promoteId = { + "*": { + type: "string", + doc: "A name of a feature property to use as ID for feature state." + } + }; + var v8 = { + $version: $version, + $root: $root, + sources: sources, + source: source, + source_vector: source_vector, + source_raster: source_raster, + source_raster_dem: source_raster_dem, + source_geojson: source_geojson, + source_video: source_video, + source_image: source_image, + layer: layer, + layout: layout, + layout_background: layout_background, + layout_fill: layout_fill, + layout_circle: layout_circle, + layout_heatmap: layout_heatmap, + "layout_fill-extrusion": { + visibility: { + type: "enum", + values: { + visible: { + doc: "The layer is shown." + }, + none: { + doc: "The layer is not shown." + } + }, + "default": "visible", + doc: "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + "property-type": "constant" + } + }, + layout_line: layout_line, + layout_symbol: layout_symbol, + layout_raster: layout_raster, + layout_hillshade: layout_hillshade, + filter: filter, + filter_operator: filter_operator, + geometry_type: geometry_type, + "function": { + expression: { + type: "expression", + doc: "An expression." + }, + stops: { + type: "array", + doc: "An array of stops.", + value: "function_stop" + }, + base: { + type: "number", + "default": 1, + minimum: 0, + doc: "The exponential base of the interpolation curve. It controls the rate at which the result increases. Higher values make the result increase more towards the high end of the range. With `1` the stops are interpolated linearly." + }, + property: { + type: "string", + doc: "The name of a feature property to use as the function input.", + "default": "$zoom" + }, + type: { + type: "enum", + values: { + identity: { + doc: "Return the input value as the output value." + }, + exponential: { + doc: "Generate an output by interpolating between stops just less than and just greater than the function input." + }, + interval: { + doc: "Return the output value of the stop just less than the function input." + }, + categorical: { + doc: "Return the output value of the stop equal to the function input." + } + }, + doc: "The interpolation strategy to use in function evaluation.", + "default": "exponential" + }, + colorSpace: { + type: "enum", + values: { + rgb: { + doc: "Use the RGB color space to interpolate color values" + }, + lab: { + doc: "Use the LAB color space to interpolate color values." + }, + hcl: { + doc: "Use the HCL color space to interpolate color values, interpolating the Hue, Chroma, and Luminance channels individually." + } + }, + doc: "The color space in which colors interpolated. Interpolating colors in perceptual color spaces like LAB and HCL tend to produce color ramps that look more consistent and produce colors that can be differentiated more easily than those interpolated in RGB space.", + "default": "rgb" + }, + "default": { + type: "*", + required: false, + doc: "A value to serve as a fallback function result when a value isn't otherwise available. It is used in the following circumstances:\n* In categorical functions, when the feature value does not match any of the stop domain values.\n* In property and zoom-and-property functions, when a feature does not contain a value for the specified property.\n* In identity functions, when the feature value is not valid for the style property (for example, if the function is being used for a `circle-color` property but the feature property value is not a string or not a valid color).\n* In interval or exponential property and zoom-and-property functions, when the feature value is not numeric.\nIf no default is provided, the style property's default is used in these circumstances." + } + }, + function_stop: function_stop, + expression: expression, + expression_name: expression_name, + light: light, + paint: paint, + paint_fill: paint_fill, + "paint_fill-extrusion": { + "fill-extrusion-opacity": { + type: "number", + "default": 1, + minimum: 0, + maximum: 1, + doc: "The opacity of the entire fill extrusion layer. This is rendered on a per-layer, not per-feature, basis, and data-driven styling is not available.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-color": { + type: "color", + "default": "#000000", + doc: "The base color of the extruded fill. The extrusion's surfaces will be shaded differently based on this color in combination with the root `light` settings. If this color is specified as `rgba` with an alpha component, the alpha component will be ignored; use `fill-extrusion-opacity` to set layer opacity.", + transition: true, + requires: [ + { + "!": "fill-extrusion-pattern" + } + ], + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + }, + "data-driven styling": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-translate": { + type: "array", + value: "number", + length: 2, + "default": [ + 0, + 0 + ], + transition: true, + units: "pixels", + doc: "The geometry's offset. Values are [x, y] where negatives indicate left and up (on the flat plane), respectively.", + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-translate-anchor": { + type: "enum", + values: { + map: { + doc: "The fill extrusion is translated relative to the map." + }, + viewport: { + doc: "The fill extrusion is translated relative to the viewport." + } + }, + doc: "Controls the frame of reference for `fill-extrusion-translate`.", + "default": "map", + requires: [ + "fill-extrusion-translate" + ], + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-pattern": { + type: "resolvedImage", + transition: true, + doc: "Name of image in sprite to use for drawing images on extruded fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + }, + "data-driven styling": { + js: "0.49.0", + android: "6.5.0", + macos: "0.11.0", + ios: "4.4.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "fill-extrusion-height": { + type: "number", + "default": 0, + minimum: 0, + units: "meters", + doc: "The height with which to extrude this layer.", + transition: true, + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + }, + "data-driven styling": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-base": { + type: "number", + "default": 0, + minimum: 0, + units: "meters", + doc: "The height with which to extrude the base of this layer. Must be less than or equal to `fill-extrusion-height`.", + transition: true, + requires: [ + "fill-extrusion-height" + ], + "sdk-support": { + "basic functionality": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + }, + "data-driven styling": { + js: "0.27.0", + android: "5.1.0", + ios: "3.6.0", + macos: "0.5.0" + } + }, + expression: { + interpolated: true, + parameters: [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-vertical-gradient": { + type: "boolean", + "default": true, + doc: "Whether to apply a vertical gradient to the sides of a fill-extrusion layer. If true, sides will be shaded slightly darker farther down.", + transition: false, + "sdk-support": { + "basic functionality": { + js: "0.50.0", + ios: "4.7.0", + macos: "0.13.0" + } + }, + expression: { + interpolated: false, + parameters: [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }, + paint_line: paint_line, + paint_circle: paint_circle, + paint_heatmap: paint_heatmap, + paint_symbol: paint_symbol, + paint_raster: paint_raster, + paint_hillshade: paint_hillshade, + paint_background: paint_background, + transition: transition, + "property-type": { + "data-driven": { + type: "property-type", + doc: "Property is interpolable and can be represented using a property expression." + }, + "cross-faded": { + type: "property-type", + doc: "Property is non-interpolable; rather, its values will be cross-faded to smoothly transition between integer zooms." + }, + "cross-faded-data-driven": { + type: "property-type", + doc: "Property is non-interpolable; rather, its values will be cross-faded to smoothly transition between integer zooms. It can be represented using a property expression." + }, + "color-ramp": { + type: "property-type", + doc: "Property should be specified using a color ramp from which the output color can be sampled based on a property calculation." + }, + "data-constant": { + type: "property-type", + doc: "Property is interpolable but cannot be represented using a property expression." + }, + constant: { + type: "property-type", + doc: "Property is constant across all zoom levels and property values." + } + }, + promoteId: promoteId + }; + + // Note: This regex matches even invalid JSON strings, but since we’re + // working on the output of `JSON.stringify` we know that only valid strings + // are present (unless the user supplied a weird `options.indent` but in + // that case we don’t care since the output would be invalid anyway). + var stringOrChar = /("(?:[^\\"]|\\.)*")|[:,]/g; + + var jsonStringifyPrettyCompact = function stringify(passedObj, options) { + var indent, maxLength, replacer; + + options = options || {}; + indent = JSON.stringify( + [1], + undefined, + options.indent === undefined ? 2 : options.indent + ).slice(2, -3); + maxLength = + indent === "" + ? Infinity + : options.maxLength === undefined + ? 80 + : options.maxLength; + replacer = options.replacer; + + return (function _stringify(obj, currentIndent, reserved) { + // prettier-ignore + var end, index, items, key, keyPart, keys, length, nextIndent, prettified, start, string, value; + + if (obj && typeof obj.toJSON === "function") { + obj = obj.toJSON(); + } + + string = JSON.stringify(obj, replacer); + + if (string === undefined) { + return string; + } + + length = maxLength - currentIndent.length - reserved; + + if (string.length <= length) { + prettified = string.replace(stringOrChar, function(match, stringLiteral) { + return stringLiteral || match + " "; + }); + if (prettified.length <= length) { + return prettified; + } + } + + if (replacer != null) { + obj = JSON.parse(string); + replacer = undefined; + } + + if (typeof obj === "object" && obj !== null) { + nextIndent = currentIndent + indent; + items = []; + index = 0; + + if (Array.isArray(obj)) { + start = "["; + end = "]"; + length = obj.length; + for (; index < length; index++) { + items.push( + _stringify(obj[index], nextIndent, index === length - 1 ? 0 : 1) || + "null" + ); + } + } else { + start = "{"; + end = "}"; + keys = Object.keys(obj); + length = keys.length; + for (; index < length; index++) { + key = keys[index]; + keyPart = JSON.stringify(key) + ": "; + value = _stringify( + obj[key], + nextIndent, + keyPart.length + (index === length - 1 ? 0 : 1) + ); + if (value !== undefined) { + items.push(keyPart + value); + } + } + } + + if (items.length > 0) { + return [start, indent + items.join(",\n" + nextIndent), end].join( + "\n" + currentIndent + ); + } + } + + return string; + })(passedObj, "", 0); + }; + + function sortKeysBy(obj, reference) { + var result = {}; + for (var key in reference) { + if (obj[key] !== undefined) { + result[key] = obj[key]; + } + } + for (var key$1 in obj) { + if (result[key$1] === undefined) { + result[key$1] = obj[key$1]; + } + } + return result; + } + function format(style, space) { + if (space === void 0) + space = 2; + style = sortKeysBy(style, v8.$root); + if (style.layers) { + style.layers = style.layers.map(function (layer) { + return sortKeysBy(layer, v8.layer); + }); + } + return jsonStringifyPrettyCompact(style, { indent: space }); + } + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); + } + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var punycode = createCommonjsModule(function (module, exports) { + (function(root) { + + /** Detect free variables */ + var freeExports = exports && + !exports.nodeType && exports; + var freeModule = module && + !module.nodeType && module; + var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * http://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if (freeExports && freeModule) { + if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { // in Rhino or a web browser + root.punycode = punycode; + } + + }(commonjsGlobal)); + }); + + var util = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } + }; + + // Copyright Joyent, Inc. and other Node contributors. + + // If obj.hasOwnProperty has been overridden, then calling + // obj.hasOwnProperty(prop) will break. + // See: https://github.com/joyent/node/issues/1707 + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var decode = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (Array.isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; + }; + + // Copyright Joyent, Inc. and other Node contributors. + + var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } + }; + + var encode = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return Object.keys(obj).map(function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (Array.isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) { return ''; } + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); + }; + + var querystring = createCommonjsModule(function (module, exports) { + + exports.decode = exports.parse = decode; + exports.encode = exports.stringify = encode; + }); + var querystring_1 = querystring.decode; + var querystring_2 = querystring.parse; + var querystring_3 = querystring.encode; + var querystring_4 = querystring.stringify; + + var parse = urlParse; + var resolve = urlResolve; + var resolveObject = urlResolveObject; + var format$1 = urlFormat; + + var Url_1 = Url; + + function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; + } + + // Reference: RFC 3986, RFC 1808, RFC 2396 + + // define these here so at least they only have to be + // compiled once on the first module load. + var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }; + + function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) { return url; } + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; + } + + Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + { hostEnd = hec; } + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + { hostEnd = hec; } + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + { hostEnd = rest.length; } + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) { continue; } + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + { continue; } + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) { this.pathname = rest; } + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; + }; + + // format a parsed object into a url string + function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) { obj = urlParse(obj); } + if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); } + return obj.format(); + } + + Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; } + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; } + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; } + if (search && search.charAt(0) !== '?') { search = '?' + search; } + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; + }; + + function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); + } + + Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); + }; + + function urlResolveObject(source, relative) { + if (!source) { return relative; } + return urlParse(source, false, true).resolveObject(relative); + } + + Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + { result[rkey] = relative[rkey]; } + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())){ } + if (!relative.host) { relative.host = ''; } + if (!relative.hostname) { relative.hostname = ''; } + if (relPath[0] !== '') { relPath.unshift(''); } + if (relPath.length < 2) { relPath.unshift(''); } + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') { srcPath[0] = result.host; } + else { srcPath.unshift(result.host); } + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') { relPath[0] = relative.host; } + else { relPath.unshift(relative.host); } + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) { srcPath = []; } + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + }; + + Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) { this.hostname = host; } + }; + + var url = { + parse: parse, + resolve: resolve, + resolveObject: resolveObject, + format: format$1, + Url: Url_1 + }; + + function getPropertyReference(propertyName) { + for (var i = 0; i < v8.layout.length; i++) { + for (var key in v8[v8.layout[i]]) { + if (key === propertyName) { + return v8[v8.layout[i]][key]; + } + } + } + for (var i$1 = 0; i$1 < v8.paint.length; i$1++) { + for (var key$1 in v8[v8.paint[i$1]]) { + if (key$1 === propertyName) { + return v8[v8.paint[i$1]][key$1]; + } + } + } + return null; + } + function eachSource(style, callback) { + for (var k in style.sources) { + callback(style.sources[k]); + } + } + function eachLayer(style, callback) { + for (var i = 0, list = style.layers; i < list.length; i += 1) { + var layer = list[i]; + callback(layer); + } + } + function eachProperty(style, options, callback) { + function inner(layer, propertyType) { + var properties = layer[propertyType]; + if (!properties) { + return; + } + Object.keys(properties).forEach(function (key) { + callback({ + path: [ + layer.id, + propertyType, + key + ], + key: key, + value: properties[key], + reference: getPropertyReference(key), + set: function set(x) { + properties[key] = x; + } + }); + }); + } + eachLayer(style, function (layer) { + if (options.paint) { + inner(layer, 'paint'); + } + if (options.layout) { + inner(layer, 'layout'); + } + }); + } + + function eachLayout(layer, callback) { + for (var k in layer) { + if (k.indexOf('layout') === 0) { + callback(layer[k], k); + } + } + } + function eachPaint(layer, callback) { + for (var k in layer) { + if (k.indexOf('paint') === 0) { + callback(layer[k], k); + } + } + } + function resolveConstant(style, value) { + if (typeof value === 'string' && value[0] === '@') { + return resolveConstant(style, style.constants[value]); + } else { + return value; + } + } + function isFunction(value) { + return Array.isArray(value.stops); + } + function renameProperty(obj, from, to) { + obj[to] = obj[from]; + delete obj[from]; + } + function migrateToV8 (style) { + style.version = 8; + eachSource(style, function (source) { + if (source.type === 'video' && source.url !== undefined) { + renameProperty(source, 'url', 'urls'); + } + if (source.type === 'video') { + source.coordinates.forEach(function (coord) { + return coord.reverse(); + }); + } + }); + eachLayer(style, function (layer) { + eachLayout(layer, function (layout) { + if (layout['symbol-min-distance'] !== undefined) { + renameProperty(layout, 'symbol-min-distance', 'symbol-spacing'); + } + }); + eachPaint(layer, function (paint) { + if (paint['background-image'] !== undefined) { + renameProperty(paint, 'background-image', 'background-pattern'); + } + if (paint['line-image'] !== undefined) { + renameProperty(paint, 'line-image', 'line-pattern'); + } + if (paint['fill-image'] !== undefined) { + renameProperty(paint, 'fill-image', 'fill-pattern'); + } + }); + }); + eachProperty(style, { + paint: true, + layout: true + }, function (property) { + var value = resolveConstant(style, property.value); + if (isFunction(value)) { + value.stops.forEach(function (stop) { + stop[1] = resolveConstant(style, stop[1]); + }); + } + property.set(value); + }); + delete style.constants; + eachLayer(style, function (layer) { + eachLayout(layer, function (layout) { + delete layout['text-max-size']; + delete layout['icon-max-size']; + }); + eachPaint(layer, function (paint) { + if (paint['text-size']) { + if (!layer.layout) { + layer.layout = {}; + } + layer.layout['text-size'] = paint['text-size']; + delete paint['text-size']; + } + if (paint['icon-size']) { + if (!layer.layout) { + layer.layout = {}; + } + layer.layout['icon-size'] = paint['icon-size']; + delete paint['icon-size']; + } + }); + }); + function migrateFontstackURL(input) { + var inputParsed = url.parse(input); + var inputPathnameParts = inputParsed.pathname.split('/'); + if (inputParsed.protocol !== 'mapbox:') { + return input; + } else if (inputParsed.hostname === 'fontstack') { + return 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf'; + } else if (inputParsed.hostname === 'fonts') { + return 'mapbox://fonts/' + inputPathnameParts[2] + '/{fontstack}/{range}.pbf'; + } + } + if (style.glyphs) { + style.glyphs = migrateFontstackURL(style.glyphs); + } + function migrateFontStack(font) { + function splitAndTrim(string) { + return string.split(',').map(function (s) { + return s.trim(); + }); + } + if (Array.isArray(font)) { + return font; + } else if (typeof font === 'string') { + return splitAndTrim(font); + } else if (typeof font === 'object') { + font.stops.forEach(function (stop) { + stop[1] = splitAndTrim(stop[1]); + }); + return font; + } else { + throw new Error('unexpected font value'); + } + } + eachLayer(style, function (layer) { + eachLayout(layer, function (layout) { + if (layout['text-font']) { + layout['text-font'] = migrateFontStack(layout['text-font']); + } + }); + }); + var firstSymbolLayer = 0; + for (var i = style.layers.length - 1; i >= 0; i--) { + var layer = style.layers[i]; + if (layer.type !== 'symbol') { + firstSymbolLayer = i + 1; + break; + } + } + var symbolLayers = style.layers.splice(firstSymbolLayer); + symbolLayers.reverse(); + style.layers = style.layers.concat(symbolLayers); + return style; + } + + function extend (output) { + var inputs = [], len = arguments.length - 1; + while (len-- > 0) + inputs[len] = arguments[len + 1]; + for (var i = 0, list = inputs; i < list.length; i += 1) { + var input = list[i]; + for (var k in input) { + output[k] = input[k]; + } + } + return output; + } + + var ParsingError = function (Error) { + function ParsingError(key, message) { + Error.call(this, message); + this.message = message; + this.key = key; + } + if (Error) + ParsingError.__proto__ = Error; + ParsingError.prototype = Object.create(Error && Error.prototype); + ParsingError.prototype.constructor = ParsingError; + return ParsingError; + }(Error); + + var Scope = function Scope(parent, bindings) { + if (bindings === void 0) + bindings = []; + this.parent = parent; + this.bindings = {}; + for (var i = 0, list = bindings; i < list.length; i += 1) { + var ref = list[i]; + var name = ref[0]; + var expression = ref[1]; + this.bindings[name] = expression; + } + }; + Scope.prototype.concat = function concat(bindings) { + return new Scope(this, bindings); + }; + Scope.prototype.get = function get(name) { + if (this.bindings[name]) { + return this.bindings[name]; + } + if (this.parent) { + return this.parent.get(name); + } + throw new Error(name + ' not found in scope.'); + }; + Scope.prototype.has = function has(name) { + if (this.bindings[name]) { + return true; + } + return this.parent ? this.parent.has(name) : false; + }; + + var NullType = { kind: 'null' }; + var NumberType = { kind: 'number' }; + var StringType = { kind: 'string' }; + var BooleanType = { kind: 'boolean' }; + var ColorType = { kind: 'color' }; + var ObjectType = { kind: 'object' }; + var ValueType = { kind: 'value' }; + var ErrorType = { kind: 'error' }; + var CollatorType = { kind: 'collator' }; + var FormattedType = { kind: 'formatted' }; + var ResolvedImageType = { kind: 'resolvedImage' }; + function array(itemType, N) { + return { + kind: 'array', + itemType: itemType, + N: N + }; + } + function toString(type) { + if (type.kind === 'array') { + var itemType = toString(type.itemType); + return typeof type.N === 'number' ? 'array<' + itemType + ', ' + type.N + '>' : type.itemType.kind === 'value' ? 'array' : 'array<' + itemType + '>'; + } else { + return type.kind; + } + } + var valueMemberTypes = [ + NullType, + NumberType, + StringType, + BooleanType, + ColorType, + FormattedType, + ObjectType, + array(ValueType), + ResolvedImageType + ]; + function checkSubtype(expected, t) { + if (t.kind === 'error') { + return null; + } else if (expected.kind === 'array') { + if (t.kind === 'array' && (t.N === 0 && t.itemType.kind === 'value' || !checkSubtype(expected.itemType, t.itemType)) && (typeof expected.N !== 'number' || expected.N === t.N)) { + return null; + } + } else if (expected.kind === t.kind) { + return null; + } else if (expected.kind === 'value') { + for (var i = 0, list = valueMemberTypes; i < list.length; i += 1) { + var memberType = list[i]; + if (!checkSubtype(memberType, t)) { + return null; + } + } + } + return 'Expected ' + toString(expected) + ' but found ' + toString(t) + ' instead.'; + } + function isValidType(provided, allowedTypes) { + return allowedTypes.some(function (t) { + return t.kind === provided.kind; + }); + } + function isValidNativeType(provided, allowedTypes) { + return allowedTypes.some(function (t) { + if (t === 'null') { + return provided === null; + } else if (t === 'array') { + return Array.isArray(provided); + } else if (t === 'object') { + return provided && !Array.isArray(provided) && typeof provided === 'object'; + } else { + return t === typeof provided; + } + }); + } + + var csscolorparser = createCommonjsModule(function (module, exports) { + // (c) Dean McNamee , 2012. + // + // https://github.com/deanm/css-color-parser-js + // + // Permission is hereby granted, free of charge, to any person obtaining a copy + // of this software and associated documentation files (the "Software"), to + // deal in the Software without restriction, including without limitation the + // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + // sell copies of the Software, and to permit persons to whom the Software is + // furnished to do so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in + // all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + // IN THE SOFTWARE. + + // http://www.w3.org/TR/css3-color/ + var kCSSColorTable = { + "transparent": [0,0,0,0], "aliceblue": [240,248,255,1], + "antiquewhite": [250,235,215,1], "aqua": [0,255,255,1], + "aquamarine": [127,255,212,1], "azure": [240,255,255,1], + "beige": [245,245,220,1], "bisque": [255,228,196,1], + "black": [0,0,0,1], "blanchedalmond": [255,235,205,1], + "blue": [0,0,255,1], "blueviolet": [138,43,226,1], + "brown": [165,42,42,1], "burlywood": [222,184,135,1], + "cadetblue": [95,158,160,1], "chartreuse": [127,255,0,1], + "chocolate": [210,105,30,1], "coral": [255,127,80,1], + "cornflowerblue": [100,149,237,1], "cornsilk": [255,248,220,1], + "crimson": [220,20,60,1], "cyan": [0,255,255,1], + "darkblue": [0,0,139,1], "darkcyan": [0,139,139,1], + "darkgoldenrod": [184,134,11,1], "darkgray": [169,169,169,1], + "darkgreen": [0,100,0,1], "darkgrey": [169,169,169,1], + "darkkhaki": [189,183,107,1], "darkmagenta": [139,0,139,1], + "darkolivegreen": [85,107,47,1], "darkorange": [255,140,0,1], + "darkorchid": [153,50,204,1], "darkred": [139,0,0,1], + "darksalmon": [233,150,122,1], "darkseagreen": [143,188,143,1], + "darkslateblue": [72,61,139,1], "darkslategray": [47,79,79,1], + "darkslategrey": [47,79,79,1], "darkturquoise": [0,206,209,1], + "darkviolet": [148,0,211,1], "deeppink": [255,20,147,1], + "deepskyblue": [0,191,255,1], "dimgray": [105,105,105,1], + "dimgrey": [105,105,105,1], "dodgerblue": [30,144,255,1], + "firebrick": [178,34,34,1], "floralwhite": [255,250,240,1], + "forestgreen": [34,139,34,1], "fuchsia": [255,0,255,1], + "gainsboro": [220,220,220,1], "ghostwhite": [248,248,255,1], + "gold": [255,215,0,1], "goldenrod": [218,165,32,1], + "gray": [128,128,128,1], "green": [0,128,0,1], + "greenyellow": [173,255,47,1], "grey": [128,128,128,1], + "honeydew": [240,255,240,1], "hotpink": [255,105,180,1], + "indianred": [205,92,92,1], "indigo": [75,0,130,1], + "ivory": [255,255,240,1], "khaki": [240,230,140,1], + "lavender": [230,230,250,1], "lavenderblush": [255,240,245,1], + "lawngreen": [124,252,0,1], "lemonchiffon": [255,250,205,1], + "lightblue": [173,216,230,1], "lightcoral": [240,128,128,1], + "lightcyan": [224,255,255,1], "lightgoldenrodyellow": [250,250,210,1], + "lightgray": [211,211,211,1], "lightgreen": [144,238,144,1], + "lightgrey": [211,211,211,1], "lightpink": [255,182,193,1], + "lightsalmon": [255,160,122,1], "lightseagreen": [32,178,170,1], + "lightskyblue": [135,206,250,1], "lightslategray": [119,136,153,1], + "lightslategrey": [119,136,153,1], "lightsteelblue": [176,196,222,1], + "lightyellow": [255,255,224,1], "lime": [0,255,0,1], + "limegreen": [50,205,50,1], "linen": [250,240,230,1], + "magenta": [255,0,255,1], "maroon": [128,0,0,1], + "mediumaquamarine": [102,205,170,1], "mediumblue": [0,0,205,1], + "mediumorchid": [186,85,211,1], "mediumpurple": [147,112,219,1], + "mediumseagreen": [60,179,113,1], "mediumslateblue": [123,104,238,1], + "mediumspringgreen": [0,250,154,1], "mediumturquoise": [72,209,204,1], + "mediumvioletred": [199,21,133,1], "midnightblue": [25,25,112,1], + "mintcream": [245,255,250,1], "mistyrose": [255,228,225,1], + "moccasin": [255,228,181,1], "navajowhite": [255,222,173,1], + "navy": [0,0,128,1], "oldlace": [253,245,230,1], + "olive": [128,128,0,1], "olivedrab": [107,142,35,1], + "orange": [255,165,0,1], "orangered": [255,69,0,1], + "orchid": [218,112,214,1], "palegoldenrod": [238,232,170,1], + "palegreen": [152,251,152,1], "paleturquoise": [175,238,238,1], + "palevioletred": [219,112,147,1], "papayawhip": [255,239,213,1], + "peachpuff": [255,218,185,1], "peru": [205,133,63,1], + "pink": [255,192,203,1], "plum": [221,160,221,1], + "powderblue": [176,224,230,1], "purple": [128,0,128,1], + "rebeccapurple": [102,51,153,1], + "red": [255,0,0,1], "rosybrown": [188,143,143,1], + "royalblue": [65,105,225,1], "saddlebrown": [139,69,19,1], + "salmon": [250,128,114,1], "sandybrown": [244,164,96,1], + "seagreen": [46,139,87,1], "seashell": [255,245,238,1], + "sienna": [160,82,45,1], "silver": [192,192,192,1], + "skyblue": [135,206,235,1], "slateblue": [106,90,205,1], + "slategray": [112,128,144,1], "slategrey": [112,128,144,1], + "snow": [255,250,250,1], "springgreen": [0,255,127,1], + "steelblue": [70,130,180,1], "tan": [210,180,140,1], + "teal": [0,128,128,1], "thistle": [216,191,216,1], + "tomato": [255,99,71,1], "turquoise": [64,224,208,1], + "violet": [238,130,238,1], "wheat": [245,222,179,1], + "white": [255,255,255,1], "whitesmoke": [245,245,245,1], + "yellow": [255,255,0,1], "yellowgreen": [154,205,50,1]}; + + function clamp_css_byte(i) { // Clamp to integer 0 .. 255. + i = Math.round(i); // Seems to be what Chrome does (vs truncation). + return i < 0 ? 0 : i > 255 ? 255 : i; + } + + function clamp_css_float(f) { // Clamp to float 0.0 .. 1.0. + return f < 0 ? 0 : f > 1 ? 1 : f; + } + + function parse_css_int(str) { // int or percentage. + if (str[str.length - 1] === '%') + { return clamp_css_byte(parseFloat(str) / 100 * 255); } + return clamp_css_byte(parseInt(str)); + } + + function parse_css_float(str) { // float or percentage. + if (str[str.length - 1] === '%') + { return clamp_css_float(parseFloat(str) / 100); } + return clamp_css_float(parseFloat(str)); + } + + function css_hue_to_rgb(m1, m2, h) { + if (h < 0) { h += 1; } + else if (h > 1) { h -= 1; } + + if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; } + if (h * 2 < 1) { return m2; } + if (h * 3 < 2) { return m1 + (m2 - m1) * (2/3 - h) * 6; } + return m1; + } + + function parseCSSColor(css_str) { + // Remove all whitespace, not compliant, but should just be more accepting. + var str = css_str.replace(/ /g, '').toLowerCase(); + + // Color keywords (and transparent) lookup. + if (str in kCSSColorTable) { return kCSSColorTable[str].slice(); } // dup. + + // #abc and #abc123 syntax. + if (str[0] === '#') { + if (str.length === 4) { + var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. + if (!(iv >= 0 && iv <= 0xfff)) { return null; } // Covers NaN. + return [((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8), + (iv & 0xf0) | ((iv & 0xf0) >> 4), + (iv & 0xf) | ((iv & 0xf) << 4), + 1]; + } else if (str.length === 7) { + var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. + if (!(iv >= 0 && iv <= 0xffffff)) { return null; } // Covers NaN. + return [(iv & 0xff0000) >> 16, + (iv & 0xff00) >> 8, + iv & 0xff, + 1]; + } + + return null; + } + + var op = str.indexOf('('), ep = str.indexOf(')'); + if (op !== -1 && ep + 1 === str.length) { + var fname = str.substr(0, op); + var params = str.substr(op+1, ep-(op+1)).split(','); + var alpha = 1; // To allow case fallthrough. + switch (fname) { + case 'rgba': + if (params.length !== 4) { return null; } + alpha = parse_css_float(params.pop()); + // Fall through. + case 'rgb': + if (params.length !== 3) { return null; } + return [parse_css_int(params[0]), + parse_css_int(params[1]), + parse_css_int(params[2]), + alpha]; + case 'hsla': + if (params.length !== 4) { return null; } + alpha = parse_css_float(params.pop()); + // Fall through. + case 'hsl': + if (params.length !== 3) { return null; } + var h = (((parseFloat(params[0]) % 360) + 360) % 360) / 360; // 0 .. 1 + // NOTE(deanm): According to the CSS spec s/l should only be + // percentages, but we don't bother and let float or percentage. + var s = parse_css_float(params[1]); + var l = parse_css_float(params[2]); + var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; + var m1 = l * 2 - m2; + return [clamp_css_byte(css_hue_to_rgb(m1, m2, h+1/3) * 255), + clamp_css_byte(css_hue_to_rgb(m1, m2, h) * 255), + clamp_css_byte(css_hue_to_rgb(m1, m2, h-1/3) * 255), + alpha]; + default: + return null; + } + } + + return null; + } + + try { exports.parseCSSColor = parseCSSColor; } catch(e) { } + }); + var csscolorparser_1 = csscolorparser.parseCSSColor; + + var Color = function Color(r, g, b, a) { + if (a === void 0) + a = 1; + this.r = r; + this.g = g; + this.b = b; + this.a = a; + }; + Color.parse = function parse(input) { + if (!input) { + return undefined; + } + if (input instanceof Color) { + return input; + } + if (typeof input !== 'string') { + return undefined; + } + var rgba = csscolorparser_1(input); + if (!rgba) { + return undefined; + } + return new Color(rgba[0] / 255 * rgba[3], rgba[1] / 255 * rgba[3], rgba[2] / 255 * rgba[3], rgba[3]); + }; + Color.prototype.toString = function toString() { + var ref = this.toArray(); + var r = ref[0]; + var g = ref[1]; + var b = ref[2]; + var a = ref[3]; + return 'rgba(' + Math.round(r) + ',' + Math.round(g) + ',' + Math.round(b) + ',' + a + ')'; + }; + Color.prototype.toArray = function toArray() { + var ref = this; + var r = ref.r; + var g = ref.g; + var b = ref.b; + var a = ref.a; + return a === 0 ? [ + 0, + 0, + 0, + 0 + ] : [ + r * 255 / a, + g * 255 / a, + b * 255 / a, + a + ]; + }; + Color.black = new Color(0, 0, 0, 1); + Color.white = new Color(1, 1, 1, 1); + Color.transparent = new Color(0, 0, 0, 0); + Color.red = new Color(1, 0, 0, 1); + + var Collator = function Collator(caseSensitive, diacriticSensitive, locale) { + if (caseSensitive) { + this.sensitivity = diacriticSensitive ? 'variant' : 'case'; + } else { + this.sensitivity = diacriticSensitive ? 'accent' : 'base'; + } + this.locale = locale; + this.collator = new Intl.Collator(this.locale ? this.locale : [], { + sensitivity: this.sensitivity, + usage: 'search' + }); + }; + Collator.prototype.compare = function compare(lhs, rhs) { + return this.collator.compare(lhs, rhs); + }; + Collator.prototype.resolvedLocale = function resolvedLocale() { + return new Intl.Collator(this.locale ? this.locale : []).resolvedOptions().locale; + }; + + var FormattedSection = function FormattedSection(text, image, scale, fontStack, textColor) { + this.text = text; + this.image = image; + this.scale = scale; + this.fontStack = fontStack; + this.textColor = textColor; + }; + var Formatted = function Formatted(sections) { + this.sections = sections; + }; + Formatted.fromString = function fromString(unformatted) { + return new Formatted([new FormattedSection(unformatted, null, null, null, null)]); + }; + Formatted.prototype.isEmpty = function isEmpty() { + if (this.sections.length === 0) { + return true; + } + return !this.sections.some(function (section) { + return section.text.length !== 0 || section.image && section.image.name.length !== 0; + }); + }; + Formatted.factory = function factory(text) { + if (text instanceof Formatted) { + return text; + } else { + return Formatted.fromString(text); + } + }; + Formatted.prototype.toString = function toString() { + if (this.sections.length === 0) { + return ''; + } + return this.sections.map(function (section) { + return section.text; + }).join(''); + }; + Formatted.prototype.serialize = function serialize() { + var serialized = ['format']; + for (var i = 0, list = this.sections; i < list.length; i += 1) { + var section = list[i]; + if (section.image) { + serialized.push([ + 'image', + section.image.name + ]); + continue; + } + serialized.push(section.text); + var options = {}; + if (section.fontStack) { + options['text-font'] = [ + 'literal', + section.fontStack.split(',') + ]; + } + if (section.scale) { + options['font-scale'] = section.scale; + } + if (section.textColor) { + options['text-color'] = ['rgba'].concat(section.textColor.toArray()); + } + serialized.push(options); + } + return serialized; + }; + + var ResolvedImage = function ResolvedImage(options) { + this.name = options.name; + this.available = options.available; + }; + ResolvedImage.prototype.toString = function toString() { + return this.name; + }; + ResolvedImage.fromString = function fromString(name) { + if (!name) { + return null; + } + return new ResolvedImage({ + name: name, + available: false + }); + }; + ResolvedImage.prototype.serialize = function serialize() { + return [ + 'image', + this.name + ]; + }; + + function validateRGBA(r, g, b, a) { + if (!(typeof r === 'number' && r >= 0 && r <= 255 && typeof g === 'number' && g >= 0 && g <= 255 && typeof b === 'number' && b >= 0 && b <= 255)) { + var value = typeof a === 'number' ? [ + r, + g, + b, + a + ] : [ + r, + g, + b + ]; + return 'Invalid rgba value [' + value.join(', ') + ']: \'r\', \'g\', and \'b\' must be between 0 and 255.'; + } + if (!(typeof a === 'undefined' || typeof a === 'number' && a >= 0 && a <= 1)) { + return 'Invalid rgba value [' + [ + r, + g, + b, + a + ].join(', ') + ']: \'a\' must be between 0 and 1.'; + } + return null; + } + function isValue(mixed) { + if (mixed === null) { + return true; + } else if (typeof mixed === 'string') { + return true; + } else if (typeof mixed === 'boolean') { + return true; + } else if (typeof mixed === 'number') { + return true; + } else if (mixed instanceof Color) { + return true; + } else if (mixed instanceof Collator) { + return true; + } else if (mixed instanceof Formatted) { + return true; + } else if (mixed instanceof ResolvedImage) { + return true; + } else if (Array.isArray(mixed)) { + for (var i = 0, list = mixed; i < list.length; i += 1) { + var item = list[i]; + if (!isValue(item)) { + return false; + } + } + return true; + } else if (typeof mixed === 'object') { + for (var key in mixed) { + if (!isValue(mixed[key])) { + return false; + } + } + return true; + } else { + return false; + } + } + function typeOf(value) { + if (value === null) { + return NullType; + } else if (typeof value === 'string') { + return StringType; + } else if (typeof value === 'boolean') { + return BooleanType; + } else if (typeof value === 'number') { + return NumberType; + } else if (value instanceof Color) { + return ColorType; + } else if (value instanceof Collator) { + return CollatorType; + } else if (value instanceof Formatted) { + return FormattedType; + } else if (value instanceof ResolvedImage) { + return ResolvedImageType; + } else if (Array.isArray(value)) { + var length = value.length; + var itemType; + for (var i = 0, list = value; i < list.length; i += 1) { + var item = list[i]; + var t = typeOf(item); + if (!itemType) { + itemType = t; + } else if (itemType === t) { + continue; + } else { + itemType = ValueType; + break; + } + } + return array(itemType || ValueType, length); + } else { + return ObjectType; + } + } + function toString$1(value) { + var type = typeof value; + if (value === null) { + return ''; + } else if (type === 'string' || type === 'number' || type === 'boolean') { + return String(value); + } else if (value instanceof Color || value instanceof Formatted || value instanceof ResolvedImage) { + return value.toString(); + } else { + return JSON.stringify(value); + } + } + + var Literal = function Literal(type, value) { + this.type = type; + this.value = value; + }; + Literal.parse = function parse(args, context) { + if (args.length !== 2) { + return context.error('\'literal\' expression requires exactly one argument, but found ' + (args.length - 1) + ' instead.'); + } + if (!isValue(args[1])) { + return context.error('invalid value'); + } + var value = args[1]; + var type = typeOf(value); + var expected = context.expectedType; + if (type.kind === 'array' && type.N === 0 && expected && expected.kind === 'array' && (typeof expected.N !== 'number' || expected.N === 0)) { + type = expected; + } + return new Literal(type, value); + }; + Literal.prototype.evaluate = function evaluate() { + return this.value; + }; + Literal.prototype.eachChild = function eachChild() { + }; + Literal.prototype.outputDefined = function outputDefined() { + return true; + }; + Literal.prototype.serialize = function serialize() { + if (this.type.kind === 'array' || this.type.kind === 'object') { + return [ + 'literal', + this.value + ]; + } else if (this.value instanceof Color) { + return ['rgba'].concat(this.value.toArray()); + } else if (this.value instanceof Formatted) { + return this.value.serialize(); + } else { + return this.value; + } + }; + + var RuntimeError = function RuntimeError(message) { + this.name = 'ExpressionEvaluationError'; + this.message = message; + }; + RuntimeError.prototype.toJSON = function toJSON() { + return this.message; + }; + + var types = { + string: StringType, + number: NumberType, + boolean: BooleanType, + object: ObjectType + }; + var Assertion = function Assertion(type, args) { + this.type = type; + this.args = args; + }; + Assertion.parse = function parse(args, context) { + if (args.length < 2) { + return context.error('Expected at least one argument.'); + } + var i = 1; + var type; + var name = args[0]; + if (name === 'array') { + var itemType; + if (args.length > 2) { + var type$1 = args[1]; + if (typeof type$1 !== 'string' || !(type$1 in types) || type$1 === 'object') { + return context.error('The item type argument of "array" must be one of string, number, boolean', 1); + } + itemType = types[type$1]; + i++; + } else { + itemType = ValueType; + } + var N; + if (args.length > 3) { + if (args[2] !== null && (typeof args[2] !== 'number' || args[2] < 0 || args[2] !== Math.floor(args[2]))) { + return context.error('The length argument to "array" must be a positive integer literal', 2); + } + N = args[2]; + i++; + } + type = array(itemType, N); + } else { + type = types[name]; + } + var parsed = []; + for (; i < args.length; i++) { + var input = context.parse(args[i], i, ValueType); + if (!input) { + return null; + } + parsed.push(input); + } + return new Assertion(type, parsed); + }; + Assertion.prototype.evaluate = function evaluate(ctx) { + for (var i = 0; i < this.args.length; i++) { + var value = this.args[i].evaluate(ctx); + var error = checkSubtype(this.type, typeOf(value)); + if (!error) { + return value; + } else if (i === this.args.length - 1) { + throw new RuntimeError('Expected value to be of type ' + toString(this.type) + ', but found ' + toString(typeOf(value)) + ' instead.'); + } + } + return null; + }; + Assertion.prototype.eachChild = function eachChild(fn) { + this.args.forEach(fn); + }; + Assertion.prototype.outputDefined = function outputDefined() { + return this.args.every(function (arg) { + return arg.outputDefined(); + }); + }; + Assertion.prototype.serialize = function serialize() { + var type = this.type; + var serialized = [type.kind]; + if (type.kind === 'array') { + var itemType = type.itemType; + if (itemType.kind === 'string' || itemType.kind === 'number' || itemType.kind === 'boolean') { + serialized.push(itemType.kind); + var N = type.N; + if (typeof N === 'number' || this.args.length > 1) { + serialized.push(N); + } + } + } + return serialized.concat(this.args.map(function (arg) { + return arg.serialize(); + })); + }; + + var FormatExpression = function FormatExpression(sections) { + this.type = FormattedType; + this.sections = sections; + }; + FormatExpression.parse = function parse(args, context) { + if (args.length < 2) { + return context.error('Expected at least one argument.'); + } + var firstArg = args[1]; + if (!Array.isArray(firstArg) && typeof firstArg === 'object') { + return context.error('First argument must be an image or text section.'); + } + var sections = []; + var nextTokenMayBeObject = false; + for (var i = 1; i <= args.length - 1; ++i) { + var arg = args[i]; + if (nextTokenMayBeObject && typeof arg === 'object' && !Array.isArray(arg)) { + nextTokenMayBeObject = false; + var scale = null; + if (arg['font-scale']) { + scale = context.parse(arg['font-scale'], 1, NumberType); + if (!scale) { + return null; + } + } + var font = null; + if (arg['text-font']) { + font = context.parse(arg['text-font'], 1, array(StringType)); + if (!font) { + return null; + } + } + var textColor = null; + if (arg['text-color']) { + textColor = context.parse(arg['text-color'], 1, ColorType); + if (!textColor) { + return null; + } + } + var lastExpression = sections[sections.length - 1]; + lastExpression.scale = scale; + lastExpression.font = font; + lastExpression.textColor = textColor; + } else { + var content = context.parse(args[i], 1, ValueType); + if (!content) { + return null; + } + var kind = content.type.kind; + if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage') { + return context.error('Formatted text type must be \'string\', \'value\', \'image\' or \'null\'.'); + } + nextTokenMayBeObject = true; + sections.push({ + content: content, + scale: null, + font: null, + textColor: null + }); + } + } + return new FormatExpression(sections); + }; + FormatExpression.prototype.evaluate = function evaluate(ctx) { + var evaluateSection = function (section) { + var evaluatedContent = section.content.evaluate(ctx); + if (typeOf(evaluatedContent) === ResolvedImageType) { + return new FormattedSection('', evaluatedContent, null, null, null); + } + return new FormattedSection(toString$1(evaluatedContent), null, section.scale ? section.scale.evaluate(ctx) : null, section.font ? section.font.evaluate(ctx).join(',') : null, section.textColor ? section.textColor.evaluate(ctx) : null); + }; + return new Formatted(this.sections.map(evaluateSection)); + }; + FormatExpression.prototype.eachChild = function eachChild(fn) { + for (var i = 0, list = this.sections; i < list.length; i += 1) { + var section = list[i]; + fn(section.content); + if (section.scale) { + fn(section.scale); + } + if (section.font) { + fn(section.font); + } + if (section.textColor) { + fn(section.textColor); + } + } + }; + FormatExpression.prototype.outputDefined = function outputDefined() { + return false; + }; + FormatExpression.prototype.serialize = function serialize() { + var serialized = ['format']; + for (var i = 0, list = this.sections; i < list.length; i += 1) { + var section = list[i]; + serialized.push(section.content.serialize()); + var options = {}; + if (section.scale) { + options['font-scale'] = section.scale.serialize(); + } + if (section.font) { + options['text-font'] = section.font.serialize(); + } + if (section.textColor) { + options['text-color'] = section.textColor.serialize(); + } + serialized.push(options); + } + return serialized; + }; + + var ImageExpression = function ImageExpression(input) { + this.type = ResolvedImageType; + this.input = input; + }; + ImageExpression.parse = function parse(args, context) { + if (args.length !== 2) { + return context.error('Expected two arguments.'); + } + var name = context.parse(args[1], 1, StringType); + if (!name) { + return context.error('No image name provided.'); + } + return new ImageExpression(name); + }; + ImageExpression.prototype.evaluate = function evaluate(ctx) { + var evaluatedImageName = this.input.evaluate(ctx); + var value = ResolvedImage.fromString(evaluatedImageName); + if (value && ctx.availableImages) { + value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1; + } + return value; + }; + ImageExpression.prototype.eachChild = function eachChild(fn) { + fn(this.input); + }; + ImageExpression.prototype.outputDefined = function outputDefined() { + return false; + }; + ImageExpression.prototype.serialize = function serialize() { + return [ + 'image', + this.input.serialize() + ]; + }; + + var types$1 = { + 'to-boolean': BooleanType, + 'to-color': ColorType, + 'to-number': NumberType, + 'to-string': StringType + }; + var Coercion = function Coercion(type, args) { + this.type = type; + this.args = args; + }; + Coercion.parse = function parse(args, context) { + if (args.length < 2) { + return context.error('Expected at least one argument.'); + } + var name = args[0]; + if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2) { + return context.error('Expected one argument.'); + } + var type = types$1[name]; + var parsed = []; + for (var i = 1; i < args.length; i++) { + var input = context.parse(args[i], i, ValueType); + if (!input) { + return null; + } + parsed.push(input); + } + return new Coercion(type, parsed); + }; + Coercion.prototype.evaluate = function evaluate(ctx) { + if (this.type.kind === 'boolean') { + return Boolean(this.args[0].evaluate(ctx)); + } else if (this.type.kind === 'color') { + var input; + var error; + for (var i = 0, list = this.args; i < list.length; i += 1) { + var arg = list[i]; + input = arg.evaluate(ctx); + error = null; + if (input instanceof Color) { + return input; + } else if (typeof input === 'string') { + var c = ctx.parseColor(input); + if (c) { + return c; + } + } else if (Array.isArray(input)) { + if (input.length < 3 || input.length > 4) { + error = 'Invalid rbga value ' + JSON.stringify(input) + ': expected an array containing either three or four numeric values.'; + } else { + error = validateRGBA(input[0], input[1], input[2], input[3]); + } + if (!error) { + return new Color(input[0] / 255, input[1] / 255, input[2] / 255, input[3]); + } + } + } + throw new RuntimeError(error || 'Could not parse color from value \'' + (typeof input === 'string' ? input : String(JSON.stringify(input))) + '\''); + } else if (this.type.kind === 'number') { + var value = null; + for (var i$1 = 0, list$1 = this.args; i$1 < list$1.length; i$1 += 1) { + var arg$1 = list$1[i$1]; + value = arg$1.evaluate(ctx); + if (value === null) { + return 0; + } + var num = Number(value); + if (isNaN(num)) { + continue; + } + return num; + } + throw new RuntimeError('Could not convert ' + JSON.stringify(value) + ' to number.'); + } else if (this.type.kind === 'formatted') { + return Formatted.fromString(toString$1(this.args[0].evaluate(ctx))); + } else if (this.type.kind === 'resolvedImage') { + return ResolvedImage.fromString(toString$1(this.args[0].evaluate(ctx))); + } else { + return toString$1(this.args[0].evaluate(ctx)); + } + }; + Coercion.prototype.eachChild = function eachChild(fn) { + this.args.forEach(fn); + }; + Coercion.prototype.outputDefined = function outputDefined() { + return this.args.every(function (arg) { + return arg.outputDefined(); + }); + }; + Coercion.prototype.serialize = function serialize() { + if (this.type.kind === 'formatted') { + return new FormatExpression([{ + content: this.args[0], + scale: null, + font: null, + textColor: null + }]).serialize(); + } + if (this.type.kind === 'resolvedImage') { + return new ImageExpression(this.args[0]).serialize(); + } + var serialized = ['to-' + this.type.kind]; + this.eachChild(function (child) { + serialized.push(child.serialize()); + }); + return serialized; + }; + + var geometryTypes = [ + 'Unknown', + 'Point', + 'LineString', + 'Polygon' + ]; + var EvaluationContext = function EvaluationContext() { + this.globals = null; + this.feature = null; + this.featureState = null; + this.formattedSection = null; + this._parseColorCache = {}; + this.availableImages = null; + this.canonical = null; + }; + EvaluationContext.prototype.id = function id() { + return this.feature && 'id' in this.feature ? this.feature.id : null; + }; + EvaluationContext.prototype.geometryType = function geometryType() { + return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null; + }; + EvaluationContext.prototype.geometry = function geometry() { + return this.feature && 'geometry' in this.feature ? this.feature.geometry : null; + }; + EvaluationContext.prototype.canonicalID = function canonicalID() { + return this.canonical; + }; + EvaluationContext.prototype.properties = function properties() { + return this.feature && this.feature.properties || {}; + }; + EvaluationContext.prototype.parseColor = function parseColor(input) { + var cached = this._parseColorCache[input]; + if (!cached) { + cached = this._parseColorCache[input] = Color.parse(input); + } + return cached; + }; + + var CompoundExpression = function CompoundExpression(name, type, evaluate, args) { + this.name = name; + this.type = type; + this._evaluate = evaluate; + this.args = args; + }; + CompoundExpression.prototype.evaluate = function evaluate(ctx) { + return this._evaluate(ctx, this.args); + }; + CompoundExpression.prototype.eachChild = function eachChild(fn) { + this.args.forEach(fn); + }; + CompoundExpression.prototype.outputDefined = function outputDefined() { + return false; + }; + CompoundExpression.prototype.serialize = function serialize() { + return [this.name].concat(this.args.map(function (arg) { + return arg.serialize(); + })); + }; + CompoundExpression.parse = function parse(args, context) { + var ref$1; + var op = args[0]; + var definition = CompoundExpression.definitions[op]; + if (!definition) { + return context.error('Unknown expression "' + op + '". If you wanted a literal array, use ["literal", [...]].', 0); + } + var type = Array.isArray(definition) ? definition[0] : definition.type; + var availableOverloads = Array.isArray(definition) ? [[ + definition[1], + definition[2] + ]] : definition.overloads; + var overloads = availableOverloads.filter(function (ref) { + var signature = ref[0]; + return !Array.isArray(signature) || signature.length === args.length - 1; + }); + var signatureContext = null; + for (var i$3 = 0, list = overloads; i$3 < list.length; i$3 += 1) { + var ref = list[i$3]; + var params = ref[0]; + var evaluate = ref[1]; + signatureContext = new ParsingContext(context.registry, context.path, null, context.scope); + var parsedArgs = []; + var argParseFailed = false; + for (var i = 1; i < args.length; i++) { + var arg = args[i]; + var expectedType = Array.isArray(params) ? params[i - 1] : params.type; + var parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType); + if (!parsed) { + argParseFailed = true; + break; + } + parsedArgs.push(parsed); + } + if (argParseFailed) { + continue; + } + if (Array.isArray(params)) { + if (params.length !== parsedArgs.length) { + signatureContext.error('Expected ' + params.length + ' arguments, but found ' + parsedArgs.length + ' instead.'); + continue; + } + } + for (var i$1 = 0; i$1 < parsedArgs.length; i$1++) { + var expected = Array.isArray(params) ? params[i$1] : params.type; + var arg$1 = parsedArgs[i$1]; + signatureContext.concat(i$1 + 1).checkSubtype(expected, arg$1.type); + } + if (signatureContext.errors.length === 0) { + return new CompoundExpression(op, type, evaluate, parsedArgs); + } + } + if (overloads.length === 1) { + (ref$1 = context.errors).push.apply(ref$1, signatureContext.errors); + } else { + var expected$1 = overloads.length ? overloads : availableOverloads; + var signatures = expected$1.map(function (ref) { + var params = ref[0]; + return stringifySignature(params); + }).join(' | '); + var actualTypes = []; + for (var i$2 = 1; i$2 < args.length; i$2++) { + var parsed$1 = context.parse(args[i$2], 1 + actualTypes.length); + if (!parsed$1) { + return null; + } + actualTypes.push(toString(parsed$1.type)); + } + context.error('Expected arguments of type ' + signatures + ', but found (' + actualTypes.join(', ') + ') instead.'); + } + return null; + }; + CompoundExpression.register = function register(registry, definitions) { + CompoundExpression.definitions = definitions; + for (var name in definitions) { + registry[name] = CompoundExpression; + } + }; + function stringifySignature(signature) { + if (Array.isArray(signature)) { + return '(' + signature.map(toString).join(', ') + ')'; + } else { + return '(' + toString(signature.type) + '...)'; + } + } + + var CollatorExpression = function CollatorExpression(caseSensitive, diacriticSensitive, locale) { + this.type = CollatorType; + this.locale = locale; + this.caseSensitive = caseSensitive; + this.diacriticSensitive = diacriticSensitive; + }; + CollatorExpression.parse = function parse(args, context) { + if (args.length !== 2) { + return context.error('Expected one argument.'); + } + var options = args[1]; + if (typeof options !== 'object' || Array.isArray(options)) { + return context.error('Collator options argument must be an object.'); + } + var caseSensitive = context.parse(options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType); + if (!caseSensitive) { + return null; + } + var diacriticSensitive = context.parse(options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType); + if (!diacriticSensitive) { + return null; + } + var locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) { + return null; + } + } + return new CollatorExpression(caseSensitive, diacriticSensitive, locale); + }; + CollatorExpression.prototype.evaluate = function evaluate(ctx) { + return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null); + }; + CollatorExpression.prototype.eachChild = function eachChild(fn) { + fn(this.caseSensitive); + fn(this.diacriticSensitive); + if (this.locale) { + fn(this.locale); + } + }; + CollatorExpression.prototype.outputDefined = function outputDefined() { + return false; + }; + CollatorExpression.prototype.serialize = function serialize() { + var options = {}; + options['case-sensitive'] = this.caseSensitive.serialize(); + options['diacritic-sensitive'] = this.diacriticSensitive.serialize(); + if (this.locale) { + options['locale'] = this.locale.serialize(); + } + return [ + 'collator', + options + ]; + }; + + var EXTENT = 8192; + function updateBBox(bbox, coord) { + bbox[0] = Math.min(bbox[0], coord[0]); + bbox[1] = Math.min(bbox[1], coord[1]); + bbox[2] = Math.max(bbox[2], coord[0]); + bbox[3] = Math.max(bbox[3], coord[1]); + } + function mercatorXfromLng(lng) { + return (180 + lng) / 360; + } + function mercatorYfromLat(lat) { + return (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360))) / 360; + } + function boxWithinBox(bbox1, bbox2) { + if (bbox1[0] <= bbox2[0]) { + return false; + } + if (bbox1[2] >= bbox2[2]) { + return false; + } + if (bbox1[1] <= bbox2[1]) { + return false; + } + if (bbox1[3] >= bbox2[3]) { + return false; + } + return true; + } + function getTileCoordinates(p, canonical) { + var x = mercatorXfromLng(p[0]); + var y = mercatorYfromLat(p[1]); + var tilesAtZoom = Math.pow(2, canonical.z); + return [ + Math.round(x * tilesAtZoom * EXTENT), + Math.round(y * tilesAtZoom * EXTENT) + ]; + } + function onBoundary(p, p1, p2) { + var x1 = p[0] - p1[0]; + var y1 = p[1] - p1[1]; + var x2 = p[0] - p2[0]; + var y2 = p[1] - p2[1]; + return x1 * y2 - x2 * y1 === 0 && x1 * x2 <= 0 && y1 * y2 <= 0; + } + function rayIntersect(p, p1, p2) { + return p1[1] > p[1] !== p2[1] > p[1] && p[0] < (p2[0] - p1[0]) * (p[1] - p1[1]) / (p2[1] - p1[1]) + p1[0]; + } + function pointWithinPolygon(point, rings) { + var inside = false; + for (var i = 0, len = rings.length; i < len; i++) { + var ring = rings[i]; + for (var j = 0, len2 = ring.length; j < len2 - 1; j++) { + if (onBoundary(point, ring[j], ring[j + 1])) { + return false; + } + if (rayIntersect(point, ring[j], ring[j + 1])) { + inside = !inside; + } + } + } + return inside; + } + function pointWithinPolygons(point, polygons) { + for (var i = 0; i < polygons.length; i++) { + if (pointWithinPolygon(point, polygons[i])) { + return true; + } + } + return false; + } + function perp(v1, v2) { + return v1[0] * v2[1] - v1[1] * v2[0]; + } + function twoSided(p1, p2, q1, q2) { + var x1 = p1[0] - q1[0]; + var y1 = p1[1] - q1[1]; + var x2 = p2[0] - q1[0]; + var y2 = p2[1] - q1[1]; + var x3 = q2[0] - q1[0]; + var y3 = q2[1] - q1[1]; + var det1 = x1 * y3 - x3 * y1; + var det2 = x2 * y3 - x3 * y2; + if (det1 > 0 && det2 < 0 || det1 < 0 && det2 > 0) { + return true; + } + return false; + } + function lineIntersectLine(a, b, c, d) { + var vectorP = [ + b[0] - a[0], + b[1] - a[1] + ]; + var vectorQ = [ + d[0] - c[0], + d[1] - c[1] + ]; + if (perp(vectorQ, vectorP) === 0) { + return false; + } + if (twoSided(a, b, c, d) && twoSided(c, d, a, b)) { + return true; + } + return false; + } + function lineIntersectPolygon(p1, p2, polygon) { + for (var i = 0, list = polygon; i < list.length; i += 1) { + var ring = list[i]; + for (var j = 0; j < ring.length - 1; ++j) { + if (lineIntersectLine(p1, p2, ring[j], ring[j + 1])) { + return true; + } + } + } + return false; + } + function lineStringWithinPolygon(line, polygon) { + for (var i = 0; i < line.length; ++i) { + if (!pointWithinPolygon(line[i], polygon)) { + return false; + } + } + for (var i$1 = 0; i$1 < line.length - 1; ++i$1) { + if (lineIntersectPolygon(line[i$1], line[i$1 + 1], polygon)) { + return false; + } + } + return true; + } + function lineStringWithinPolygons(line, polygons) { + for (var i = 0; i < polygons.length; i++) { + if (lineStringWithinPolygon(line, polygons[i])) { + return true; + } + } + return false; + } + function getTilePolygon(coordinates, bbox, canonical) { + var polygon = []; + for (var i = 0; i < coordinates.length; i++) { + var ring = []; + for (var j = 0; j < coordinates[i].length; j++) { + var coord = getTileCoordinates(coordinates[i][j], canonical); + updateBBox(bbox, coord); + ring.push(coord); + } + polygon.push(ring); + } + return polygon; + } + function getTilePolygons(coordinates, bbox, canonical) { + var polygons = []; + for (var i = 0; i < coordinates.length; i++) { + var polygon = getTilePolygon(coordinates[i], bbox, canonical); + polygons.push(polygon); + } + return polygons; + } + function updatePoint(p, bbox, polyBBox, worldSize) { + if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) { + var halfWorldSize = worldSize * 0.5; + var shift = p[0] - polyBBox[0] > halfWorldSize ? -worldSize : polyBBox[0] - p[0] > halfWorldSize ? worldSize : 0; + if (shift === 0) { + shift = p[0] - polyBBox[2] > halfWorldSize ? -worldSize : polyBBox[2] - p[0] > halfWorldSize ? worldSize : 0; + } + p[0] += shift; + } + updateBBox(bbox, p); + } + function resetBBox(bbox) { + bbox[0] = bbox[1] = Infinity; + bbox[2] = bbox[3] = -Infinity; + } + function getTilePoints(geometry, pointBBox, polyBBox, canonical) { + var worldSize = Math.pow(2, canonical.z) * EXTENT; + var shifts = [ + canonical.x * EXTENT, + canonical.y * EXTENT + ]; + var tilePoints = []; + for (var i$1 = 0, list$1 = geometry; i$1 < list$1.length; i$1 += 1) { + var points = list$1[i$1]; + for (var i = 0, list = points; i < list.length; i += 1) { + var point = list[i]; + var p = [ + point.x + shifts[0], + point.y + shifts[1] + ]; + updatePoint(p, pointBBox, polyBBox, worldSize); + tilePoints.push(p); + } + } + return tilePoints; + } + function getTileLines(geometry, lineBBox, polyBBox, canonical) { + var worldSize = Math.pow(2, canonical.z) * EXTENT; + var shifts = [ + canonical.x * EXTENT, + canonical.y * EXTENT + ]; + var tileLines = []; + for (var i$1 = 0, list$1 = geometry; i$1 < list$1.length; i$1 += 1) { + var line = list$1[i$1]; + var tileLine = []; + for (var i = 0, list = line; i < list.length; i += 1) { + var point = list[i]; + var p = [ + point.x + shifts[0], + point.y + shifts[1] + ]; + updateBBox(lineBBox, p); + tileLine.push(p); + } + tileLines.push(tileLine); + } + if (lineBBox[2] - lineBBox[0] <= worldSize / 2) { + resetBBox(lineBBox); + for (var i$3 = 0, list$3 = tileLines; i$3 < list$3.length; i$3 += 1) { + var line$1 = list$3[i$3]; + for (var i$2 = 0, list$2 = line$1; i$2 < list$2.length; i$2 += 1) { + var p$1 = list$2[i$2]; + updatePoint(p$1, lineBBox, polyBBox, worldSize); + } + } + } + return tileLines; + } + function pointsWithinPolygons(ctx, polygonGeometry) { + var pointBBox = [ + Infinity, + Infinity, + -Infinity, + -Infinity + ]; + var polyBBox = [ + Infinity, + Infinity, + -Infinity, + -Infinity + ]; + var canonical = ctx.canonicalID(); + if (polygonGeometry.type === 'Polygon') { + var tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + var tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) { + return false; + } + for (var i = 0, list = tilePoints; i < list.length; i += 1) { + var point = list[i]; + if (!pointWithinPolygon(point, tilePolygon)) { + return false; + } + } + } + if (polygonGeometry.type === 'MultiPolygon') { + var tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + var tilePoints$1 = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) { + return false; + } + for (var i$1 = 0, list$1 = tilePoints$1; i$1 < list$1.length; i$1 += 1) { + var point$1 = list$1[i$1]; + if (!pointWithinPolygons(point$1, tilePolygons)) { + return false; + } + } + } + return true; + } + function linesWithinPolygons(ctx, polygonGeometry) { + var lineBBox = [ + Infinity, + Infinity, + -Infinity, + -Infinity + ]; + var polyBBox = [ + Infinity, + Infinity, + -Infinity, + -Infinity + ]; + var canonical = ctx.canonicalID(); + if (polygonGeometry.type === 'Polygon') { + var tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + var tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) { + return false; + } + for (var i = 0, list = tileLines; i < list.length; i += 1) { + var line = list[i]; + if (!lineStringWithinPolygon(line, tilePolygon)) { + return false; + } + } + } + if (polygonGeometry.type === 'MultiPolygon') { + var tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + var tileLines$1 = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) { + return false; + } + for (var i$1 = 0, list$1 = tileLines$1; i$1 < list$1.length; i$1 += 1) { + var line$1 = list$1[i$1]; + if (!lineStringWithinPolygons(line$1, tilePolygons)) { + return false; + } + } + } + return true; + } + var Within = function Within(geojson, geometries) { + this.type = BooleanType; + this.geojson = geojson; + this.geometries = geometries; + }; + Within.parse = function parse(args, context) { + if (args.length !== 2) { + return context.error('\'within\' expression requires exactly one argument, but found ' + (args.length - 1) + ' instead.'); + } + if (isValue(args[1])) { + var geojson = args[1]; + if (geojson.type === 'FeatureCollection') { + for (var i = 0; i < geojson.features.length; ++i) { + var type = geojson.features[i].geometry.type; + if (type === 'Polygon' || type === 'MultiPolygon') { + return new Within(geojson, geojson.features[i].geometry); + } + } + } else if (geojson.type === 'Feature') { + var type$1 = geojson.geometry.type; + if (type$1 === 'Polygon' || type$1 === 'MultiPolygon') { + return new Within(geojson, geojson.geometry); + } + } else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') { + return new Within(geojson, geojson); + } + } + return context.error('\'within\' expression requires valid geojson object that contains polygon geometry type.'); + }; + Within.prototype.evaluate = function evaluate(ctx) { + if (ctx.geometry() != null && ctx.canonicalID() != null) { + if (ctx.geometryType() === 'Point') { + return pointsWithinPolygons(ctx, this.geometries); + } else if (ctx.geometryType() === 'LineString') { + return linesWithinPolygons(ctx, this.geometries); + } + } + return false; + }; + Within.prototype.eachChild = function eachChild() { + }; + Within.prototype.outputDefined = function outputDefined() { + return true; + }; + Within.prototype.serialize = function serialize() { + return [ + 'within', + this.geojson + ]; + }; + + function isFeatureConstant(e) { + if (e instanceof CompoundExpression) { + if (e.name === 'get' && e.args.length === 1) { + return false; + } else if (e.name === 'feature-state') { + return false; + } else if (e.name === 'has' && e.args.length === 1) { + return false; + } else if (e.name === 'properties' || e.name === 'geometry-type' || e.name === 'id') { + return false; + } else if (/^filter-/.test(e.name)) { + return false; + } + } + if (e instanceof Within) { + return false; + } + var result = true; + e.eachChild(function (arg) { + if (result && !isFeatureConstant(arg)) { + result = false; + } + }); + return result; + } + function isStateConstant(e) { + if (e instanceof CompoundExpression) { + if (e.name === 'feature-state') { + return false; + } + } + var result = true; + e.eachChild(function (arg) { + if (result && !isStateConstant(arg)) { + result = false; + } + }); + return result; + } + function isGlobalPropertyConstant(e, properties) { + if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) { + return false; + } + var result = true; + e.eachChild(function (arg) { + if (result && !isGlobalPropertyConstant(arg, properties)) { + result = false; + } + }); + return result; + } + + var Var = function Var(name, boundExpression) { + this.type = boundExpression.type; + this.name = name; + this.boundExpression = boundExpression; + }; + Var.parse = function parse(args, context) { + if (args.length !== 2 || typeof args[1] !== 'string') { + return context.error('\'var\' expression requires exactly one string literal argument.'); + } + var name = args[1]; + if (!context.scope.has(name)) { + return context.error('Unknown variable "' + name + '". Make sure "' + name + '" has been bound in an enclosing "let" expression before using it.', 1); + } + return new Var(name, context.scope.get(name)); + }; + Var.prototype.evaluate = function evaluate(ctx) { + return this.boundExpression.evaluate(ctx); + }; + Var.prototype.eachChild = function eachChild() { + }; + Var.prototype.outputDefined = function outputDefined() { + return false; + }; + Var.prototype.serialize = function serialize() { + return [ + 'var', + this.name + ]; + }; + + var ParsingContext = function ParsingContext(registry, path, expectedType, scope, errors) { + if (path === void 0) + path = []; + if (scope === void 0) + scope = new Scope(); + if (errors === void 0) + errors = []; + this.registry = registry; + this.path = path; + this.key = path.map(function (part) { + return '[' + part + ']'; + }).join(''); + this.scope = scope; + this.errors = errors; + this.expectedType = expectedType; + }; + ParsingContext.prototype.parse = function parse(expr, index, expectedType, bindings, options) { + if (options === void 0) + options = {}; + if (index) { + return this.concat(index, expectedType, bindings)._parse(expr, options); + } + return this._parse(expr, options); + }; + ParsingContext.prototype._parse = function _parse(expr, options) { + if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') { + expr = [ + 'literal', + expr + ]; + } + function annotate(parsed, type, typeAnnotation) { + if (typeAnnotation === 'assert') { + return new Assertion(type, [parsed]); + } else if (typeAnnotation === 'coerce') { + return new Coercion(type, [parsed]); + } else { + return parsed; + } + } + if (Array.isArray(expr)) { + if (expr.length === 0) { + return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].'); + } + var op = expr[0]; + if (typeof op !== 'string') { + this.error('Expression name must be a string, but found ' + typeof op + ' instead. If you wanted a literal array, use ["literal", [...]].', 0); + return null; + } + var Expr = this.registry[op]; + if (Expr) { + var parsed = Expr.parse(expr, this); + if (!parsed) { + return null; + } + if (this.expectedType) { + var expected = this.expectedType; + var actual = parsed.type; + if ((expected.kind === 'string' || expected.kind === 'number' || expected.kind === 'boolean' || expected.kind === 'object' || expected.kind === 'array') && actual.kind === 'value') { + parsed = annotate(parsed, expected, options.typeAnnotation || 'assert'); + } else if ((expected.kind === 'color' || expected.kind === 'formatted' || expected.kind === 'resolvedImage') && (actual.kind === 'value' || actual.kind === 'string')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } else if (this.checkSubtype(expected, actual)) { + return null; + } + } + if (!(parsed instanceof Literal) && parsed.type.kind !== 'resolvedImage' && isConstant(parsed)) { + var ec = new EvaluationContext(); + try { + parsed = new Literal(parsed.type, parsed.evaluate(ec)); + } catch (e) { + this.error(e.message); + return null; + } + } + return parsed; + } + return this.error('Unknown expression "' + op + '". If you wanted a literal array, use ["literal", [...]].', 0); + } else if (typeof expr === 'undefined') { + return this.error('\'undefined\' value invalid. Use null instead.'); + } else if (typeof expr === 'object') { + return this.error('Bare objects invalid. Use ["literal", {...}] instead.'); + } else { + return this.error('Expected an array, but found ' + typeof expr + ' instead.'); + } + }; + ParsingContext.prototype.concat = function concat(index, expectedType, bindings) { + var path = typeof index === 'number' ? this.path.concat(index) : this.path; + var scope = bindings ? this.scope.concat(bindings) : this.scope; + return new ParsingContext(this.registry, path, expectedType || null, scope, this.errors); + }; + ParsingContext.prototype.error = function error(error$1) { + var keys = [], len = arguments.length - 1; + while (len-- > 0) + keys[len] = arguments[len + 1]; + var key = '' + this.key + keys.map(function (k) { + return '[' + k + ']'; + }).join(''); + this.errors.push(new ParsingError(key, error$1)); + }; + ParsingContext.prototype.checkSubtype = function checkSubtype$1(expected, t) { + var error = checkSubtype(expected, t); + if (error) { + this.error(error); + } + return error; + }; + function isConstant(expression) { + if (expression instanceof Var) { + return isConstant(expression.boundExpression); + } else if (expression instanceof CompoundExpression && expression.name === 'error') { + return false; + } else if (expression instanceof CollatorExpression) { + return false; + } else if (expression instanceof Within) { + return false; + } + var isTypeAnnotation = expression instanceof Coercion || expression instanceof Assertion; + var childrenConstant = true; + expression.eachChild(function (child) { + if (isTypeAnnotation) { + childrenConstant = childrenConstant && isConstant(child); + } else { + childrenConstant = childrenConstant && child instanceof Literal; + } + }); + if (!childrenConstant) { + return false; + } + return isFeatureConstant(expression) && isGlobalPropertyConstant(expression, [ + 'zoom', + 'heatmap-density', + 'line-progress', + 'accumulated', + 'is-supported-script' + ]); + } + + function findStopLessThanOrEqualTo(stops, input) { + var lastIndex = stops.length - 1; + var lowerIndex = 0; + var upperIndex = lastIndex; + var currentIndex = 0; + var currentValue, nextValue; + while (lowerIndex <= upperIndex) { + currentIndex = Math.floor((lowerIndex + upperIndex) / 2); + currentValue = stops[currentIndex]; + nextValue = stops[currentIndex + 1]; + if (currentValue <= input) { + if (currentIndex === lastIndex || input < nextValue) { + return currentIndex; + } + lowerIndex = currentIndex + 1; + } else if (currentValue > input) { + upperIndex = currentIndex - 1; + } else { + throw new RuntimeError('Input is not a number.'); + } + } + return 0; + } + + var Step = function Step(type, input, stops) { + this.type = type; + this.input = input; + this.labels = []; + this.outputs = []; + for (var i = 0, list = stops; i < list.length; i += 1) { + var ref = list[i]; + var label = ref[0]; + var expression = ref[1]; + this.labels.push(label); + this.outputs.push(expression); + } + }; + Step.parse = function parse(args, context) { + if (args.length - 1 < 4) { + return context.error('Expected at least 4 arguments, but found only ' + (args.length - 1) + '.'); + } + if ((args.length - 1) % 2 !== 0) { + return context.error('Expected an even number of arguments.'); + } + var input = context.parse(args[1], 1, NumberType); + if (!input) { + return null; + } + var stops = []; + var outputType = null; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + for (var i = 1; i < args.length; i += 2) { + var label = i === 1 ? -Infinity : args[i]; + var value = args[i + 1]; + var labelKey = i; + var valueKey = i + 1; + if (typeof label !== 'number') { + return context.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + var parsed = context.parse(value, valueKey, outputType); + if (!parsed) { + return null; + } + outputType = outputType || parsed.type; + stops.push([ + label, + parsed + ]); + } + return new Step(outputType, input, stops); + }; + Step.prototype.evaluate = function evaluate(ctx) { + var labels = this.labels; + var outputs = this.outputs; + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + var value = this.input.evaluate(ctx); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + var stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + var index = findStopLessThanOrEqualTo(labels, value); + return outputs[index].evaluate(ctx); + }; + Step.prototype.eachChild = function eachChild(fn) { + fn(this.input); + for (var i = 0, list = this.outputs; i < list.length; i += 1) { + var expression = list[i]; + fn(expression); + } + }; + Step.prototype.outputDefined = function outputDefined() { + return this.outputs.every(function (out) { + return out.outputDefined(); + }); + }; + Step.prototype.serialize = function serialize() { + var serialized = [ + 'step', + this.input.serialize() + ]; + for (var i = 0; i < this.labels.length; i++) { + if (i > 0) { + serialized.push(this.labels[i]); + } + serialized.push(this.outputs[i].serialize()); + } + return serialized; + }; + + /* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Ported from Webkit + * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h + */ + + var unitbezier = UnitBezier; + + function UnitBezier(p1x, p1y, p2x, p2y) { + // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). + this.cx = 3.0 * p1x; + this.bx = 3.0 * (p2x - p1x) - this.cx; + this.ax = 1.0 - this.cx - this.bx; + + this.cy = 3.0 * p1y; + this.by = 3.0 * (p2y - p1y) - this.cy; + this.ay = 1.0 - this.cy - this.by; + + this.p1x = p1x; + this.p1y = p2y; + this.p2x = p2x; + this.p2y = p2y; + } + + UnitBezier.prototype.sampleCurveX = function(t) { + // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. + return ((this.ax * t + this.bx) * t + this.cx) * t; + }; + + UnitBezier.prototype.sampleCurveY = function(t) { + return ((this.ay * t + this.by) * t + this.cy) * t; + }; + + UnitBezier.prototype.sampleCurveDerivativeX = function(t) { + return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx; + }; + + UnitBezier.prototype.solveCurveX = function(x, epsilon) { + if (typeof epsilon === 'undefined') { epsilon = 1e-6; } + + var t0, t1, t2, x2, i; + + // First try a few iterations of Newton's method -- normally very fast. + for (t2 = x, i = 0; i < 8; i++) { + + x2 = this.sampleCurveX(t2) - x; + if (Math.abs(x2) < epsilon) { return t2; } + + var d2 = this.sampleCurveDerivativeX(t2); + if (Math.abs(d2) < 1e-6) { break; } + + t2 = t2 - x2 / d2; + } + + // Fall back to the bisection method for reliability. + t0 = 0.0; + t1 = 1.0; + t2 = x; + + if (t2 < t0) { return t0; } + if (t2 > t1) { return t1; } + + while (t0 < t1) { + + x2 = this.sampleCurveX(t2); + if (Math.abs(x2 - x) < epsilon) { return t2; } + + if (x > x2) { + t0 = t2; + } else { + t1 = t2; + } + + t2 = (t1 - t0) * 0.5 + t0; + } + + // Failure. + return t2; + }; + + UnitBezier.prototype.solve = function(x, epsilon) { + return this.sampleCurveY(this.solveCurveX(x, epsilon)); + }; + + function number(a, b, t) { + return a * (1 - t) + b * t; + } + function color(from, to, t) { + return new Color(number(from.r, to.r, t), number(from.g, to.g, t), number(from.b, to.b, t), number(from.a, to.a, t)); + } + function array$1(from, to, t) { + return from.map(function (d, i) { + return number(d, to[i], t); + }); + } + + var interpolate = /*#__PURE__*/Object.freeze({ + __proto__: null, + number: number, + color: color, + array: array$1 + }); + + var Xn = 0.95047, Yn = 1, Zn = 1.08883, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1, deg2rad = Math.PI / 180, rad2deg = 180 / Math.PI; + function xyz2lab(t) { + return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0; + } + function lab2xyz(t) { + return t > t1 ? t * t * t : t2 * (t - t0); + } + function xyz2rgb(x) { + return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); + } + function rgb2xyz(x) { + x /= 255; + return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); + } + function rgbToLab(rgbColor) { + var b = rgb2xyz(rgbColor.r), a = rgb2xyz(rgbColor.g), l = rgb2xyz(rgbColor.b), x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn), y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.072175 * l) / Yn), z = xyz2lab((0.0193339 * b + 0.119192 * a + 0.9503041 * l) / Zn); + return { + l: 116 * y - 16, + a: 500 * (x - y), + b: 200 * (y - z), + alpha: rgbColor.a + }; + } + function labToRgb(labColor) { + var y = (labColor.l + 16) / 116, x = isNaN(labColor.a) ? y : y + labColor.a / 500, z = isNaN(labColor.b) ? y : y - labColor.b / 200; + y = Yn * lab2xyz(y); + x = Xn * lab2xyz(x); + z = Zn * lab2xyz(z); + return new Color(xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z), xyz2rgb(-0.969266 * x + 1.8760108 * y + 0.041556 * z), xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z), labColor.alpha); + } + function interpolateLab(from, to, t) { + return { + l: number(from.l, to.l, t), + a: number(from.a, to.a, t), + b: number(from.b, to.b, t), + alpha: number(from.alpha, to.alpha, t) + }; + } + function rgbToHcl(rgbColor) { + var ref = rgbToLab(rgbColor); + var l = ref.l; + var a = ref.a; + var b = ref.b; + var h = Math.atan2(b, a) * rad2deg; + return { + h: h < 0 ? h + 360 : h, + c: Math.sqrt(a * a + b * b), + l: l, + alpha: rgbColor.a + }; + } + function hclToRgb(hclColor) { + var h = hclColor.h * deg2rad, c = hclColor.c, l = hclColor.l; + return labToRgb({ + l: l, + a: Math.cos(h) * c, + b: Math.sin(h) * c, + alpha: hclColor.alpha + }); + } + function interpolateHue(a, b, t) { + var d = b - a; + return a + t * (d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d); + } + function interpolateHcl(from, to, t) { + return { + h: interpolateHue(from.h, to.h, t), + c: number(from.c, to.c, t), + l: number(from.l, to.l, t), + alpha: number(from.alpha, to.alpha, t) + }; + } + var lab = { + forward: rgbToLab, + reverse: labToRgb, + interpolate: interpolateLab + }; + var hcl = { + forward: rgbToHcl, + reverse: hclToRgb, + interpolate: interpolateHcl + }; + + var colorSpaces = /*#__PURE__*/Object.freeze({ + __proto__: null, + lab: lab, + hcl: hcl + }); + + var Interpolate = function Interpolate(type, operator, interpolation, input, stops) { + this.type = type; + this.operator = operator; + this.interpolation = interpolation; + this.input = input; + this.labels = []; + this.outputs = []; + for (var i = 0, list = stops; i < list.length; i += 1) { + var ref = list[i]; + var label = ref[0]; + var expression = ref[1]; + this.labels.push(label); + this.outputs.push(expression); + } + }; + Interpolate.interpolationFactor = function interpolationFactor(interpolation, input, lower, upper) { + var t = 0; + if (interpolation.name === 'exponential') { + t = exponentialInterpolation(input, interpolation.base, lower, upper); + } else if (interpolation.name === 'linear') { + t = exponentialInterpolation(input, 1, lower, upper); + } else if (interpolation.name === 'cubic-bezier') { + var c = interpolation.controlPoints; + var ub = new unitbezier(c[0], c[1], c[2], c[3]); + t = ub.solve(exponentialInterpolation(input, 1, lower, upper)); + } + return t; + }; + Interpolate.parse = function parse(args, context) { + var operator = args[0]; + var interpolation = args[1]; + var input = args[2]; + var rest = args.slice(3); + if (!Array.isArray(interpolation) || interpolation.length === 0) { + return context.error('Expected an interpolation type expression.', 1); + } + if (interpolation[0] === 'linear') { + interpolation = { name: 'linear' }; + } else if (interpolation[0] === 'exponential') { + var base = interpolation[1]; + if (typeof base !== 'number') { + return context.error('Exponential interpolation requires a numeric base.', 1, 1); + } + interpolation = { + name: 'exponential', + base: base + }; + } else if (interpolation[0] === 'cubic-bezier') { + var controlPoints = interpolation.slice(1); + if (controlPoints.length !== 4 || controlPoints.some(function (t) { + return typeof t !== 'number' || t < 0 || t > 1; + })) { + return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1); + } + interpolation = { + name: 'cubic-bezier', + controlPoints: controlPoints + }; + } else { + return context.error('Unknown interpolation type ' + String(interpolation[0]), 1, 0); + } + if (args.length - 1 < 4) { + return context.error('Expected at least 4 arguments, but found only ' + (args.length - 1) + '.'); + } + if ((args.length - 1) % 2 !== 0) { + return context.error('Expected an even number of arguments.'); + } + input = context.parse(input, 2, NumberType); + if (!input) { + return null; + } + var stops = []; + var outputType = null; + if (operator === 'interpolate-hcl' || operator === 'interpolate-lab') { + outputType = ColorType; + } else if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + for (var i = 0; i < rest.length; i += 2) { + var label = rest[i]; + var value = rest[i + 1]; + var labelKey = i + 3; + var valueKey = i + 4; + if (typeof label !== 'number') { + return context.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + var parsed = context.parse(value, valueKey, outputType); + if (!parsed) { + return null; + } + outputType = outputType || parsed.type; + stops.push([ + label, + parsed + ]); + } + if (outputType.kind !== 'number' && outputType.kind !== 'color' && !(outputType.kind === 'array' && outputType.itemType.kind === 'number' && typeof outputType.N === 'number')) { + return context.error('Type ' + toString(outputType) + ' is not interpolatable.'); + } + return new Interpolate(outputType, operator, interpolation, input, stops); + }; + Interpolate.prototype.evaluate = function evaluate(ctx) { + var labels = this.labels; + var outputs = this.outputs; + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + var value = this.input.evaluate(ctx); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + var stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + var index = findStopLessThanOrEqualTo(labels, value); + var lower = labels[index]; + var upper = labels[index + 1]; + var t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper); + var outputLower = outputs[index].evaluate(ctx); + var outputUpper = outputs[index + 1].evaluate(ctx); + if (this.operator === 'interpolate') { + return interpolate[this.type.kind.toLowerCase()](outputLower, outputUpper, t); + } else if (this.operator === 'interpolate-hcl') { + return hcl.reverse(hcl.interpolate(hcl.forward(outputLower), hcl.forward(outputUpper), t)); + } else { + return lab.reverse(lab.interpolate(lab.forward(outputLower), lab.forward(outputUpper), t)); + } + }; + Interpolate.prototype.eachChild = function eachChild(fn) { + fn(this.input); + for (var i = 0, list = this.outputs; i < list.length; i += 1) { + var expression = list[i]; + fn(expression); + } + }; + Interpolate.prototype.outputDefined = function outputDefined() { + return this.outputs.every(function (out) { + return out.outputDefined(); + }); + }; + Interpolate.prototype.serialize = function serialize() { + var interpolation; + if (this.interpolation.name === 'linear') { + interpolation = ['linear']; + } else if (this.interpolation.name === 'exponential') { + if (this.interpolation.base === 1) { + interpolation = ['linear']; + } else { + interpolation = [ + 'exponential', + this.interpolation.base + ]; + } + } else { + interpolation = ['cubic-bezier'].concat(this.interpolation.controlPoints); + } + var serialized = [ + this.operator, + interpolation, + this.input.serialize() + ]; + for (var i = 0; i < this.labels.length; i++) { + serialized.push(this.labels[i], this.outputs[i].serialize()); + } + return serialized; + }; + function exponentialInterpolation(input, base, lowerValue, upperValue) { + var difference = upperValue - lowerValue; + var progress = input - lowerValue; + if (difference === 0) { + return 0; + } else if (base === 1) { + return progress / difference; + } else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } + } + + var Coalesce = function Coalesce(type, args) { + this.type = type; + this.args = args; + }; + Coalesce.parse = function parse(args, context) { + if (args.length < 2) { + return context.error('Expectected at least one argument.'); + } + var outputType = null; + var expectedType = context.expectedType; + if (expectedType && expectedType.kind !== 'value') { + outputType = expectedType; + } + var parsedArgs = []; + for (var i = 0, list = args.slice(1); i < list.length; i += 1) { + var arg = list[i]; + var parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, { typeAnnotation: 'omit' }); + if (!parsed) { + return null; + } + outputType = outputType || parsed.type; + parsedArgs.push(parsed); + } + var needsAnnotation = expectedType && parsedArgs.some(function (arg) { + return checkSubtype(expectedType, arg.type); + }); + return needsAnnotation ? new Coalesce(ValueType, parsedArgs) : new Coalesce(outputType, parsedArgs); + }; + Coalesce.prototype.evaluate = function evaluate(ctx) { + var result = null; + var argCount = 0; + var requestedImageName; + for (var i = 0, list = this.args; i < list.length; i += 1) { + var arg = list[i]; + argCount++; + result = arg.evaluate(ctx); + if (result && result instanceof ResolvedImage && !result.available) { + if (!requestedImageName) { + requestedImageName = result.name; + } + result = null; + if (argCount === this.args.length) { + result = requestedImageName; + } + } + if (result !== null) { + break; + } + } + return result; + }; + Coalesce.prototype.eachChild = function eachChild(fn) { + this.args.forEach(fn); + }; + Coalesce.prototype.outputDefined = function outputDefined() { + return this.args.every(function (arg) { + return arg.outputDefined(); + }); + }; + Coalesce.prototype.serialize = function serialize() { + var serialized = ['coalesce']; + this.eachChild(function (child) { + serialized.push(child.serialize()); + }); + return serialized; + }; + + var Let = function Let(bindings, result) { + this.type = result.type; + this.bindings = [].concat(bindings); + this.result = result; + }; + Let.prototype.evaluate = function evaluate(ctx) { + return this.result.evaluate(ctx); + }; + Let.prototype.eachChild = function eachChild(fn) { + for (var i = 0, list = this.bindings; i < list.length; i += 1) { + var binding = list[i]; + fn(binding[1]); + } + fn(this.result); + }; + Let.parse = function parse(args, context) { + if (args.length < 4) { + return context.error('Expected at least 3 arguments, but found ' + (args.length - 1) + ' instead.'); + } + var bindings = []; + for (var i = 1; i < args.length - 1; i += 2) { + var name = args[i]; + if (typeof name !== 'string') { + return context.error('Expected string, but found ' + typeof name + ' instead.', i); + } + if (/[^a-zA-Z0-9_]/.test(name)) { + return context.error('Variable names must contain only alphanumeric characters or \'_\'.', i); + } + var value = context.parse(args[i + 1], i + 1); + if (!value) { + return null; + } + bindings.push([ + name, + value + ]); + } + var result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings); + if (!result) { + return null; + } + return new Let(bindings, result); + }; + Let.prototype.outputDefined = function outputDefined() { + return this.result.outputDefined(); + }; + Let.prototype.serialize = function serialize() { + var serialized = ['let']; + for (var i = 0, list = this.bindings; i < list.length; i += 1) { + var ref = list[i]; + var name = ref[0]; + var expr = ref[1]; + serialized.push(name, expr.serialize()); + } + serialized.push(this.result.serialize()); + return serialized; + }; + + var At = function At(type, index, input) { + this.type = type; + this.index = index; + this.input = input; + }; + At.parse = function parse(args, context) { + if (args.length !== 3) { + return context.error('Expected 2 arguments, but found ' + (args.length - 1) + ' instead.'); + } + var index = context.parse(args[1], 1, NumberType); + var input = context.parse(args[2], 2, array(context.expectedType || ValueType)); + if (!index || !input) { + return null; + } + var t = input.type; + return new At(t.itemType, index, input); + }; + At.prototype.evaluate = function evaluate(ctx) { + var index = this.index.evaluate(ctx); + var array = this.input.evaluate(ctx); + if (index < 0) { + throw new RuntimeError('Array index out of bounds: ' + index + ' < 0.'); + } + if (index >= array.length) { + throw new RuntimeError('Array index out of bounds: ' + index + ' > ' + (array.length - 1) + '.'); + } + if (index !== Math.floor(index)) { + throw new RuntimeError('Array index must be an integer, but found ' + index + ' instead.'); + } + return array[index]; + }; + At.prototype.eachChild = function eachChild(fn) { + fn(this.index); + fn(this.input); + }; + At.prototype.outputDefined = function outputDefined() { + return false; + }; + At.prototype.serialize = function serialize() { + return [ + 'at', + this.index.serialize(), + this.input.serialize() + ]; + }; + + var In = function In(needle, haystack) { + this.type = BooleanType; + this.needle = needle; + this.haystack = haystack; + }; + In.parse = function parse(args, context) { + if (args.length !== 3) { + return context.error('Expected 2 arguments, but found ' + (args.length - 1) + ' instead.'); + } + var needle = context.parse(args[1], 1, ValueType); + var haystack = context.parse(args[2], 2, ValueType); + if (!needle || !haystack) { + return null; + } + if (!isValidType(needle.type, [ + BooleanType, + StringType, + NumberType, + NullType, + ValueType + ])) { + return context.error('Expected first argument to be of type boolean, string, number or null, but found ' + toString(needle.type) + ' instead'); + } + return new In(needle, haystack); + }; + In.prototype.evaluate = function evaluate(ctx) { + var needle = this.needle.evaluate(ctx); + var haystack = this.haystack.evaluate(ctx); + if (!haystack) { + return false; + } + if (!isValidNativeType(needle, [ + 'boolean', + 'string', + 'number', + 'null' + ])) { + throw new RuntimeError('Expected first argument to be of type boolean, string, number or null, but found ' + toString(typeOf(needle)) + ' instead.'); + } + if (!isValidNativeType(haystack, [ + 'string', + 'array' + ])) { + throw new RuntimeError('Expected second argument to be of type array or string, but found ' + toString(typeOf(haystack)) + ' instead.'); + } + return haystack.indexOf(needle) >= 0; + }; + In.prototype.eachChild = function eachChild(fn) { + fn(this.needle); + fn(this.haystack); + }; + In.prototype.outputDefined = function outputDefined() { + return true; + }; + In.prototype.serialize = function serialize() { + return [ + 'in', + this.needle.serialize(), + this.haystack.serialize() + ]; + }; + + var IndexOf = function IndexOf(needle, haystack, fromIndex) { + this.type = NumberType; + this.needle = needle; + this.haystack = haystack; + this.fromIndex = fromIndex; + }; + IndexOf.parse = function parse(args, context) { + if (args.length <= 2 || args.length >= 5) { + return context.error('Expected 3 or 4 arguments, but found ' + (args.length - 1) + ' instead.'); + } + var needle = context.parse(args[1], 1, ValueType); + var haystack = context.parse(args[2], 2, ValueType); + if (!needle || !haystack) { + return null; + } + if (!isValidType(needle.type, [ + BooleanType, + StringType, + NumberType, + NullType, + ValueType + ])) { + return context.error('Expected first argument to be of type boolean, string, number or null, but found ' + toString(needle.type) + ' instead'); + } + if (args.length === 4) { + var fromIndex = context.parse(args[3], 3, NumberType); + if (!fromIndex) { + return null; + } + return new IndexOf(needle, haystack, fromIndex); + } else { + return new IndexOf(needle, haystack); + } + }; + IndexOf.prototype.evaluate = function evaluate(ctx) { + var needle = this.needle.evaluate(ctx); + var haystack = this.haystack.evaluate(ctx); + if (!isValidNativeType(needle, [ + 'boolean', + 'string', + 'number', + 'null' + ])) { + throw new RuntimeError('Expected first argument to be of type boolean, string, number or null, but found ' + toString(typeOf(needle)) + ' instead.'); + } + if (!isValidNativeType(haystack, [ + 'string', + 'array' + ])) { + throw new RuntimeError('Expected second argument to be of type array or string, but found ' + toString(typeOf(haystack)) + ' instead.'); + } + if (this.fromIndex) { + var fromIndex = this.fromIndex.evaluate(ctx); + return haystack.indexOf(needle, fromIndex); + } + return haystack.indexOf(needle); + }; + IndexOf.prototype.eachChild = function eachChild(fn) { + fn(this.needle); + fn(this.haystack); + if (this.fromIndex) { + fn(this.fromIndex); + } + }; + IndexOf.prototype.outputDefined = function outputDefined() { + return false; + }; + IndexOf.prototype.serialize = function serialize() { + if (this.fromIndex != null && this.fromIndex !== undefined) { + var fromIndex = this.fromIndex.serialize(); + return [ + 'index-of', + this.needle.serialize(), + this.haystack.serialize(), + fromIndex + ]; + } + return [ + 'index-of', + this.needle.serialize(), + this.haystack.serialize() + ]; + }; + + var Match = function Match(inputType, outputType, input, cases, outputs, otherwise) { + this.inputType = inputType; + this.type = outputType; + this.input = input; + this.cases = cases; + this.outputs = outputs; + this.otherwise = otherwise; + }; + Match.parse = function parse(args, context) { + if (args.length < 5) { + return context.error('Expected at least 4 arguments, but found only ' + (args.length - 1) + '.'); + } + if (args.length % 2 !== 1) { + return context.error('Expected an even number of arguments.'); + } + var inputType; + var outputType; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + var cases = {}; + var outputs = []; + for (var i = 2; i < args.length - 1; i += 2) { + var labels = args[i]; + var value = args[i + 1]; + if (!Array.isArray(labels)) { + labels = [labels]; + } + var labelContext = context.concat(i); + if (labels.length === 0) { + return labelContext.error('Expected at least one branch label.'); + } + for (var i$1 = 0, list = labels; i$1 < list.length; i$1 += 1) { + var label = list[i$1]; + if (typeof label !== 'number' && typeof label !== 'string') { + return labelContext.error('Branch labels must be numbers or strings.'); + } else if (typeof label === 'number' && Math.abs(label) > Number.MAX_SAFE_INTEGER) { + return labelContext.error('Branch labels must be integers no larger than ' + Number.MAX_SAFE_INTEGER + '.'); + } else if (typeof label === 'number' && Math.floor(label) !== label) { + return labelContext.error('Numeric branch labels must be integer values.'); + } else if (!inputType) { + inputType = typeOf(label); + } else if (labelContext.checkSubtype(inputType, typeOf(label))) { + return null; + } + if (typeof cases[String(label)] !== 'undefined') { + return labelContext.error('Branch labels must be unique.'); + } + cases[String(label)] = outputs.length; + } + var result = context.parse(value, i, outputType); + if (!result) { + return null; + } + outputType = outputType || result.type; + outputs.push(result); + } + var input = context.parse(args[1], 1, ValueType); + if (!input) { + return null; + } + var otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) { + return null; + } + if (input.type.kind !== 'value' && context.concat(1).checkSubtype(inputType, input.type)) { + return null; + } + return new Match(inputType, outputType, input, cases, outputs, otherwise); + }; + Match.prototype.evaluate = function evaluate(ctx) { + var input = this.input.evaluate(ctx); + var output = typeOf(input) === this.inputType && this.outputs[this.cases[input]] || this.otherwise; + return output.evaluate(ctx); + }; + Match.prototype.eachChild = function eachChild(fn) { + fn(this.input); + this.outputs.forEach(fn); + fn(this.otherwise); + }; + Match.prototype.outputDefined = function outputDefined() { + return this.outputs.every(function (out) { + return out.outputDefined(); + }) && this.otherwise.outputDefined(); + }; + Match.prototype.serialize = function serialize() { + var this$1 = this; + var serialized = [ + 'match', + this.input.serialize() + ]; + var sortedLabels = Object.keys(this.cases).sort(); + var groupedByOutput = []; + var outputLookup = {}; + for (var i = 0, list = sortedLabels; i < list.length; i += 1) { + var label = list[i]; + var outputIndex = outputLookup[this.cases[label]]; + if (outputIndex === undefined) { + outputLookup[this.cases[label]] = groupedByOutput.length; + groupedByOutput.push([ + this.cases[label], + [label] + ]); + } else { + groupedByOutput[outputIndex][1].push(label); + } + } + var coerceLabel = function (label) { + return this$1.inputType.kind === 'number' ? Number(label) : label; + }; + for (var i$1 = 0, list$1 = groupedByOutput; i$1 < list$1.length; i$1 += 1) { + var ref = list$1[i$1]; + var outputIndex = ref[0]; + var labels = ref[1]; + if (labels.length === 1) { + serialized.push(coerceLabel(labels[0])); + } else { + serialized.push(labels.map(coerceLabel)); + } + serialized.push(this.outputs[outputIndex$1].serialize()); + } + serialized.push(this.otherwise.serialize()); + return serialized; + }; + + var Case = function Case(type, branches, otherwise) { + this.type = type; + this.branches = branches; + this.otherwise = otherwise; + }; + Case.parse = function parse(args, context) { + if (args.length < 4) { + return context.error('Expected at least 3 arguments, but found only ' + (args.length - 1) + '.'); + } + if (args.length % 2 !== 0) { + return context.error('Expected an odd number of arguments.'); + } + var outputType; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + var branches = []; + for (var i = 1; i < args.length - 1; i += 2) { + var test = context.parse(args[i], i, BooleanType); + if (!test) { + return null; + } + var result = context.parse(args[i + 1], i + 1, outputType); + if (!result) { + return null; + } + branches.push([ + test, + result + ]); + outputType = outputType || result.type; + } + var otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) { + return null; + } + return new Case(outputType, branches, otherwise); + }; + Case.prototype.evaluate = function evaluate(ctx) { + for (var i = 0, list = this.branches; i < list.length; i += 1) { + var ref = list[i]; + var test = ref[0]; + var expression = ref[1]; + if (test.evaluate(ctx)) { + return expression.evaluate(ctx); + } + } + return this.otherwise.evaluate(ctx); + }; + Case.prototype.eachChild = function eachChild(fn) { + for (var i = 0, list = this.branches; i < list.length; i += 1) { + var ref = list[i]; + var test = ref[0]; + var expression = ref[1]; + fn(test); + fn(expression); + } + fn(this.otherwise); + }; + Case.prototype.outputDefined = function outputDefined() { + return this.branches.every(function (ref) { + var _ = ref[0]; + var out = ref[1]; + return out.outputDefined(); + }) && this.otherwise.outputDefined(); + }; + Case.prototype.serialize = function serialize() { + var serialized = ['case']; + this.eachChild(function (child) { + serialized.push(child.serialize()); + }); + return serialized; + }; + + var Slice = function Slice(type, input, beginIndex, endIndex) { + this.type = type; + this.input = input; + this.beginIndex = beginIndex; + this.endIndex = endIndex; + }; + Slice.parse = function parse(args, context) { + if (args.length <= 2 || args.length >= 5) { + return context.error('Expected 3 or 4 arguments, but found ' + (args.length - 1) + ' instead.'); + } + var input = context.parse(args[1], 1, ValueType); + var beginIndex = context.parse(args[2], 2, NumberType); + if (!input || !beginIndex) { + return null; + } + if (!isValidType(input.type, [ + array(ValueType), + StringType, + ValueType + ])) { + return context.error('Expected first argument to be of type array or string, but found ' + toString(input.type) + ' instead'); + } + if (args.length === 4) { + var endIndex = context.parse(args[3], 3, NumberType); + if (!endIndex) { + return null; + } + return new Slice(input.type, input, beginIndex, endIndex); + } else { + return new Slice(input.type, input, beginIndex); + } + }; + Slice.prototype.evaluate = function evaluate(ctx) { + var input = this.input.evaluate(ctx); + var beginIndex = this.beginIndex.evaluate(ctx); + if (!isValidNativeType(input, [ + 'string', + 'array' + ])) { + throw new RuntimeError('Expected first argument to be of type array or string, but found ' + toString(typeOf(input)) + ' instead.'); + } + if (this.endIndex) { + var endIndex = this.endIndex.evaluate(ctx); + return input.slice(beginIndex, endIndex); + } + return input.slice(beginIndex); + }; + Slice.prototype.eachChild = function eachChild(fn) { + fn(this.input); + fn(this.beginIndex); + if (this.endIndex) { + fn(this.endIndex); + } + }; + Slice.prototype.outputDefined = function outputDefined() { + return false; + }; + Slice.prototype.serialize = function serialize() { + if (this.endIndex != null && this.endIndex !== undefined) { + var endIndex = this.endIndex.serialize(); + return [ + 'slice', + this.input.serialize(), + this.beginIndex.serialize(), + endIndex + ]; + } + return [ + 'slice', + this.input.serialize(), + this.beginIndex.serialize() + ]; + }; + + function isComparableType(op, type) { + if (op === '==' || op === '!=') { + return type.kind === 'boolean' || type.kind === 'string' || type.kind === 'number' || type.kind === 'null' || type.kind === 'value'; + } else { + return type.kind === 'string' || type.kind === 'number' || type.kind === 'value'; + } + } + function eq(ctx, a, b) { + return a === b; + } + function neq(ctx, a, b) { + return a !== b; + } + function lt(ctx, a, b) { + return a < b; + } + function gt(ctx, a, b) { + return a > b; + } + function lteq(ctx, a, b) { + return a <= b; + } + function gteq(ctx, a, b) { + return a >= b; + } + function eqCollate(ctx, a, b, c) { + return c.compare(a, b) === 0; + } + function neqCollate(ctx, a, b, c) { + return !eqCollate(ctx, a, b, c); + } + function ltCollate(ctx, a, b, c) { + return c.compare(a, b) < 0; + } + function gtCollate(ctx, a, b, c) { + return c.compare(a, b) > 0; + } + function lteqCollate(ctx, a, b, c) { + return c.compare(a, b) <= 0; + } + function gteqCollate(ctx, a, b, c) { + return c.compare(a, b) >= 0; + } + function makeComparison(op, compareBasic, compareWithCollator) { + var isOrderComparison = op !== '==' && op !== '!='; + return function () { + function Comparison(lhs, rhs, collator) { + this.type = BooleanType; + this.lhs = lhs; + this.rhs = rhs; + this.collator = collator; + this.hasUntypedArgument = lhs.type.kind === 'value' || rhs.type.kind === 'value'; + } + Comparison.parse = function parse(args, context) { + if (args.length !== 3 && args.length !== 4) { + return context.error('Expected two or three arguments.'); + } + var op = args[0]; + var lhs = context.parse(args[1], 1, ValueType); + if (!lhs) { + return null; + } + if (!isComparableType(op, lhs.type)) { + return context.concat(1).error('"' + op + '" comparisons are not supported for type \'' + toString(lhs.type) + '\'.'); + } + var rhs = context.parse(args[2], 2, ValueType); + if (!rhs) { + return null; + } + if (!isComparableType(op, rhs.type)) { + return context.concat(2).error('"' + op + '" comparisons are not supported for type \'' + toString(rhs.type) + '\'.'); + } + if (lhs.type.kind !== rhs.type.kind && lhs.type.kind !== 'value' && rhs.type.kind !== 'value') { + return context.error('Cannot compare types \'' + toString(lhs.type) + '\' and \'' + toString(rhs.type) + '\'.'); + } + if (isOrderComparison) { + if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') { + lhs = new Assertion(rhs.type, [lhs]); + } else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') { + rhs = new Assertion(lhs.type, [rhs]); + } + } + var collator = null; + if (args.length === 4) { + if (lhs.type.kind !== 'string' && rhs.type.kind !== 'string' && lhs.type.kind !== 'value' && rhs.type.kind !== 'value') { + return context.error('Cannot use collator to compare non-string types.'); + } + collator = context.parse(args[3], 3, CollatorType); + if (!collator) { + return null; + } + } + return new Comparison(lhs, rhs, collator); + }; + Comparison.prototype.evaluate = function evaluate(ctx) { + var lhs = this.lhs.evaluate(ctx); + var rhs = this.rhs.evaluate(ctx); + if (isOrderComparison && this.hasUntypedArgument) { + var lt = typeOf(lhs); + var rt = typeOf(rhs); + if (lt.kind !== rt.kind || !(lt.kind === 'string' || lt.kind === 'number')) { + throw new RuntimeError('Expected arguments for "' + op + '" to be (string, string) or (number, number), but found (' + lt.kind + ', ' + rt.kind + ') instead.'); + } + } + if (this.collator && !isOrderComparison && this.hasUntypedArgument) { + var lt$1 = typeOf(lhs); + var rt$1 = typeOf(rhs); + if (lt$1.kind !== 'string' || rt$1.kind !== 'string') { + return compareBasic(ctx, lhs, rhs); + } + } + return this.collator ? compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) : compareBasic(ctx, lhs, rhs); + }; + Comparison.prototype.eachChild = function eachChild(fn) { + fn(this.lhs); + fn(this.rhs); + if (this.collator) { + fn(this.collator); + } + }; + Comparison.prototype.outputDefined = function outputDefined() { + return true; + }; + Comparison.prototype.serialize = function serialize() { + var serialized = [op]; + this.eachChild(function (child) { + serialized.push(child.serialize()); + }); + return serialized; + }; + return Comparison; + }(); + } + var Equals = makeComparison('==', eq, eqCollate); + var NotEquals = makeComparison('!=', neq, neqCollate); + var LessThan = makeComparison('<', lt, ltCollate); + var GreaterThan = makeComparison('>', gt, gtCollate); + var LessThanOrEqual = makeComparison('<=', lteq, lteqCollate); + var GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate); + + var NumberFormat = function NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits) { + this.type = StringType; + this.number = number; + this.locale = locale; + this.currency = currency; + this.minFractionDigits = minFractionDigits; + this.maxFractionDigits = maxFractionDigits; + }; + NumberFormat.parse = function parse(args, context) { + if (args.length !== 3) { + return context.error('Expected two arguments.'); + } + var number = context.parse(args[1], 1, NumberType); + if (!number) { + return null; + } + var options = args[2]; + if (typeof options !== 'object' || Array.isArray(options)) { + return context.error('NumberFormat options argument must be an object.'); + } + var locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) { + return null; + } + } + var currency = null; + if (options['currency']) { + currency = context.parse(options['currency'], 1, StringType); + if (!currency) { + return null; + } + } + var minFractionDigits = null; + if (options['min-fraction-digits']) { + minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType); + if (!minFractionDigits) { + return null; + } + } + var maxFractionDigits = null; + if (options['max-fraction-digits']) { + maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType); + if (!maxFractionDigits) { + return null; + } + } + return new NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits); + }; + NumberFormat.prototype.evaluate = function evaluate(ctx) { + return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], { + style: this.currency ? 'currency' : 'decimal', + currency: this.currency ? this.currency.evaluate(ctx) : undefined, + minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : undefined, + maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : undefined + }).format(this.number.evaluate(ctx)); + }; + NumberFormat.prototype.eachChild = function eachChild(fn) { + fn(this.number); + if (this.locale) { + fn(this.locale); + } + if (this.currency) { + fn(this.currency); + } + if (this.minFractionDigits) { + fn(this.minFractionDigits); + } + if (this.maxFractionDigits) { + fn(this.maxFractionDigits); + } + }; + NumberFormat.prototype.outputDefined = function outputDefined() { + return false; + }; + NumberFormat.prototype.serialize = function serialize() { + var options = {}; + if (this.locale) { + options['locale'] = this.locale.serialize(); + } + if (this.currency) { + options['currency'] = this.currency.serialize(); + } + if (this.minFractionDigits) { + options['min-fraction-digits'] = this.minFractionDigits.serialize(); + } + if (this.maxFractionDigits) { + options['max-fraction-digits'] = this.maxFractionDigits.serialize(); + } + return [ + 'number-format', + this.number.serialize(), + options + ]; + }; + + var Length = function Length(input) { + this.type = NumberType; + this.input = input; + }; + Length.parse = function parse(args, context) { + if (args.length !== 2) { + return context.error('Expected 1 argument, but found ' + (args.length - 1) + ' instead.'); + } + var input = context.parse(args[1], 1); + if (!input) { + return null; + } + if (input.type.kind !== 'array' && input.type.kind !== 'string' && input.type.kind !== 'value') { + return context.error('Expected argument of type string or array, but found ' + toString(input.type) + ' instead.'); + } + return new Length(input); + }; + Length.prototype.evaluate = function evaluate(ctx) { + var input = this.input.evaluate(ctx); + if (typeof input === 'string') { + return input.length; + } else if (Array.isArray(input)) { + return input.length; + } else { + throw new RuntimeError('Expected value to be of type string or array, but found ' + toString(typeOf(input)) + ' instead.'); + } + }; + Length.prototype.eachChild = function eachChild(fn) { + fn(this.input); + }; + Length.prototype.outputDefined = function outputDefined() { + return false; + }; + Length.prototype.serialize = function serialize() { + var serialized = ['length']; + this.eachChild(function (child) { + serialized.push(child.serialize()); + }); + return serialized; + }; + + var expressions = { + '==': Equals, + '!=': NotEquals, + '>': GreaterThan, + '<': LessThan, + '>=': GreaterThanOrEqual, + '<=': LessThanOrEqual, + 'array': Assertion, + 'at': At, + 'boolean': Assertion, + 'case': Case, + 'coalesce': Coalesce, + 'collator': CollatorExpression, + 'format': FormatExpression, + 'image': ImageExpression, + 'in': In, + 'index-of': IndexOf, + 'interpolate': Interpolate, + 'interpolate-hcl': Interpolate, + 'interpolate-lab': Interpolate, + 'length': Length, + 'let': Let, + 'literal': Literal, + 'match': Match, + 'number': Assertion, + 'number-format': NumberFormat, + 'object': Assertion, + 'slice': Slice, + 'step': Step, + 'string': Assertion, + 'to-boolean': Coercion, + 'to-color': Coercion, + 'to-number': Coercion, + 'to-string': Coercion, + 'var': Var, + 'within': Within + }; + function rgba(ctx, ref) { + var r = ref[0]; + var g = ref[1]; + var b = ref[2]; + var a = ref[3]; + r = r.evaluate(ctx); + g = g.evaluate(ctx); + b = b.evaluate(ctx); + var alpha = a ? a.evaluate(ctx) : 1; + var error = validateRGBA(r, g, b, alpha); + if (error) { + throw new RuntimeError(error); + } + return new Color(r / 255 * alpha, g / 255 * alpha, b / 255 * alpha, alpha); + } + function has(key, obj) { + return key in obj; + } + function get(key, obj) { + var v = obj[key]; + return typeof v === 'undefined' ? null : v; + } + function binarySearch(v, a, i, j) { + while (i <= j) { + var m = i + j >> 1; + if (a[m] === v) { + return true; + } + if (a[m] > v) { + j = m - 1; + } else { + i = m + 1; + } + } + return false; + } + function varargs(type) { + return { type: type }; + } + CompoundExpression.register(expressions, { + 'error': [ + ErrorType, + [StringType], + function (ctx, ref) { + var v = ref[0]; + throw new RuntimeError(v.evaluate(ctx)); + } + ], + 'typeof': [ + StringType, + [ValueType], + function (ctx, ref) { + var v = ref[0]; + return toString(typeOf(v.evaluate(ctx))); + } + ], + 'to-rgba': [ + array(NumberType, 4), + [ColorType], + function (ctx, ref) { + var v = ref[0]; + return v.evaluate(ctx).toArray(); + } + ], + 'rgb': [ + ColorType, + [ + NumberType, + NumberType, + NumberType + ], + rgba + ], + 'rgba': [ + ColorType, + [ + NumberType, + NumberType, + NumberType, + NumberType + ], + rgba + ], + 'has': { + type: BooleanType, + overloads: [ + [ + [StringType], + function (ctx, ref) { + var key = ref[0]; + return has(key.evaluate(ctx), ctx.properties()); + } + ], + [ + [ + StringType, + ObjectType + ], + function (ctx, ref) { + var key = ref[0]; + var obj = ref[1]; + return has(key.evaluate(ctx), obj.evaluate(ctx)); + } + ] + ] + }, + 'get': { + type: ValueType, + overloads: [ + [ + [StringType], + function (ctx, ref) { + var key = ref[0]; + return get(key.evaluate(ctx), ctx.properties()); + } + ], + [ + [ + StringType, + ObjectType + ], + function (ctx, ref) { + var key = ref[0]; + var obj = ref[1]; + return get(key.evaluate(ctx), obj.evaluate(ctx)); + } + ] + ] + }, + 'feature-state': [ + ValueType, + [StringType], + function (ctx, ref) { + var key = ref[0]; + return get(key.evaluate(ctx), ctx.featureState || {}); + } + ], + 'properties': [ + ObjectType, + [], + function (ctx) { + return ctx.properties(); + } + ], + 'geometry-type': [ + StringType, + [], + function (ctx) { + return ctx.geometryType(); + } + ], + 'id': [ + ValueType, + [], + function (ctx) { + return ctx.id(); + } + ], + 'zoom': [ + NumberType, + [], + function (ctx) { + return ctx.globals.zoom; + } + ], + 'heatmap-density': [ + NumberType, + [], + function (ctx) { + return ctx.globals.heatmapDensity || 0; + } + ], + 'line-progress': [ + NumberType, + [], + function (ctx) { + return ctx.globals.lineProgress || 0; + } + ], + 'accumulated': [ + ValueType, + [], + function (ctx) { + return ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated; + } + ], + '+': [ + NumberType, + varargs(NumberType), + function (ctx, args) { + var result = 0; + for (var i = 0, list = args; i < list.length; i += 1) { + var arg = list[i]; + result += arg.evaluate(ctx); + } + return result; + } + ], + '*': [ + NumberType, + varargs(NumberType), + function (ctx, args) { + var result = 1; + for (var i = 0, list = args; i < list.length; i += 1) { + var arg = list[i]; + result *= arg.evaluate(ctx); + } + return result; + } + ], + '-': { + type: NumberType, + overloads: [ + [ + [ + NumberType, + NumberType + ], + function (ctx, ref) { + var a = ref[0]; + var b = ref[1]; + return a.evaluate(ctx) - b.evaluate(ctx); + } + ], + [ + [NumberType], + function (ctx, ref) { + var a = ref[0]; + return -a.evaluate(ctx); + } + ] + ] + }, + '/': [ + NumberType, + [ + NumberType, + NumberType + ], + function (ctx, ref) { + var a = ref[0]; + var b = ref[1]; + return a.evaluate(ctx) / b.evaluate(ctx); + } + ], + '%': [ + NumberType, + [ + NumberType, + NumberType + ], + function (ctx, ref) { + var a = ref[0]; + var b = ref[1]; + return a.evaluate(ctx) % b.evaluate(ctx); + } + ], + 'ln2': [ + NumberType, + [], + function () { + return Math.LN2; + } + ], + 'pi': [ + NumberType, + [], + function () { + return Math.PI; + } + ], + 'e': [ + NumberType, + [], + function () { + return Math.E; + } + ], + '^': [ + NumberType, + [ + NumberType, + NumberType + ], + function (ctx, ref) { + var b = ref[0]; + var e = ref[1]; + return Math.pow(b.evaluate(ctx), e.evaluate(ctx)); + } + ], + 'sqrt': [ + NumberType, + [NumberType], + function (ctx, ref) { + var x = ref[0]; + return Math.sqrt(x.evaluate(ctx)); + } + ], + 'log10': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.log(n.evaluate(ctx)) / Math.LN10; + } + ], + 'ln': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.log(n.evaluate(ctx)); + } + ], + 'log2': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.log(n.evaluate(ctx)) / Math.LN2; + } + ], + 'sin': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.sin(n.evaluate(ctx)); + } + ], + 'cos': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.cos(n.evaluate(ctx)); + } + ], + 'tan': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.tan(n.evaluate(ctx)); + } + ], + 'asin': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.asin(n.evaluate(ctx)); + } + ], + 'acos': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.acos(n.evaluate(ctx)); + } + ], + 'atan': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.atan(n.evaluate(ctx)); + } + ], + 'min': [ + NumberType, + varargs(NumberType), + function (ctx, args) { + return Math.min.apply(Math, args.map(function (arg) { + return arg.evaluate(ctx); + })); + } + ], + 'max': [ + NumberType, + varargs(NumberType), + function (ctx, args) { + return Math.max.apply(Math, args.map(function (arg) { + return arg.evaluate(ctx); + })); + } + ], + 'abs': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.abs(n.evaluate(ctx)); + } + ], + 'round': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + var v = n.evaluate(ctx); + return v < 0 ? -Math.round(-v) : Math.round(v); + } + ], + 'floor': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.floor(n.evaluate(ctx)); + } + ], + 'ceil': [ + NumberType, + [NumberType], + function (ctx, ref) { + var n = ref[0]; + return Math.ceil(n.evaluate(ctx)); + } + ], + 'filter-==': [ + BooleanType, + [ + StringType, + ValueType + ], + function (ctx, ref) { + var k = ref[0]; + var v = ref[1]; + return ctx.properties()[k.value] === v.value; + } + ], + 'filter-id-==': [ + BooleanType, + [ValueType], + function (ctx, ref) { + var v = ref[0]; + return ctx.id() === v.value; + } + ], + 'filter-type-==': [ + BooleanType, + [StringType], + function (ctx, ref) { + var v = ref[0]; + return ctx.geometryType() === v.value; + } + ], + 'filter-<': [ + BooleanType, + [ + StringType, + ValueType + ], + function (ctx, ref) { + var k = ref[0]; + var v = ref[1]; + var a = ctx.properties()[k.value]; + var b = v.value; + return typeof a === typeof b && a < b; + } + ], + 'filter-id-<': [ + BooleanType, + [ValueType], + function (ctx, ref) { + var v = ref[0]; + var a = ctx.id(); + var b = v.value; + return typeof a === typeof b && a < b; + } + ], + 'filter->': [ + BooleanType, + [ + StringType, + ValueType + ], + function (ctx, ref) { + var k = ref[0]; + var v = ref[1]; + var a = ctx.properties()[k.value]; + var b = v.value; + return typeof a === typeof b && a > b; + } + ], + 'filter-id->': [ + BooleanType, + [ValueType], + function (ctx, ref) { + var v = ref[0]; + var a = ctx.id(); + var b = v.value; + return typeof a === typeof b && a > b; + } + ], + 'filter-<=': [ + BooleanType, + [ + StringType, + ValueType + ], + function (ctx, ref) { + var k = ref[0]; + var v = ref[1]; + var a = ctx.properties()[k.value]; + var b = v.value; + return typeof a === typeof b && a <= b; + } + ], + 'filter-id-<=': [ + BooleanType, + [ValueType], + function (ctx, ref) { + var v = ref[0]; + var a = ctx.id(); + var b = v.value; + return typeof a === typeof b && a <= b; + } + ], + 'filter->=': [ + BooleanType, + [ + StringType, + ValueType + ], + function (ctx, ref) { + var k = ref[0]; + var v = ref[1]; + var a = ctx.properties()[k.value]; + var b = v.value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-id->=': [ + BooleanType, + [ValueType], + function (ctx, ref) { + var v = ref[0]; + var a = ctx.id(); + var b = v.value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-has': [ + BooleanType, + [ValueType], + function (ctx, ref) { + var k = ref[0]; + return k.value in ctx.properties(); + } + ], + 'filter-has-id': [ + BooleanType, + [], + function (ctx) { + return ctx.id() !== null && ctx.id() !== undefined; + } + ], + 'filter-type-in': [ + BooleanType, + [array(StringType)], + function (ctx, ref) { + var v = ref[0]; + return v.value.indexOf(ctx.geometryType()) >= 0; + } + ], + 'filter-id-in': [ + BooleanType, + [array(ValueType)], + function (ctx, ref) { + var v = ref[0]; + return v.value.indexOf(ctx.id()) >= 0; + } + ], + 'filter-in-small': [ + BooleanType, + [ + StringType, + array(ValueType) + ], + function (ctx, ref) { + var k = ref[0]; + var v = ref[1]; + return v.value.indexOf(ctx.properties()[k.value]) >= 0; + } + ], + 'filter-in-large': [ + BooleanType, + [ + StringType, + array(ValueType) + ], + function (ctx, ref) { + var k = ref[0]; + var v = ref[1]; + return binarySearch(ctx.properties()[k.value], v.value, 0, v.value.length - 1); + } + ], + 'all': { + type: BooleanType, + overloads: [ + [ + [ + BooleanType, + BooleanType + ], + function (ctx, ref) { + var a = ref[0]; + var b = ref[1]; + return a.evaluate(ctx) && b.evaluate(ctx); + } + ], + [ + varargs(BooleanType), + function (ctx, args) { + for (var i = 0, list = args; i < list.length; i += 1) { + var arg = list[i]; + if (!arg.evaluate(ctx)) { + return false; + } + } + return true; + } + ] + ] + }, + 'any': { + type: BooleanType, + overloads: [ + [ + [ + BooleanType, + BooleanType + ], + function (ctx, ref) { + var a = ref[0]; + var b = ref[1]; + return a.evaluate(ctx) || b.evaluate(ctx); + } + ], + [ + varargs(BooleanType), + function (ctx, args) { + for (var i = 0, list = args; i < list.length; i += 1) { + var arg = list[i]; + if (arg.evaluate(ctx)) { + return true; + } + } + return false; + } + ] + ] + }, + '!': [ + BooleanType, + [BooleanType], + function (ctx, ref) { + var b = ref[0]; + return !b.evaluate(ctx); + } + ], + 'is-supported-script': [ + BooleanType, + [StringType], + function (ctx, ref) { + var s = ref[0]; + var isSupportedScript = ctx.globals && ctx.globals.isSupportedScript; + if (isSupportedScript) { + return isSupportedScript(s.evaluate(ctx)); + } + return true; + } + ], + 'upcase': [ + StringType, + [StringType], + function (ctx, ref) { + var s = ref[0]; + return s.evaluate(ctx).toUpperCase(); + } + ], + 'downcase': [ + StringType, + [StringType], + function (ctx, ref) { + var s = ref[0]; + return s.evaluate(ctx).toLowerCase(); + } + ], + 'concat': [ + StringType, + varargs(ValueType), + function (ctx, args) { + return args.map(function (arg) { + return toString$1(arg.evaluate(ctx)); + }).join(''); + } + ], + 'resolved-locale': [ + StringType, + [CollatorType], + function (ctx, ref) { + var collator = ref[0]; + return collator.evaluate(ctx).resolvedLocale(); + } + ] + }); + + function success(value) { + return { + result: 'success', + value: value + }; + } + function error(value) { + return { + result: 'error', + value: value + }; + } + + function supportsPropertyExpression(spec) { + return spec['property-type'] === 'data-driven' || spec['property-type'] === 'cross-faded-data-driven'; + } + function supportsZoomExpression(spec) { + return !!spec.expression && spec.expression.parameters.indexOf('zoom') > -1; + } + function supportsInterpolation(spec) { + return !!spec.expression && spec.expression.interpolated; + } + + function getType(val) { + if (val instanceof Number) { + return 'number'; + } else if (val instanceof String) { + return 'string'; + } else if (val instanceof Boolean) { + return 'boolean'; + } else if (Array.isArray(val)) { + return 'array'; + } else if (val === null) { + return 'null'; + } else { + return typeof val; + } + } + + function isFunction$1(value) { + return typeof value === 'object' && value !== null && !Array.isArray(value); + } + function identityFunction(x) { + return x; + } + function createFunction(parameters, propertySpec) { + var isColor = propertySpec.type === 'color'; + var zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === 'object'; + var featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + var zoomDependent = zoomAndFeatureDependent || !featureDependent; + var type = parameters.type || (supportsInterpolation(propertySpec) ? 'exponential' : 'interval'); + if (isColor) { + parameters = extend({}, parameters); + if (parameters.stops) { + parameters.stops = parameters.stops.map(function (stop) { + return [ + stop[0], + Color.parse(stop[1]) + ]; + }); + } + if (parameters.default) { + parameters.default = Color.parse(parameters.default); + } else { + parameters.default = Color.parse(propertySpec.default); + } + } + if (parameters.colorSpace && parameters.colorSpace !== 'rgb' && !colorSpaces[parameters.colorSpace]) { + throw new Error('Unknown color space: ' + parameters.colorSpace); + } + var innerFun; + var hashedStops; + var categoricalKeyType; + if (type === 'exponential') { + innerFun = evaluateExponentialFunction; + } else if (type === 'interval') { + innerFun = evaluateIntervalFunction; + } else if (type === 'categorical') { + innerFun = evaluateCategoricalFunction; + hashedStops = Object.create(null); + for (var i = 0, list = parameters.stops; i < list.length; i += 1) { + var stop = list[i]; + hashedStops[stop[0]] = stop[1]; + } + categoricalKeyType = typeof parameters.stops[0][0]; + } else if (type === 'identity') { + innerFun = evaluateIdentityFunction; + } else { + throw new Error('Unknown function type "' + type + '"'); + } + if (zoomAndFeatureDependent) { + var featureFunctions = {}; + var zoomStops = []; + for (var s = 0; s < parameters.stops.length; s++) { + var stop$1 = parameters.stops[s]; + var zoom = stop$1[0].zoom; + if (featureFunctions[zoom] === undefined) { + featureFunctions[zoom] = { + zoom: zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default, + stops: [] + }; + zoomStops.push(zoom); + } + featureFunctions[zoom].stops.push([ + stop$1[0].value, + stop$1[1] + ]); + } + var featureFunctionStops = []; + for (var i$1 = 0, list$1 = zoomStops; i$1 < list$1.length; i$1 += 1) { + var z = list$1[i$1]; + featureFunctionStops.push([ + featureFunctions[z].zoom, + createFunction(featureFunctions[z], propertySpec) + ]); + } + var interpolationType = { name: 'linear' }; + return { + kind: 'composite', + interpolationType: interpolationType, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), + zoomStops: featureFunctionStops.map(function (s) { + return s[0]; + }), + evaluate: function evaluate(ref, properties) { + var zoom = ref.zoom; + return evaluateExponentialFunction({ + stops: featureFunctionStops, + base: parameters.base + }, propertySpec, zoom).evaluate(zoom, properties); + } + }; + } else if (zoomDependent) { + var interpolationType$1 = type === 'exponential' ? { + name: 'exponential', + base: parameters.base !== undefined ? parameters.base : 1 + } : null; + return { + kind: 'camera', + interpolationType: interpolationType$1, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType$1), + zoomStops: parameters.stops.map(function (s) { + return s[0]; + }), + evaluate: function (ref) { + var zoom = ref.zoom; + return innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType); + } + }; + } else { + return { + kind: 'source', + evaluate: function evaluate(_, feature) { + var value = feature && feature.properties ? feature.properties[parameters.property] : undefined; + if (value === undefined) { + return coalesce(parameters.default, propertySpec.default); + } + return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType); + } + }; + } + } + function coalesce(a, b, c) { + if (a !== undefined) { + return a; + } + if (b !== undefined) { + return b; + } + if (c !== undefined) { + return c; + } + } + function evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) { + var evaluated = typeof input === keyType ? hashedStops[input] : undefined; + return coalesce(evaluated, parameters.default, propertySpec.default); + } + function evaluateIntervalFunction(parameters, propertySpec, input) { + if (getType(input) !== 'number') { + return coalesce(parameters.default, propertySpec.default); + } + var n = parameters.stops.length; + if (n === 1) { + return parameters.stops[0][1]; + } + if (input <= parameters.stops[0][0]) { + return parameters.stops[0][1]; + } + if (input >= parameters.stops[n - 1][0]) { + return parameters.stops[n - 1][1]; + } + var index = findStopLessThanOrEqualTo(parameters.stops.map(function (stop) { + return stop[0]; + }), input); + return parameters.stops[index][1]; + } + function evaluateExponentialFunction(parameters, propertySpec, input) { + var base = parameters.base !== undefined ? parameters.base : 1; + if (getType(input) !== 'number') { + return coalesce(parameters.default, propertySpec.default); + } + var n = parameters.stops.length; + if (n === 1) { + return parameters.stops[0][1]; + } + if (input <= parameters.stops[0][0]) { + return parameters.stops[0][1]; + } + if (input >= parameters.stops[n - 1][0]) { + return parameters.stops[n - 1][1]; + } + var index = findStopLessThanOrEqualTo(parameters.stops.map(function (stop) { + return stop[0]; + }), input); + var t = interpolationFactor(input, base, parameters.stops[index][0], parameters.stops[index + 1][0]); + var outputLower = parameters.stops[index][1]; + var outputUpper = parameters.stops[index + 1][1]; + var interp = interpolate[propertySpec.type] || identityFunction; + if (parameters.colorSpace && parameters.colorSpace !== 'rgb') { + var colorspace = colorSpaces[parameters.colorSpace]; + interp = function (a, b) { + return colorspace.reverse(colorspace.interpolate(colorspace.forward(a), colorspace.forward(b), t)); + }; + } + if (typeof outputLower.evaluate === 'function') { + return { + evaluate: function evaluate() { + var args = [], len = arguments.length; + while (len--) + args[len] = arguments[len]; + var evaluatedLower = outputLower.evaluate.apply(undefined, args); + var evaluatedUpper = outputUpper.evaluate.apply(undefined, args); + if (evaluatedLower === undefined || evaluatedUpper === undefined) { + return undefined; + } + return interp(evaluatedLower, evaluatedUpper, t); + } + }; + } + return interp(outputLower, outputUpper, t); + } + function evaluateIdentityFunction(parameters, propertySpec, input) { + if (propertySpec.type === 'color') { + input = Color.parse(input); + } else if (propertySpec.type === 'formatted') { + input = Formatted.fromString(input.toString()); + } else if (propertySpec.type === 'resolvedImage') { + input = ResolvedImage.fromString(input.toString()); + } else if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) { + input = undefined; + } + return coalesce(input, parameters.default, propertySpec.default); + } + function interpolationFactor(input, base, lowerValue, upperValue) { + var difference = upperValue - lowerValue; + var progress = input - lowerValue; + if (difference === 0) { + return 0; + } else if (base === 1) { + return progress / difference; + } else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } + } + + var StyleExpression = function StyleExpression(expression, propertySpec) { + this.expression = expression; + this._warningHistory = {}; + this._evaluator = new EvaluationContext(); + this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null; + this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null; + }; + StyleExpression.prototype.evaluateWithoutErrorHandling = function evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + this._evaluator.globals = globals; + this._evaluator.feature = feature; + this._evaluator.featureState = featureState; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection; + return this.expression.evaluate(this._evaluator); + }; + StyleExpression.prototype.evaluate = function evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + this._evaluator.globals = globals; + this._evaluator.feature = feature || null; + this._evaluator.featureState = featureState || null; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection || null; + try { + var val = this.expression.evaluate(this._evaluator); + if (val === null || val === undefined || typeof val === 'number' && val !== val) { + return this._defaultValue; + } + if (this._enumValues && !(val in this._enumValues)) { + throw new RuntimeError('Expected value to be one of ' + Object.keys(this._enumValues).map(function (v) { + return JSON.stringify(v); + }).join(', ') + ', but found ' + JSON.stringify(val) + ' instead.'); + } + return val; + } catch (e) { + if (!this._warningHistory[e.message]) { + this._warningHistory[e.message] = true; + if (typeof console !== 'undefined') { + console.warn(e.message); + } + } + return this._defaultValue; + } + }; + function isExpression(expression) { + return Array.isArray(expression) && expression.length > 0 && typeof expression[0] === 'string' && expression[0] in expressions; + } + function createExpression(expression, propertySpec) { + var parser = new ParsingContext(expressions, [], propertySpec ? getExpectedType(propertySpec) : undefined); + var parsed = parser.parse(expression, undefined, undefined, undefined, propertySpec && propertySpec.type === 'string' ? { typeAnnotation: 'coerce' } : undefined); + if (!parsed) { + return error(parser.errors); + } + return success(new StyleExpression(parsed, propertySpec)); + } + var ZoomConstantExpression = function ZoomConstantExpression(kind, expression) { + this.kind = kind; + this._styleExpression = expression; + this.isStateDependent = kind !== 'constant' && !isStateConstant(expression.expression); + }; + ZoomConstantExpression.prototype.evaluateWithoutErrorHandling = function evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); + }; + ZoomConstantExpression.prototype.evaluate = function evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); + }; + var ZoomDependentExpression = function ZoomDependentExpression(kind, expression, zoomStops, interpolationType) { + this.kind = kind; + this.zoomStops = zoomStops; + this._styleExpression = expression; + this.isStateDependent = kind !== 'camera' && !isStateConstant(expression.expression); + this.interpolationType = interpolationType; + }; + ZoomDependentExpression.prototype.evaluateWithoutErrorHandling = function evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); + }; + ZoomDependentExpression.prototype.evaluate = function evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); + }; + ZoomDependentExpression.prototype.interpolationFactor = function interpolationFactor(input, lower, upper) { + if (this.interpolationType) { + return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper); + } else { + return 0; + } + }; + function createPropertyExpression(expression, propertySpec) { + expression = createExpression(expression, propertySpec); + if (expression.result === 'error') { + return expression; + } + var parsed = expression.value.expression; + var isFeatureConstant$1 = isFeatureConstant(parsed); + if (!isFeatureConstant$1 && !supportsPropertyExpression(propertySpec)) { + return error([new ParsingError('', 'data expressions not supported')]); + } + var isZoomConstant = isGlobalPropertyConstant(parsed, ['zoom']); + if (!isZoomConstant && !supportsZoomExpression(propertySpec)) { + return error([new ParsingError('', 'zoom expressions not supported')]); + } + var zoomCurve = findZoomCurve(parsed); + if (!zoomCurve && !isZoomConstant) { + return error([new ParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]); + } else if (zoomCurve instanceof ParsingError) { + return error([zoomCurve]); + } else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) { + return error([new ParsingError('', '"interpolate" expressions cannot be used with this property')]); + } + if (!zoomCurve) { + return success(isFeatureConstant$1 ? new ZoomConstantExpression('constant', expression.value) : new ZoomConstantExpression('source', expression.value)); + } + var interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined; + return success(isFeatureConstant$1 ? new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType) : new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType)); + } + var StylePropertyFunction = function StylePropertyFunction(parameters, specification) { + this._parameters = parameters; + this._specification = specification; + extend(this, createFunction(this._parameters, this._specification)); + }; + StylePropertyFunction.deserialize = function deserialize(serialized) { + return new StylePropertyFunction(serialized._parameters, serialized._specification); + }; + StylePropertyFunction.serialize = function serialize(input) { + return { + _parameters: input._parameters, + _specification: input._specification + }; + }; + function normalizePropertyExpression(value, specification) { + if (isFunction$1(value)) { + return new StylePropertyFunction(value, specification); + } else if (isExpression(value)) { + var expression = createPropertyExpression(value, specification); + if (expression.result === 'error') { + throw new Error(expression.value.map(function (err) { + return err.key + ': ' + err.message; + }).join(', ')); + } + return expression.value; + } else { + var constant = value; + if (typeof value === 'string' && specification.type === 'color') { + constant = Color.parse(value); + } + return { + kind: 'constant', + evaluate: function () { + return constant; + } + }; + } + } + function findZoomCurve(expression) { + var result = null; + if (expression instanceof Let) { + result = findZoomCurve(expression.result); + } else if (expression instanceof Coalesce) { + for (var i = 0, list = expression.args; i < list.length; i += 1) { + var arg = list[i]; + result = findZoomCurve(arg); + if (result) { + break; + } + } + } else if ((expression instanceof Step || expression instanceof Interpolate) && expression.input instanceof CompoundExpression && expression.input.name === 'zoom') { + result = expression; + } + if (result instanceof ParsingError) { + return result; + } + expression.eachChild(function (child) { + var childResult = findZoomCurve(child); + if (childResult instanceof ParsingError) { + result = childResult; + } else if (!result && childResult) { + result = new ParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'); + } else if (result && childResult && result !== childResult) { + result = new ParsingError('', 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'); + } + }); + return result; + } + function getExpectedType(spec) { + var types = { + color: ColorType, + string: StringType, + number: NumberType, + enum: StringType, + boolean: BooleanType, + formatted: FormattedType, + resolvedImage: ResolvedImageType + }; + if (spec.type === 'array') { + return array(types[spec.value] || ValueType, spec.length); + } + return types[spec.type]; + } + function getDefaultValue(spec) { + if (spec.type === 'color' && isFunction$1(spec.default)) { + return new Color(0, 0, 0, 0); + } else if (spec.type === 'color') { + return Color.parse(spec.default) || null; + } else if (spec.default === undefined) { + return null; + } else { + return spec.default; + } + } + + function convertLiteral(value) { + return typeof value === 'object' ? [ + 'literal', + value + ] : value; + } + function convertFunction(parameters, propertySpec) { + var stops = parameters.stops; + if (!stops) { + return convertIdentityFunction(parameters, propertySpec); + } + var zoomAndFeatureDependent = stops && typeof stops[0][0] === 'object'; + var featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + var zoomDependent = zoomAndFeatureDependent || !featureDependent; + stops = stops.map(function (stop) { + if (!featureDependent && propertySpec.tokens && typeof stop[1] === 'string') { + return [ + stop[0], + convertTokenString(stop[1]) + ]; + } + return [ + stop[0], + convertLiteral(stop[1]) + ]; + }); + if (zoomAndFeatureDependent) { + return convertZoomAndPropertyFunction(parameters, propertySpec, stops); + } else if (zoomDependent) { + return convertZoomFunction(parameters, propertySpec, stops); + } else { + return convertPropertyFunction(parameters, propertySpec, stops); + } + } + function convertIdentityFunction(parameters, propertySpec) { + var get = [ + 'get', + parameters.property + ]; + if (parameters.default === undefined) { + return propertySpec.type === 'string' ? [ + 'string', + get + ] : get; + } else if (propertySpec.type === 'enum') { + return [ + 'match', + get, + Object.keys(propertySpec.values), + get, + parameters.default + ]; + } else { + var expression = [ + propertySpec.type === 'color' ? 'to-color' : propertySpec.type, + get, + convertLiteral(parameters.default) + ]; + if (propertySpec.type === 'array') { + expression.splice(1, 0, propertySpec.value, propertySpec.length || null); + } + return expression; + } + } + function getInterpolateOperator(parameters) { + switch (parameters.colorSpace) { + case 'hcl': + return 'interpolate-hcl'; + case 'lab': + return 'interpolate-lab'; + default: + return 'interpolate'; + } + } + function convertZoomAndPropertyFunction(parameters, propertySpec, stops) { + var featureFunctionParameters = {}; + var featureFunctionStops = {}; + var zoomStops = []; + for (var s = 0; s < stops.length; s++) { + var stop = stops[s]; + var zoom = stop[0].zoom; + if (featureFunctionParameters[zoom] === undefined) { + featureFunctionParameters[zoom] = { + zoom: zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default + }; + featureFunctionStops[zoom] = []; + zoomStops.push(zoom); + } + featureFunctionStops[zoom].push([ + stop[0].value, + stop[1] + ]); + } + var functionType = getFunctionType({}, propertySpec); + if (functionType === 'exponential') { + var expression = [ + getInterpolateOperator(parameters), + ['linear'], + ['zoom'] + ]; + for (var i = 0, list = zoomStops; i < list.length; i += 1) { + var z = list[i]; + var output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]); + appendStopPair(expression, z, output, false); + } + return expression; + } else { + var expression$1 = [ + 'step', + ['zoom'] + ]; + for (var i$1 = 0, list$1 = zoomStops; i$1 < list$1.length; i$1 += 1) { + var z$1 = list$1[i$1]; + var output$1 = convertPropertyFunction(featureFunctionParameters[z$1], propertySpec, featureFunctionStops[z$1]); + appendStopPair(expression$1, z$1, output$1, true); + } + fixupDegenerateStepCurve(expression$1); + return expression$1; + } + } + function coalesce$1(a, b) { + if (a !== undefined) { + return a; + } + if (b !== undefined) { + return b; + } + } + function getFallback(parameters, propertySpec) { + var defaultValue = convertLiteral(coalesce$1(parameters.default, propertySpec.default)); + if (defaultValue === undefined && propertySpec.type === 'resolvedImage') { + return ''; + } + return defaultValue; + } + function convertPropertyFunction(parameters, propertySpec, stops) { + var type = getFunctionType(parameters, propertySpec); + var get = [ + 'get', + parameters.property + ]; + if (type === 'categorical' && typeof stops[0][0] === 'boolean') { + var expression = ['case']; + for (var i = 0, list = stops; i < list.length; i += 1) { + var stop = list[i]; + expression.push([ + '==', + get, + stop[0] + ], stop[1]); + } + expression.push(getFallback(parameters, propertySpec)); + return expression; + } else if (type === 'categorical') { + var expression$1 = [ + 'match', + get + ]; + for (var i$1 = 0, list$1 = stops; i$1 < list$1.length; i$1 += 1) { + var stop$1 = list$1[i$1]; + appendStopPair(expression$1, stop$1[0], stop$1[1], false); + } + expression$1.push(getFallback(parameters, propertySpec)); + return expression$1; + } else if (type === 'interval') { + var expression$2 = [ + 'step', + [ + 'number', + get + ] + ]; + for (var i$2 = 0, list$2 = stops; i$2 < list$2.length; i$2 += 1) { + var stop$2 = list$2[i$2]; + appendStopPair(expression$2, stop$2[0], stop$2[1], true); + } + fixupDegenerateStepCurve(expression$2); + return parameters.default === undefined ? expression$2 : [ + 'case', + [ + '==', + [ + 'typeof', + get + ], + 'number' + ], + expression$2, + convertLiteral(parameters.default) + ]; + } else if (type === 'exponential') { + var base = parameters.base !== undefined ? parameters.base : 1; + var expression$3 = [ + getInterpolateOperator(parameters), + base === 1 ? ['linear'] : [ + 'exponential', + base + ], + [ + 'number', + get + ] + ]; + for (var i$3 = 0, list$3 = stops; i$3 < list$3.length; i$3 += 1) { + var stop$3 = list$3[i$3]; + appendStopPair(expression$3, stop$3[0], stop$3[1], false); + } + return parameters.default === undefined ? expression$3 : [ + 'case', + [ + '==', + [ + 'typeof', + get + ], + 'number' + ], + expression$3, + convertLiteral(parameters.default) + ]; + } else { + throw new Error('Unknown property function type ' + type); + } + } + function convertZoomFunction(parameters, propertySpec, stops, input) { + if (input === void 0) + input = ['zoom']; + var type = getFunctionType(parameters, propertySpec); + var expression; + var isStep = false; + if (type === 'interval') { + expression = [ + 'step', + input + ]; + isStep = true; + } else if (type === 'exponential') { + var base = parameters.base !== undefined ? parameters.base : 1; + expression = [ + getInterpolateOperator(parameters), + base === 1 ? ['linear'] : [ + 'exponential', + base + ], + input + ]; + } else { + throw new Error('Unknown zoom function type "' + type + '"'); + } + for (var i = 0, list = stops; i < list.length; i += 1) { + var stop = list[i]; + appendStopPair(expression, stop[0], stop[1], isStep); + } + fixupDegenerateStepCurve(expression); + return expression; + } + function fixupDegenerateStepCurve(expression) { + if (expression[0] === 'step' && expression.length === 3) { + expression.push(0); + expression.push(expression[3]); + } + } + function appendStopPair(curve, input, output, isStep) { + if (curve.length > 3 && input === curve[curve.length - 2]) { + return; + } + if (!(isStep && curve.length === 2)) { + curve.push(input); + } + curve.push(output); + } + function getFunctionType(parameters, propertySpec) { + if (parameters.type) { + return parameters.type; + } else { + return propertySpec.expression.interpolated ? 'exponential' : 'interval'; + } + } + function convertTokenString(s) { + var result = ['concat']; + var re = /{([^{}]+)}/g; + var pos = 0; + for (var match = re.exec(s); match !== null; match = re.exec(s)) { + var literal = s.slice(pos, re.lastIndex - match[0].length); + pos = re.lastIndex; + if (literal.length > 0) { + result.push(literal); + } + result.push([ + 'get', + match[1] + ]); + } + if (result.length === 1) { + return s; + } + if (pos < s.length) { + result.push(s.slice(pos)); + } else if (result.length === 2) { + return [ + 'to-string', + result[1] + ]; + } + return result; + } + + function isExpressionFilter(filter) { + if (filter === true || filter === false) { + return true; + } + if (!Array.isArray(filter) || filter.length === 0) { + return false; + } + switch (filter[0]) { + case 'has': + return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type'; + case 'in': + return filter.length >= 3 && (typeof filter[1] !== 'string' || Array.isArray(filter[2])); + case '!in': + case '!has': + case 'none': + return false; + case '==': + case '!=': + case '>': + case '>=': + case '<': + case '<=': + return filter.length !== 3 || (Array.isArray(filter[1]) || Array.isArray(filter[2])); + case 'any': + case 'all': + for (var i = 0, list = filter.slice(1); i < list.length; i += 1) { + var f = list[i]; + if (!isExpressionFilter(f) && typeof f !== 'boolean') { + return false; + } + } + return true; + default: + return true; + } + } + var filterSpec = { + 'type': 'boolean', + 'default': false, + 'transition': false, + 'property-type': 'data-driven', + 'expression': { + 'interpolated': false, + 'parameters': [ + 'zoom', + 'feature' + ] + } + }; + function createFilter(filter) { + if (filter === null || filter === undefined) { + return { + filter: function () { + return true; + }, + needGeometry: false + }; + } + if (!isExpressionFilter(filter)) { + filter = convertFilter(filter); + } + var compiled = createExpression(filter, filterSpec); + if (compiled.result === 'error') { + throw new Error(compiled.value.map(function (err) { + return err.key + ': ' + err.message; + }).join(', ')); + } else { + var needGeometry = geometryNeeded(filter); + return { + filter: function (globalProperties, feature, canonical) { + return compiled.value.evaluate(globalProperties, feature, {}, canonical); + }, + needGeometry: needGeometry + }; + } + } + function compare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; + } + function geometryNeeded(filter) { + if (!Array.isArray(filter)) { + return false; + } + if (filter[0] === 'within') { + return true; + } + for (var index = 1; index < filter.length; index++) { + if (geometryNeeded(filter[index])) { + return true; + } + } + return false; + } + function convertFilter(filter) { + if (!filter) { + return true; + } + var op = filter[0]; + if (filter.length <= 1) { + return op !== 'any'; + } + var converted = op === '==' ? convertComparisonOp(filter[1], filter[2], '==') : op === '!=' ? convertNegation(convertComparisonOp(filter[1], filter[2], '==')) : op === '<' || op === '>' || op === '<=' || op === '>=' ? convertComparisonOp(filter[1], filter[2], op) : op === 'any' ? convertDisjunctionOp(filter.slice(1)) : op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter)) : op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter).map(convertNegation)) : op === 'in' ? convertInOp(filter[1], filter.slice(2)) : op === '!in' ? convertNegation(convertInOp(filter[1], filter.slice(2))) : op === 'has' ? convertHasOp(filter[1]) : op === '!has' ? convertNegation(convertHasOp(filter[1])) : op === 'within' ? filter : true; + return converted; + } + function convertComparisonOp(property, value, op) { + switch (property) { + case '$type': + return [ + 'filter-type-' + op, + value + ]; + case '$id': + return [ + 'filter-id-' + op, + value + ]; + default: + return [ + 'filter-' + op, + property, + value + ]; + } + } + function convertDisjunctionOp(filters) { + return ['any'].concat(filters.map(convertFilter)); + } + function convertInOp(property, values) { + if (values.length === 0) { + return false; + } + switch (property) { + case '$type': + return [ + 'filter-type-in', + [ + 'literal', + values + ] + ]; + case '$id': + return [ + 'filter-id-in', + [ + 'literal', + values + ] + ]; + default: + if (values.length > 200 && !values.some(function (v) { + return typeof v !== typeof values[0]; + })) { + return [ + 'filter-in-large', + property, + [ + 'literal', + values.sort(compare) + ] + ]; + } else { + return [ + 'filter-in-small', + property, + [ + 'literal', + values + ] + ]; + } + } + } + function convertHasOp(property) { + switch (property) { + case '$type': + return true; + case '$id': + return ['filter-has-id']; + default: + return [ + 'filter-has', + property + ]; + } + } + function convertNegation(filter) { + return [ + '!', + filter + ]; + } + + function convertFilter$1(filter) { + return _convertFilter(filter, {}); + } + function _convertFilter(filter, expectedTypes) { + var ref$1; + if (isExpressionFilter(filter)) { + return filter; + } + if (!filter) { + return true; + } + var op = filter[0]; + if (filter.length <= 1) { + return op !== 'any'; + } + var converted; + if (op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=') { + var ref = filter; + var property = ref[1]; + var value = ref[2]; + converted = convertComparisonOp$1(property, value, op, expectedTypes); + } else if (op === 'any') { + var children = filter.slice(1).map(function (f) { + var types = {}; + var child = _convertFilter(f, types); + var typechecks = runtimeTypeChecks(types); + return typechecks === true ? child : [ + 'case', + typechecks, + child, + false + ]; + }); + return ['any'].concat(children); + } else if (op === 'all') { + var children$1 = filter.slice(1).map(function (f) { + return _convertFilter(f, expectedTypes); + }); + return children$1.length > 1 ? ['all'].concat(children$1) : (ref$1 = []).concat.apply(ref$1, children$1); + } else if (op === 'none') { + return [ + '!', + _convertFilter(['any'].concat(filter.slice(1)), {}) + ]; + } else if (op === 'in') { + converted = convertInOp$1(filter[1], filter.slice(2)); + } else if (op === '!in') { + converted = convertInOp$1(filter[1], filter.slice(2), true); + } else if (op === 'has') { + converted = convertHasOp$1(filter[1]); + } else if (op === '!has') { + converted = [ + '!', + convertHasOp$1(filter[1]) + ]; + } else { + converted = true; + } + return converted; + } + function runtimeTypeChecks(expectedTypes) { + var conditions = []; + for (var property in expectedTypes) { + var get = property === '$id' ? ['id'] : [ + 'get', + property + ]; + conditions.push([ + '==', + [ + 'typeof', + get + ], + expectedTypes[property] + ]); + } + if (conditions.length === 0) { + return true; + } + if (conditions.length === 1) { + return conditions[0]; + } + return ['all'].concat(conditions); + } + function convertComparisonOp$1(property, value, op, expectedTypes) { + var get; + if (property === '$type') { + return [ + op, + ['geometry-type'], + value + ]; + } else if (property === '$id') { + get = ['id']; + } else { + get = [ + 'get', + property + ]; + } + if (expectedTypes && value !== null) { + var type = typeof value; + expectedTypes[property] = type; + } + if (op === '==' && property !== '$id' && value === null) { + return [ + 'all', + [ + 'has', + property + ], + [ + '==', + get, + null + ] + ]; + } else if (op === '!=' && property !== '$id' && value === null) { + return [ + 'any', + [ + '!', + [ + 'has', + property + ] + ], + [ + '!=', + get, + null + ] + ]; + } + return [ + op, + get, + value + ]; + } + function convertInOp$1(property, values, negate) { + if (negate === void 0) + negate = false; + if (values.length === 0) { + return negate; + } + var get; + if (property === '$type') { + get = ['geometry-type']; + } else if (property === '$id') { + get = ['id']; + } else { + get = [ + 'get', + property + ]; + } + var uniformTypes = true; + var type = typeof values[0]; + for (var i = 0, list = values; i < list.length; i += 1) { + var value = list[i]; + if (typeof value !== type) { + uniformTypes = false; + break; + } + } + if (uniformTypes && (type === 'string' || type === 'number')) { + var uniqueValues = values.sort().filter(function (v, i) { + return i === 0 || values[i - 1] !== v; + }); + return [ + 'match', + get, + uniqueValues, + !negate, + negate + ]; + } + return [negate ? 'all' : 'any'].concat(values.map(function (v) { + return [ + negate ? '!=' : '==', + get, + v + ]; + })); + } + function convertHasOp$1(property) { + if (property === '$type') { + return true; + } else if (property === '$id') { + return [ + '!=', + ['id'], + null + ]; + } else { + return [ + 'has', + property + ]; + } + } + + function migrateToExpressions (style) { + var converted = []; + eachLayer(style, function (layer) { + if (layer.filter) { + layer.filter = convertFilter$1(layer.filter); + } + }); + eachProperty(style, { + paint: true, + layout: true + }, function (ref) { + var path = ref.path; + var value = ref.value; + var reference = ref.reference; + var set = ref.set; + if (isExpression(value)) { + return; + } + if (typeof value === 'object' && !Array.isArray(value)) { + set(convertFunction(value, reference)); + converted.push(path.join('.')); + } else if (reference.tokens && typeof value === 'string') { + set(convertTokenString(value)); + } + }); + return style; + } + + function migrate (style) { + var migrated = false; + if (style.version === 7) { + style = migrateToV8(style); + migrated = true; + } + if (style.version === 8) { + migrated = migrateToExpressions(style); + migrated = true; + } + if (!migrated) { + throw new Error('cannot migrate from', style.version); + } + return style; + } + + function composite (style) { + var styleIDs = []; + var sourceIDs = []; + var compositedSourceLayers = []; + for (var id in style.sources) { + var source = style.sources[id]; + if (source.type !== 'vector') { + continue; + } + var match = /^mapbox:\/\/(.*)/.exec(source.url); + if (!match) { + continue; + } + styleIDs.push(id); + sourceIDs.push(match[1]); + } + if (styleIDs.length < 2) { + return style; + } + styleIDs.forEach(function (id) { + delete style.sources[id]; + }); + var compositeID = sourceIDs.join(','); + style.sources[compositeID] = { + 'type': 'vector', + 'url': 'mapbox://' + compositeID + }; + style.layers.forEach(function (layer) { + if (styleIDs.indexOf(layer.source) >= 0) { + layer.source = compositeID; + if ('source-layer' in layer) { + if (compositedSourceLayers.indexOf(layer['source-layer']) >= 0) { + throw new Error('Conflicting source layer names'); + } else { + compositedSourceLayers.push(layer['source-layer']); + } + } + } + }); + return style; + } + + var refProperties = [ + 'type', + 'source', + 'source-layer', + 'minzoom', + 'maxzoom', + 'filter', + 'layout' + ]; + + function deref(layer, parent) { + var result = {}; + for (var k in layer) { + if (k !== 'ref') { + result[k] = layer[k]; + } + } + refProperties.forEach(function (k) { + if (k in parent) { + result[k] = parent[k]; + } + }); + return result; + } + function derefLayers(layers) { + layers = layers.slice(); + var map = Object.create(null); + for (var i = 0; i < layers.length; i++) { + map[layers[i].id] = layers[i]; + } + for (var i$1 = 0; i$1 < layers.length; i$1++) { + if ('ref' in layers[i$1]) { + layers[i$1] = deref(layers[i$1], map[layers[i$1].ref]); + } + } + return layers; + } + + function deepEqual(a, b) { + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) { + return false; + } + for (var i = 0; i < a.length; i++) { + if (!deepEqual(a[i], b[i])) { + return false; + } + } + return true; + } + if (typeof a === 'object' && a !== null && b !== null) { + if (!(typeof b === 'object')) { + return false; + } + var keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) { + return false; + } + for (var key in a) { + if (!deepEqual(a[key], b[key])) { + return false; + } + } + return true; + } + return a === b; + } + + var operations = { + setStyle: 'setStyle', + addLayer: 'addLayer', + removeLayer: 'removeLayer', + setPaintProperty: 'setPaintProperty', + setLayoutProperty: 'setLayoutProperty', + setFilter: 'setFilter', + addSource: 'addSource', + removeSource: 'removeSource', + setGeoJSONSourceData: 'setGeoJSONSourceData', + setLayerZoomRange: 'setLayerZoomRange', + setLayerProperty: 'setLayerProperty', + setCenter: 'setCenter', + setZoom: 'setZoom', + setBearing: 'setBearing', + setPitch: 'setPitch', + setSprite: 'setSprite', + setGlyphs: 'setGlyphs', + setTransition: 'setTransition', + setLight: 'setLight' + }; + function addSource(sourceId, after, commands) { + commands.push({ + command: operations.addSource, + args: [ + sourceId, + after[sourceId] + ] + }); + } + function removeSource(sourceId, commands, sourcesRemoved) { + commands.push({ + command: operations.removeSource, + args: [sourceId] + }); + sourcesRemoved[sourceId] = true; + } + function updateSource(sourceId, after, commands, sourcesRemoved) { + removeSource(sourceId, commands, sourcesRemoved); + addSource(sourceId, after, commands); + } + function canUpdateGeoJSON(before, after, sourceId) { + var prop; + for (prop in before[sourceId]) { + if (!before[sourceId].hasOwnProperty(prop)) { + continue; + } + if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + for (prop in after[sourceId]) { + if (!after[sourceId].hasOwnProperty(prop)) { + continue; + } + if (prop !== 'data' && !deepEqual(before[sourceId][prop], after[sourceId][prop])) { + return false; + } + } + return true; + } + function diffSources(before, after, commands, sourcesRemoved) { + before = before || {}; + after = after || {}; + var sourceId; + for (sourceId in before) { + if (!before.hasOwnProperty(sourceId)) { + continue; + } + if (!after.hasOwnProperty(sourceId)) { + removeSource(sourceId, commands, sourcesRemoved); + } + } + for (sourceId in after) { + if (!after.hasOwnProperty(sourceId)) { + continue; + } + if (!before.hasOwnProperty(sourceId)) { + addSource(sourceId, after, commands); + } else if (!deepEqual(before[sourceId], after[sourceId])) { + if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) { + commands.push({ + command: operations.setGeoJSONSourceData, + args: [ + sourceId, + after[sourceId].data + ] + }); + } else { + updateSource(sourceId, after, commands, sourcesRemoved); + } + } + } + } + function diffLayerPropertyChanges(before, after, commands, layerId, klass, command) { + before = before || {}; + after = after || {}; + var prop; + for (prop in before) { + if (!before.hasOwnProperty(prop)) { + continue; + } + if (!deepEqual(before[prop], after[prop])) { + commands.push({ + command: command, + args: [ + layerId, + prop, + after[prop], + klass + ] + }); + } + } + for (prop in after) { + if (!after.hasOwnProperty(prop) || before.hasOwnProperty(prop)) { + continue; + } + if (!deepEqual(before[prop], after[prop])) { + commands.push({ + command: command, + args: [ + layerId, + prop, + after[prop], + klass + ] + }); + } + } + } + function pluckId(layer) { + return layer.id; + } + function indexById(group, layer) { + group[layer.id] = layer; + return group; + } + function diffLayers(before, after, commands) { + before = before || []; + after = after || []; + var beforeOrder = before.map(pluckId); + var afterOrder = after.map(pluckId); + var beforeIndex = before.reduce(indexById, {}); + var afterIndex = after.reduce(indexById, {}); + var tracker = beforeOrder.slice(); + var clean = Object.create(null); + var i, d, layerId, beforeLayer, afterLayer, insertBeforeLayerId, prop; + for (i = 0, d = 0; i < beforeOrder.length; i++) { + layerId = beforeOrder[i]; + if (!afterIndex.hasOwnProperty(layerId)) { + commands.push({ + command: operations.removeLayer, + args: [layerId] + }); + tracker.splice(tracker.indexOf(layerId, d), 1); + } else { + d++; + } + } + for (i = 0, d = 0; i < afterOrder.length; i++) { + layerId = afterOrder[afterOrder.length - 1 - i]; + if (tracker[tracker.length - 1 - i] === layerId) { + continue; + } + if (beforeIndex.hasOwnProperty(layerId)) { + commands.push({ + command: operations.removeLayer, + args: [layerId] + }); + tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1); + } else { + d++; + } + insertBeforeLayerId = tracker[tracker.length - i]; + commands.push({ + command: operations.addLayer, + args: [ + afterIndex[layerId], + insertBeforeLayerId + ] + }); + tracker.splice(tracker.length - i, 0, layerId); + clean[layerId] = true; + } + for (i = 0; i < afterOrder.length; i++) { + layerId = afterOrder[i]; + beforeLayer = beforeIndex[layerId]; + afterLayer = afterIndex[layerId]; + if (clean[layerId] || deepEqual(beforeLayer, afterLayer)) { + continue; + } + if (!deepEqual(beforeLayer.source, afterLayer.source) || !deepEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !deepEqual(beforeLayer.type, afterLayer.type)) { + commands.push({ + command: operations.removeLayer, + args: [layerId] + }); + insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1]; + commands.push({ + command: operations.addLayer, + args: [ + afterLayer, + insertBeforeLayerId + ] + }); + continue; + } + diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, operations.setLayoutProperty); + diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, operations.setPaintProperty); + if (!deepEqual(beforeLayer.filter, afterLayer.filter)) { + commands.push({ + command: operations.setFilter, + args: [ + layerId, + afterLayer.filter + ] + }); + } + if (!deepEqual(beforeLayer.minzoom, afterLayer.minzoom) || !deepEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) { + commands.push({ + command: operations.setLayerZoomRange, + args: [ + layerId, + afterLayer.minzoom, + afterLayer.maxzoom + ] + }); + } + for (prop in beforeLayer) { + if (!beforeLayer.hasOwnProperty(prop)) { + continue; + } + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') { + continue; + } + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty); + } else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) { + commands.push({ + command: operations.setLayerProperty, + args: [ + layerId, + prop, + afterLayer[prop] + ] + }); + } + } + for (prop in afterLayer) { + if (!afterLayer.hasOwnProperty(prop) || beforeLayer.hasOwnProperty(prop)) { + continue; + } + if (prop === 'layout' || prop === 'paint' || prop === 'filter' || prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') { + continue; + } + if (prop.indexOf('paint.') === 0) { + diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty); + } else if (!deepEqual(beforeLayer[prop], afterLayer[prop])) { + commands.push({ + command: operations.setLayerProperty, + args: [ + layerId, + prop, + afterLayer[prop] + ] + }); + } + } + } + } + function diffStyles(before, after) { + if (!before) { + return [{ + command: operations.setStyle, + args: [after] + }]; + } + var commands = []; + try { + if (!deepEqual(before.version, after.version)) { + return [{ + command: operations.setStyle, + args: [after] + }]; + } + if (!deepEqual(before.center, after.center)) { + commands.push({ + command: operations.setCenter, + args: [after.center] + }); + } + if (!deepEqual(before.zoom, after.zoom)) { + commands.push({ + command: operations.setZoom, + args: [after.zoom] + }); + } + if (!deepEqual(before.bearing, after.bearing)) { + commands.push({ + command: operations.setBearing, + args: [after.bearing] + }); + } + if (!deepEqual(before.pitch, after.pitch)) { + commands.push({ + command: operations.setPitch, + args: [after.pitch] + }); + } + if (!deepEqual(before.sprite, after.sprite)) { + commands.push({ + command: operations.setSprite, + args: [after.sprite] + }); + } + if (!deepEqual(before.glyphs, after.glyphs)) { + commands.push({ + command: operations.setGlyphs, + args: [after.glyphs] + }); + } + if (!deepEqual(before.transition, after.transition)) { + commands.push({ + command: operations.setTransition, + args: [after.transition] + }); + } + if (!deepEqual(before.light, after.light)) { + commands.push({ + command: operations.setLight, + args: [after.light] + }); + } + var sourcesRemoved = {}; + var removeOrAddSourceCommands = []; + diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved); + var beforeLayers = []; + if (before.layers) { + before.layers.forEach(function (layer) { + if (sourcesRemoved[layer.source]) { + commands.push({ + command: operations.removeLayer, + args: [layer.id] + }); + } else { + beforeLayers.push(layer); + } + }); + } + commands = commands.concat(removeOrAddSourceCommands); + diffLayers(beforeLayers, after.layers, commands); + } catch (e) { + console.warn('Unable to compute style diff:', e); + commands = [{ + command: operations.setStyle, + args: [after] + }]; + } + return commands; + } + + var ValidationError = function ValidationError(key, value, message, identifier) { + this.message = (key ? key + ': ' : '') + message; + if (identifier) { + this.identifier = identifier; + } + if (value !== null && value !== undefined && value.__line__) { + this.line = value.__line__; + } + }; + + var ParsingError$1 = function ParsingError(error) { + this.error = error; + this.message = error.message; + var match = error.message.match(/line (\d+)/); + this.line = match ? parseInt(match[1], 10) : 0; + }; + + function validateConstants(options) { + var key = options.key; + var constants = options.value; + if (constants) { + return [new ValidationError(key, constants, 'constants have been deprecated as of v8')]; + } else { + return []; + } + } + + function unbundle(value) { + if (value instanceof Number || value instanceof String || value instanceof Boolean) { + return value.valueOf(); + } else { + return value; + } + } + function deepUnbundle(value) { + if (Array.isArray(value)) { + return value.map(deepUnbundle); + } else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) { + var unbundledValue = {}; + for (var key in value) { + unbundledValue[key] = deepUnbundle(value[key]); + } + return unbundledValue; + } + return unbundle(value); + } + + function validateObject(options) { + var key = options.key; + var object = options.value; + var elementSpecs = options.valueSpec || {}; + var elementValidators = options.objectElementValidators || {}; + var style = options.style; + var styleSpec = options.styleSpec; + var errors = []; + var type = getType(object); + if (type !== 'object') { + return [new ValidationError(key, object, 'object expected, ' + type + ' found')]; + } + for (var objectKey in object) { + var elementSpecKey = objectKey.split('.')[0]; + var elementSpec = elementSpecs[elementSpecKey] || elementSpecs['*']; + var validateElement = void 0; + if (elementValidators[elementSpecKey]) { + validateElement = elementValidators[elementSpecKey]; + } else if (elementSpecs[elementSpecKey]) { + validateElement = validate; + } else if (elementValidators['*']) { + validateElement = elementValidators['*']; + } else if (elementSpecs['*']) { + validateElement = validate; + } else { + errors.push(new ValidationError(key, object[objectKey], 'unknown property "' + objectKey + '"')); + continue; + } + errors = errors.concat(validateElement({ + key: (key ? key + '.' : key) + objectKey, + value: object[objectKey], + valueSpec: elementSpec, + style: style, + styleSpec: styleSpec, + object: object, + objectKey: objectKey + }, object)); + } + for (var elementSpecKey$1 in elementSpecs) { + if (elementValidators[elementSpecKey$1]) { + continue; + } + if (elementSpecs[elementSpecKey$1].required && elementSpecs[elementSpecKey$1]['default'] === undefined && object[elementSpecKey$1] === undefined) { + errors.push(new ValidationError(key, object, 'missing required property "' + elementSpecKey$1 + '"')); + } + } + return errors; + } + + function validateArray(options) { + var array = options.value; + var arraySpec = options.valueSpec; + var style = options.style; + var styleSpec = options.styleSpec; + var key = options.key; + var validateArrayElement = options.arrayElementValidator || validate; + if (getType(array) !== 'array') { + return [new ValidationError(key, array, 'array expected, ' + getType(array) + ' found')]; + } + if (arraySpec.length && array.length !== arraySpec.length) { + return [new ValidationError(key, array, 'array length ' + arraySpec.length + ' expected, length ' + array.length + ' found')]; + } + if (arraySpec['min-length'] && array.length < arraySpec['min-length']) { + return [new ValidationError(key, array, 'array length at least ' + arraySpec['min-length'] + ' expected, length ' + array.length + ' found')]; + } + var arrayElementSpec = { + 'type': arraySpec.value, + 'values': arraySpec.values + }; + if (styleSpec.$version < 7) { + arrayElementSpec.function = arraySpec.function; + } + if (getType(arraySpec.value) === 'object') { + arrayElementSpec = arraySpec.value; + } + var errors = []; + for (var i = 0; i < array.length; i++) { + errors = errors.concat(validateArrayElement({ + array: array, + arrayIndex: i, + value: array[i], + valueSpec: arrayElementSpec, + style: style, + styleSpec: styleSpec, + key: key + '[' + i + ']' + })); + } + return errors; + } + + function validateNumber(options) { + var key = options.key; + var value = options.value; + var valueSpec = options.valueSpec; + var type = getType(value); + if (type === 'number' && value !== value) { + type = 'NaN'; + } + if (type !== 'number') { + return [new ValidationError(key, value, 'number expected, ' + type + ' found')]; + } + if ('minimum' in valueSpec && value < valueSpec.minimum) { + return [new ValidationError(key, value, value + ' is less than the minimum value ' + valueSpec.minimum)]; + } + if ('maximum' in valueSpec && value > valueSpec.maximum) { + return [new ValidationError(key, value, value + ' is greater than the maximum value ' + valueSpec.maximum)]; + } + return []; + } + + function validateFunction(options) { + var functionValueSpec = options.valueSpec; + var functionType = unbundle(options.value.type); + var stopKeyType; + var stopDomainValues = {}; + var previousStopDomainValue; + var previousStopDomainZoom; + var isZoomFunction = functionType !== 'categorical' && options.value.property === undefined; + var isPropertyFunction = !isZoomFunction; + var isZoomAndPropertyFunction = getType(options.value.stops) === 'array' && getType(options.value.stops[0]) === 'array' && getType(options.value.stops[0][0]) === 'object'; + var errors = validateObject({ + key: options.key, + value: options.value, + valueSpec: options.styleSpec.function, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + stops: validateFunctionStops, + default: validateFunctionDefault + } + }); + if (functionType === 'identity' && isZoomFunction) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "property"')); + } + if (functionType !== 'identity' && !options.value.stops) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "stops"')); + } + if (functionType === 'exponential' && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'exponential functions not supported')); + } + if (options.styleSpec.$version >= 8) { + if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'property functions not supported')); + } else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'zoom functions not supported')); + } + } + if ((functionType === 'categorical' || isZoomAndPropertyFunction) && options.value.property === undefined) { + errors.push(new ValidationError(options.key, options.value, '"property" property is required')); + } + return errors; + function validateFunctionStops(options) { + if (functionType === 'identity') { + return [new ValidationError(options.key, options.value, 'identity function may not have a "stops" property')]; + } + var errors = []; + var value = options.value; + errors = errors.concat(validateArray({ + key: options.key, + value: value, + valueSpec: options.valueSpec, + style: options.style, + styleSpec: options.styleSpec, + arrayElementValidator: validateFunctionStop + })); + if (getType(value) === 'array' && value.length === 0) { + errors.push(new ValidationError(options.key, value, 'array must have at least one stop')); + } + return errors; + } + function validateFunctionStop(options) { + var errors = []; + var value = options.value; + var key = options.key; + if (getType(value) !== 'array') { + return [new ValidationError(key, value, 'array expected, ' + getType(value) + ' found')]; + } + if (value.length !== 2) { + return [new ValidationError(key, value, 'array length 2 expected, length ' + value.length + ' found')]; + } + if (isZoomAndPropertyFunction) { + if (getType(value[0]) !== 'object') { + return [new ValidationError(key, value, 'object expected, ' + getType(value[0]) + ' found')]; + } + if (value[0].zoom === undefined) { + return [new ValidationError(key, value, 'object stop key must have zoom')]; + } + if (value[0].value === undefined) { + return [new ValidationError(key, value, 'object stop key must have value')]; + } + if (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) { + return [new ValidationError(key, value[0].zoom, 'stop zoom values must appear in ascending order')]; + } + if (unbundle(value[0].zoom) !== previousStopDomainZoom) { + previousStopDomainZoom = unbundle(value[0].zoom); + previousStopDomainValue = undefined; + stopDomainValues = {}; + } + errors = errors.concat(validateObject({ + key: key + '[0]', + value: value[0], + valueSpec: { zoom: {} }, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + zoom: validateNumber, + value: validateStopDomainValue + } + })); + } else { + errors = errors.concat(validateStopDomainValue({ + key: key + '[0]', + value: value[0], + valueSpec: {}, + style: options.style, + styleSpec: options.styleSpec + }, value)); + } + if (isExpression(deepUnbundle(value[1]))) { + return errors.concat([new ValidationError(key + '[1]', value[1], 'expressions are not allowed in function stops.')]); + } + return errors.concat(validate({ + key: key + '[1]', + value: value[1], + valueSpec: functionValueSpec, + style: options.style, + styleSpec: options.styleSpec + })); + } + function validateStopDomainValue(options, stop) { + var type = getType(options.value); + var value = unbundle(options.value); + var reportValue = options.value !== null ? options.value : stop; + if (!stopKeyType) { + stopKeyType = type; + } else if (type !== stopKeyType) { + return [new ValidationError(options.key, reportValue, type + ' stop domain type must match previous stop domain type ' + stopKeyType)]; + } + if (type !== 'number' && type !== 'string' && type !== 'boolean') { + return [new ValidationError(options.key, reportValue, 'stop domain value must be a number, string, or boolean')]; + } + if (type !== 'number' && functionType !== 'categorical') { + var message = 'number expected, ' + type + ' found'; + if (supportsPropertyExpression(functionValueSpec) && functionType === undefined) { + message += '\nIf you intended to use a categorical function, specify `"type": "categorical"`.'; + } + return [new ValidationError(options.key, reportValue, message)]; + } + if (functionType === 'categorical' && type === 'number' && (!isFinite(value) || Math.floor(value) !== value)) { + return [new ValidationError(options.key, reportValue, 'integer expected, found ' + value)]; + } + if (functionType !== 'categorical' && type === 'number' && previousStopDomainValue !== undefined && value < previousStopDomainValue) { + return [new ValidationError(options.key, reportValue, 'stop domain values must appear in ascending order')]; + } else { + previousStopDomainValue = value; + } + if (functionType === 'categorical' && value in stopDomainValues) { + return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')]; + } else { + stopDomainValues[value] = true; + } + return []; + } + function validateFunctionDefault(options) { + return validate({ + key: options.key, + value: options.value, + valueSpec: functionValueSpec, + style: options.style, + styleSpec: options.styleSpec + }); + } + } + + function validateExpression(options) { + var expression = (options.expressionContext === 'property' ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec); + if (expression.result === 'error') { + return expression.value.map(function (error) { + return new ValidationError('' + options.key + error.key, options.value, error.message); + }); + } + var expressionObj = expression.value.expression || expression.value._styleExpression.expression; + if (options.expressionContext === 'property' && options.propertyKey === 'text-font' && !expressionObj.outputDefined()) { + return [new ValidationError(options.key, options.value, 'Invalid data expression for "' + options.propertyKey + '". Output values must be contained as literals within the expression.')]; + } + if (options.expressionContext === 'property' && options.propertyType === 'layout' && !isStateConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with layout properties.')]; + } + if (options.expressionContext === 'filter' && !isStateConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with filters.')]; + } + if (options.expressionContext && options.expressionContext.indexOf('cluster') === 0) { + if (!isGlobalPropertyConstant(expressionObj, [ + 'zoom', + 'feature-state' + ])) { + return [new ValidationError(options.key, options.value, '"zoom" and "feature-state" expressions are not supported with cluster properties.')]; + } + if (options.expressionContext === 'cluster-initial' && !isFeatureConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, 'Feature data expressions are not supported with initial expression part of cluster properties.')]; + } + } + return []; + } + + function validateBoolean(options) { + var value = options.value; + var key = options.key; + var type = getType(value); + if (type !== 'boolean') { + return [new ValidationError(key, value, 'boolean expected, ' + type + ' found')]; + } + return []; + } + + function validateColor(options) { + var key = options.key; + var value = options.value; + var type = getType(value); + if (type !== 'string') { + return [new ValidationError(key, value, 'color expected, ' + type + ' found')]; + } + if (csscolorparser_1(value) === null) { + return [new ValidationError(key, value, 'color expected, "' + value + '" found')]; + } + return []; + } + + function validateEnum(options) { + var key = options.key; + var value = options.value; + var valueSpec = options.valueSpec; + var errors = []; + if (Array.isArray(valueSpec.values)) { + if (valueSpec.values.indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, 'expected one of [' + valueSpec.values.join(', ') + '], ' + JSON.stringify(value) + ' found')); + } + } else { + if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, 'expected one of [' + Object.keys(valueSpec.values).join(', ') + '], ' + JSON.stringify(value) + ' found')); + } + } + return errors; + } + + function validateFilter(options) { + if (isExpressionFilter(deepUnbundle(options.value))) { + return validateExpression(extend({}, options, { + expressionContext: 'filter', + valueSpec: { value: 'boolean' } + })); + } else { + return validateNonExpressionFilter(options); + } + } + function validateNonExpressionFilter(options) { + var value = options.value; + var key = options.key; + if (getType(value) !== 'array') { + return [new ValidationError(key, value, 'array expected, ' + getType(value) + ' found')]; + } + var styleSpec = options.styleSpec; + var type; + var errors = []; + if (value.length < 1) { + return [new ValidationError(key, value, 'filter array must have at least 1 element')]; + } + errors = errors.concat(validateEnum({ + key: key + '[0]', + value: value[0], + valueSpec: styleSpec.filter_operator, + style: options.style, + styleSpec: options.styleSpec + })); + switch (unbundle(value[0])) { + case '<': + case '<=': + case '>': + case '>=': + if (value.length >= 2 && unbundle(value[1]) === '$type') { + errors.push(new ValidationError(key, value, '"$type" cannot be use with operator "' + value[0] + '"')); + } + case '==': + case '!=': + if (value.length !== 3) { + errors.push(new ValidationError(key, value, 'filter array for operator "' + value[0] + '" must have 3 elements')); + } + case 'in': + case '!in': + if (value.length >= 2) { + type = getType(value[1]); + if (type !== 'string') { + errors.push(new ValidationError(key + '[1]', value[1], 'string expected, ' + type + ' found')); + } + } + for (var i = 2; i < value.length; i++) { + type = getType(value[i]); + if (unbundle(value[1]) === '$type') { + errors = errors.concat(validateEnum({ + key: key + '[' + i + ']', + value: value[i], + valueSpec: styleSpec.geometry_type, + style: options.style, + styleSpec: options.styleSpec + })); + } else if (type !== 'string' && type !== 'number' && type !== 'boolean') { + errors.push(new ValidationError(key + '[' + i + ']', value[i], 'string, number, or boolean expected, ' + type + ' found')); + } + } + break; + case 'any': + case 'all': + case 'none': + for (var i$1 = 1; i$1 < value.length; i$1++) { + errors = errors.concat(validateNonExpressionFilter({ + key: key + '[' + i$1 + ']', + value: value[i$1], + style: options.style, + styleSpec: options.styleSpec + })); + } + break; + case 'has': + case '!has': + type = getType(value[1]); + if (value.length !== 2) { + errors.push(new ValidationError(key, value, 'filter array for "' + value[0] + '" operator must have 2 elements')); + } else if (type !== 'string') { + errors.push(new ValidationError(key + '[1]', value[1], 'string expected, ' + type + ' found')); + } + break; + case 'within': + type = getType(value[1]); + if (value.length !== 2) { + errors.push(new ValidationError(key, value, 'filter array for "' + value[0] + '" operator must have 2 elements')); + } else if (type !== 'object') { + errors.push(new ValidationError(key + '[1]', value[1], 'object expected, ' + type + ' found')); + } + break; + } + return errors; + } + + function validateProperty(options, propertyType) { + var key = options.key; + var style = options.style; + var styleSpec = options.styleSpec; + var value = options.value; + var propertyKey = options.objectKey; + var layerSpec = styleSpec[propertyType + '_' + options.layerType]; + if (!layerSpec) { + return []; + } + var transitionMatch = propertyKey.match(/^(.*)-transition$/); + if (propertyType === 'paint' && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) { + return validate({ + key: key, + value: value, + valueSpec: styleSpec.transition, + style: style, + styleSpec: styleSpec + }); + } + var valueSpec = options.valueSpec || layerSpec[propertyKey]; + if (!valueSpec) { + return [new ValidationError(key, value, 'unknown property "' + propertyKey + '"')]; + } + var tokenMatch; + if (getType(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) { + return [new ValidationError(key, value, '"' + propertyKey + '" does not support interpolation syntax\n' + 'Use an identity property function instead: `{ "type": "identity", "property": ' + JSON.stringify(tokenMatch[1]) + ' }`.')]; + } + var errors = []; + if (options.layerType === 'symbol') { + if (propertyKey === 'text-field' && style && !style.glyphs) { + errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property')); + } + if (propertyKey === 'text-font' && isFunction$1(deepUnbundle(value)) && unbundle(value.type) === 'identity') { + errors.push(new ValidationError(key, value, '"text-font" does not support identity functions')); + } + } + return errors.concat(validate({ + key: options.key, + value: value, + valueSpec: valueSpec, + style: style, + styleSpec: styleSpec, + expressionContext: 'property', + propertyType: propertyType, + propertyKey: propertyKey + })); + } + + function validatePaintProperty(options) { + return validateProperty(options, 'paint'); + } + + function validateLayoutProperty(options) { + return validateProperty(options, 'layout'); + } + + function validateLayer(options) { + var errors = []; + var layer = options.value; + var key = options.key; + var style = options.style; + var styleSpec = options.styleSpec; + if (!layer.type && !layer.ref) { + errors.push(new ValidationError(key, layer, 'either "type" or "ref" is required')); + } + var type = unbundle(layer.type); + var ref = unbundle(layer.ref); + if (layer.id) { + var layerId = unbundle(layer.id); + for (var i = 0; i < options.arrayIndex; i++) { + var otherLayer = style.layers[i]; + if (unbundle(otherLayer.id) === layerId) { + errors.push(new ValidationError(key, layer.id, 'duplicate layer id "' + layer.id + '", previously used at line ' + otherLayer.id.__line__)); + } + } + } + if ('ref' in layer) { + [ + 'type', + 'source', + 'source-layer', + 'filter', + 'layout' + ].forEach(function (p) { + if (p in layer) { + errors.push(new ValidationError(key, layer[p], '"' + p + '" is prohibited for ref layers')); + } + }); + var parent; + style.layers.forEach(function (layer) { + if (unbundle(layer.id) === ref) { + parent = layer; + } + }); + if (!parent) { + errors.push(new ValidationError(key, layer.ref, 'ref layer "' + ref + '" not found')); + } else if (parent.ref) { + errors.push(new ValidationError(key, layer.ref, 'ref cannot reference another ref layer')); + } else { + type = unbundle(parent.type); + } + } else if (type !== 'background') { + if (!layer.source) { + errors.push(new ValidationError(key, layer, 'missing required property "source"')); + } else { + var source = style.sources && style.sources[layer.source]; + var sourceType = source && unbundle(source.type); + if (!source) { + errors.push(new ValidationError(key, layer.source, 'source "' + layer.source + '" not found')); + } else if (sourceType === 'vector' && type === 'raster') { + errors.push(new ValidationError(key, layer.source, 'layer "' + layer.id + '" requires a raster source')); + } else if (sourceType === 'raster' && type !== 'raster') { + errors.push(new ValidationError(key, layer.source, 'layer "' + layer.id + '" requires a vector source')); + } else if (sourceType === 'vector' && !layer['source-layer']) { + errors.push(new ValidationError(key, layer, 'layer "' + layer.id + '" must specify a "source-layer"')); + } else if (sourceType === 'raster-dem' && type !== 'hillshade') { + errors.push(new ValidationError(key, layer.source, 'raster-dem source can only be used with layer type \'hillshade\'.')); + } else if (type === 'line' && layer.paint && layer.paint['line-gradient'] && (sourceType !== 'geojson' || !source.lineMetrics)) { + errors.push(new ValidationError(key, layer, 'layer "' + layer.id + '" specifies a line-gradient, which requires a GeoJSON source with `lineMetrics` enabled.')); + } + } + } + errors = errors.concat(validateObject({ + key: key, + value: layer, + valueSpec: styleSpec.layer, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + '*': function _() { + return []; + }, + type: function type() { + return validate({ + key: key + '.type', + value: layer.type, + valueSpec: styleSpec.layer.type, + style: options.style, + styleSpec: options.styleSpec, + object: layer, + objectKey: 'type' + }); + }, + filter: validateFilter, + layout: function layout(options) { + return validateObject({ + layer: layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + '*': function _(options) { + return validateLayoutProperty(extend({ layerType: type }, options)); + } + } + }); + }, + paint: function paint(options) { + return validateObject({ + layer: layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + '*': function _(options) { + return validatePaintProperty(extend({ layerType: type }, options)); + } + } + }); + } + } + })); + return errors; + } + + function validateString(options) { + var value = options.value; + var key = options.key; + var type = getType(value); + if (type !== 'string') { + return [new ValidationError(key, value, 'string expected, ' + type + ' found')]; + } + return []; + } + + var objectElementValidators = { promoteId: validatePromoteId }; + function validateSource(options) { + var value = options.value; + var key = options.key; + var styleSpec = options.styleSpec; + var style = options.style; + if (!value.type) { + return [new ValidationError(key, value, '"type" is required')]; + } + var type = unbundle(value.type); + var errors; + switch (type) { + case 'vector': + case 'raster': + case 'raster-dem': + errors = validateObject({ + key: key, + value: value, + valueSpec: styleSpec['source_' + type.replace('-', '_')], + style: options.style, + styleSpec: styleSpec, + objectElementValidators: objectElementValidators + }); + return errors; + case 'geojson': + errors = validateObject({ + key: key, + value: value, + valueSpec: styleSpec.source_geojson, + style: style, + styleSpec: styleSpec, + objectElementValidators: objectElementValidators + }); + if (value.cluster) { + for (var prop in value.clusterProperties) { + var ref = value.clusterProperties[prop]; + var operator = ref[0]; + var mapExpr = ref[1]; + var reduceExpr = typeof operator === 'string' ? [ + operator, + ['accumulated'], + [ + 'get', + prop + ] + ] : operator; + errors.push.apply(errors, validateExpression({ + key: key + '.' + prop + '.map', + value: mapExpr, + expressionContext: 'cluster-map' + })); + errors.push.apply(errors, validateExpression({ + key: key + '.' + prop + '.reduce', + value: reduceExpr, + expressionContext: 'cluster-reduce' + })); + } + } + return errors; + case 'video': + return validateObject({ + key: key, + value: value, + valueSpec: styleSpec.source_video, + style: style, + styleSpec: styleSpec + }); + case 'image': + return validateObject({ + key: key, + value: value, + valueSpec: styleSpec.source_image, + style: style, + styleSpec: styleSpec + }); + case 'canvas': + return [new ValidationError(key, null, 'Please use runtime APIs to add canvas sources, rather than including them in stylesheets.', 'source.canvas')]; + default: + return validateEnum({ + key: key + '.type', + value: value.type, + valueSpec: { + values: [ + 'vector', + 'raster', + 'raster-dem', + 'geojson', + 'video', + 'image' + ] + }, + style: style, + styleSpec: styleSpec + }); + } + } + function validatePromoteId(ref) { + var key = ref.key; + var value = ref.value; + if (getType(value) === 'string') { + return validateString({ + key: key, + value: value + }); + } else { + var errors = []; + for (var prop in value) { + errors.push.apply(errors, validateString({ + key: key + '.' + prop, + value: value[prop] + })); + } + return errors; + } + } + + function validateLight(options) { + var light = options.value; + var styleSpec = options.styleSpec; + var lightSpec = styleSpec.light; + var style = options.style; + var errors = []; + var rootType = getType(light); + if (light === undefined) { + return errors; + } else if (rootType !== 'object') { + errors = errors.concat([new ValidationError('light', light, 'object expected, ' + rootType + ' found')]); + return errors; + } + for (var key in light) { + var transitionMatch = key.match(/^(.*)-transition$/); + if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) { + errors = errors.concat(validate({ + key: key, + value: light[key], + valueSpec: styleSpec.transition, + style: style, + styleSpec: styleSpec + })); + } else if (lightSpec[key]) { + errors = errors.concat(validate({ + key: key, + value: light[key], + valueSpec: lightSpec[key], + style: style, + styleSpec: styleSpec + })); + } else { + errors = errors.concat([new ValidationError(key, light[key], 'unknown property "' + key + '"')]); + } + } + return errors; + } + + function validateFormatted(options) { + if (validateString(options).length === 0) { + return []; + } + return validateExpression(options); + } + + function validateImage(options) { + if (validateString(options).length === 0) { + return []; + } + return validateExpression(options); + } + + var VALIDATORS = { + '*': function _() { + return []; + }, + 'array': validateArray, + 'boolean': validateBoolean, + 'number': validateNumber, + 'color': validateColor, + 'constants': validateConstants, + 'enum': validateEnum, + 'filter': validateFilter, + 'function': validateFunction, + 'layer': validateLayer, + 'object': validateObject, + 'source': validateSource, + 'light': validateLight, + 'string': validateString, + 'formatted': validateFormatted, + 'resolvedImage': validateImage + }; + function validate(options) { + var value = options.value; + var valueSpec = options.valueSpec; + var styleSpec = options.styleSpec; + if (valueSpec.expression && isFunction$1(unbundle(value))) { + return validateFunction(options); + } else if (valueSpec.expression && isExpression(deepUnbundle(value))) { + return validateExpression(options); + } else if (valueSpec.type && VALIDATORS[valueSpec.type]) { + return VALIDATORS[valueSpec.type](options); + } else { + var valid = validateObject(extend({}, options, { valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec })); + return valid; + } + } + + function validateGlyphsURL (options) { + var value = options.value; + var key = options.key; + var errors = validateString(options); + if (errors.length) { + return errors; + } + if (value.indexOf('{fontstack}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{fontstack}" token')); + } + if (value.indexOf('{range}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{range}" token')); + } + return errors; + } + + function validateStyleMin(style, styleSpec) { + if (styleSpec === void 0) + styleSpec = v8; + var errors = []; + errors = errors.concat(validate({ + key: '', + value: style, + valueSpec: styleSpec.$root, + styleSpec: styleSpec, + style: style, + objectElementValidators: { + glyphs: validateGlyphsURL, + '*': function _() { + return []; + } + } + })); + if (style.constants) { + errors = errors.concat(validateConstants({ + key: 'constants', + value: style.constants, + style: style, + styleSpec: styleSpec + })); + } + return sortErrors(errors); + } + validateStyleMin.source = wrapCleanErrors(validateSource); + validateStyleMin.light = wrapCleanErrors(validateLight); + validateStyleMin.layer = wrapCleanErrors(validateLayer); + validateStyleMin.filter = wrapCleanErrors(validateFilter); + validateStyleMin.paintProperty = wrapCleanErrors(validatePaintProperty); + validateStyleMin.layoutProperty = wrapCleanErrors(validateLayoutProperty); + function sortErrors(errors) { + return [].concat(errors).sort(function (a, b) { + return a.line - b.line; + }); + } + function wrapCleanErrors(inner) { + return function () { + var args = [], len = arguments.length; + while (len--) + args[len] = arguments[len]; + return sortErrors(inner.apply(this, args)); + }; + } + + var jsonlint = createCommonjsModule(function (module, exports) { + /* parser generated by jison 0.4.15 */ + /* + Returns a Parser object of the following structure: + + Parser: { + yy: {} + } + + Parser.prototype: { + yy: {}, + trace: function(), + symbols_: {associative list: name ==> number}, + terminals_: {associative list: number ==> name}, + productions_: [...], + performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$), + table: [...], + defaultActions: {...}, + parseError: function(str, hash), + parse: function(input), + + lexer: { + EOF: 1, + parseError: function(str, hash), + setInput: function(input), + input: function(), + unput: function(str), + more: function(), + less: function(n), + pastInput: function(), + upcomingInput: function(), + showPosition: function(), + test_match: function(regex_match_array, rule_index), + next: function(), + lex: function(), + begin: function(condition), + popState: function(), + _currentRules: function(), + topState: function(), + pushState: function(condition), + + options: { + ranges: boolean (optional: true ==> token location info will include a .range[] member) + flex: boolean (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match) + backtrack_lexer: boolean (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code) + }, + + performAction: function(yy, yy_, $avoiding_name_collisions, YY_START), + rules: [...], + conditions: {associative list: name ==> set}, + } + } + + + token location info (@$, _$, etc.): { + first_line: n, + last_line: n, + first_column: n, + last_column: n, + range: [start_number, end_number] (where the numbers are indexes into the input string, regular zero-based) + } + + + the parseError function receives a 'hash' object with these members for lexer and parser errors: { + text: (matched text) + token: (the produced terminal token, if any) + line: (yylineno) + } + while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: { + loc: (yylloc) + expected: (string describing the set of expected tokens) + recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error) + } + */ + var parser = (function(){ + var o=function(k,v,o,l){for(o=o||{},l=k.length;l--;o[k[l]]=v){ }return o},$V0=[1,12],$V1=[1,13],$V2=[1,9],$V3=[1,10],$V4=[1,11],$V5=[1,14],$V6=[1,15],$V7=[14,18,22,24],$V8=[18,22],$V9=[22,24]; + var parser = {trace: function trace() { }, + yy: {}, + symbols_: {"error":2,"JSONString":3,"STRING":4,"JSONNumber":5,"NUMBER":6,"JSONNullLiteral":7,"NULL":8,"JSONBooleanLiteral":9,"TRUE":10,"FALSE":11,"JSONText":12,"JSONValue":13,"EOF":14,"JSONObject":15,"JSONArray":16,"{":17,"}":18,"JSONMemberList":19,"JSONMember":20,":":21,",":22,"[":23,"]":24,"JSONElementList":25,"$accept":0,"$end":1}, + terminals_: {2:"error",4:"STRING",6:"NUMBER",8:"NULL",10:"TRUE",11:"FALSE",14:"EOF",17:"{",18:"}",21:":",22:",",23:"[",24:"]"}, + productions_: [0,[3,1],[5,1],[7,1],[9,1],[9,1],[12,2],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[15,2],[15,3],[20,3],[19,1],[19,3],[16,2],[16,3],[25,1],[25,3]], + performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */) { + /* this == yyval */ + + var $0 = $$.length - 1; + switch (yystate) { + case 1: + // replace escaped characters with actual character + this.$ = new String(yytext.replace(/\\(\\|")/g, "$"+"1") + .replace(/\\n/g,'\n') + .replace(/\\r/g,'\r') + .replace(/\\t/g,'\t') + .replace(/\\v/g,'\v') + .replace(/\\f/g,'\f') + .replace(/\\b/g,'\b')); + this.$.__line__ = this._$.first_line; + + break; + case 2: + + this.$ = new Number(yytext); + this.$.__line__ = this._$.first_line; + + break; + case 3: + + this.$ = null; + + break; + case 4: + + this.$ = new Boolean(true); + this.$.__line__ = this._$.first_line; + + break; + case 5: + + this.$ = new Boolean(false); + this.$.__line__ = this._$.first_line; + + break; + case 6: + return this.$ = $$[$0-1]; + case 13: + this.$ = {}; Object.defineProperty(this.$, '__line__', { + value: this._$.first_line, + enumerable: false + }); + break; + case 14: case 19: + this.$ = $$[$0-1]; Object.defineProperty(this.$, '__line__', { + value: this._$.first_line, + enumerable: false + }); + break; + case 15: + this.$ = [$$[$0-2], $$[$0]]; + break; + case 16: + this.$ = {}; this.$[$$[$0][0]] = $$[$0][1]; + break; + case 17: + this.$ = $$[$0-2]; $$[$0-2][$$[$0][0]] = $$[$0][1]; + break; + case 18: + this.$ = []; Object.defineProperty(this.$, '__line__', { + value: this._$.first_line, + enumerable: false + }); + break; + case 20: + this.$ = [$$[$0]]; + break; + case 21: + this.$ = $$[$0-2]; $$[$0-2].push($$[$0]); + break; + } + }, + table: [{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,12:1,13:2,15:7,16:8,17:$V5,23:$V6},{1:[3]},{14:[1,16]},o($V7,[2,7]),o($V7,[2,8]),o($V7,[2,9]),o($V7,[2,10]),o($V7,[2,11]),o($V7,[2,12]),o($V7,[2,3]),o($V7,[2,4]),o($V7,[2,5]),o([14,18,21,22,24],[2,1]),o($V7,[2,2]),{3:20,4:$V0,18:[1,17],19:18,20:19},{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,13:23,15:7,16:8,17:$V5,23:$V6,24:[1,21],25:22},{1:[2,6]},o($V7,[2,13]),{18:[1,24],22:[1,25]},o($V8,[2,16]),{21:[1,26]},o($V7,[2,18]),{22:[1,28],24:[1,27]},o($V9,[2,20]),o($V7,[2,14]),{3:20,4:$V0,20:29},{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,13:30,15:7,16:8,17:$V5,23:$V6},o($V7,[2,19]),{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,13:31,15:7,16:8,17:$V5,23:$V6},o($V8,[2,17]),o($V8,[2,15]),o($V9,[2,21])], + defaultActions: {16:[2,6]}, + parseError: function parseError(str, hash) { + if (hash.recoverable) { + this.trace(str); + } else { + throw new Error(str); + } + }, + parse: function parse(input) { + var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = '', yylineno = 0, yyleng = 0, TERROR = 2, EOF = 1; + var args = lstack.slice.call(arguments, 1); + var lexer = Object.create(this.lexer); + var sharedState = { yy: {} }; + for (var k in this.yy) { + if (Object.prototype.hasOwnProperty.call(this.yy, k)) { + sharedState.yy[k] = this.yy[k]; + } + } + lexer.setInput(input, sharedState.yy); + sharedState.yy.lexer = lexer; + sharedState.yy.parser = this; + if (typeof lexer.yylloc == 'undefined') { + lexer.yylloc = {}; + } + var yyloc = lexer.yylloc; + lstack.push(yyloc); + var ranges = lexer.options && lexer.options.ranges; + if (typeof sharedState.yy.parseError === 'function') { + this.parseError = sharedState.yy.parseError; + } else { + this.parseError = Object.getPrototypeOf(this).parseError; + } + + function lex() { + var token; + token = lexer.lex() || EOF; + if (typeof token !== 'number') { + token = self.symbols_[token] || token; + } + return token; + } + var symbol, state, action, r, yyval = {}, p, len, newState, expected; + while (true) { + state = stack[stack.length - 1]; + if (this.defaultActions[state]) { + action = this.defaultActions[state]; + } else { + if (symbol === null || typeof symbol == 'undefined') { + symbol = lex(); + } + action = table[state] && table[state][symbol]; + } + if (typeof action === 'undefined' || !action.length || !action[0]) { + var errStr = ''; + expected = []; + for (p in table[state]) { + if (this.terminals_[p] && p > TERROR) { + expected.push('\'' + this.terminals_[p] + '\''); + } + } + if (lexer.showPosition) { + errStr = 'Parse error on line ' + (yylineno + 1) + ':\n' + lexer.showPosition() + '\nExpecting ' + expected.join(', ') + ', got \'' + (this.terminals_[symbol] || symbol) + '\''; + } else { + errStr = 'Parse error on line ' + (yylineno + 1) + ': Unexpected ' + (symbol == EOF ? 'end of input' : '\'' + (this.terminals_[symbol] || symbol) + '\''); + } + this.parseError(errStr, { + text: lexer.match, + token: this.terminals_[symbol] || symbol, + line: lexer.yylineno, + loc: yyloc, + expected: expected + }); + } + if (action[0] instanceof Array && action.length > 1) { + throw new Error('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol); + } + switch (action[0]) { + case 1: + stack.push(symbol); + vstack.push(lexer.yytext); + lstack.push(lexer.yylloc); + stack.push(action[1]); + symbol = null; + { + yyleng = lexer.yyleng; + yytext = lexer.yytext; + yylineno = lexer.yylineno; + yyloc = lexer.yylloc; + } + break; + case 2: + len = this.productions_[action[1]][1]; + yyval.$ = vstack[vstack.length - len]; + yyval._$ = { + first_line: lstack[lstack.length - (len || 1)].first_line, + last_line: lstack[lstack.length - 1].last_line, + first_column: lstack[lstack.length - (len || 1)].first_column, + last_column: lstack[lstack.length - 1].last_column + }; + if (ranges) { + yyval._$.range = [ + lstack[lstack.length - (len || 1)].range[0], + lstack[lstack.length - 1].range[1] + ]; + } + r = this.performAction.apply(yyval, [ + yytext, + yyleng, + yylineno, + sharedState.yy, + action[1], + vstack, + lstack + ].concat(args)); + if (typeof r !== 'undefined') { + return r; + } + if (len) { + stack = stack.slice(0, -1 * len * 2); + vstack = vstack.slice(0, -1 * len); + lstack = lstack.slice(0, -1 * len); + } + stack.push(this.productions_[action[1]][0]); + vstack.push(yyval.$); + lstack.push(yyval._$); + newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; + stack.push(newState); + break; + case 3: + return true; + } + } + return true; + }}; + /* generated by jison-lex 0.3.4 */ + var lexer = (function(){ + var lexer = ({ + + EOF:1, + + parseError:function parseError(str, hash) { + if (this.yy.parser) { + this.yy.parser.parseError(str, hash); + } else { + throw new Error(str); + } + }, + + // resets the lexer, sets new input + setInput:function (input, yy) { + this.yy = yy || this.yy || {}; + this._input = input; + this._more = this._backtrack = this.done = false; + this.yylineno = this.yyleng = 0; + this.yytext = this.matched = this.match = ''; + this.conditionStack = ['INITIAL']; + this.yylloc = { + first_line: 1, + first_column: 0, + last_line: 1, + last_column: 0 + }; + if (this.options.ranges) { + this.yylloc.range = [0,0]; + } + this.offset = 0; + return this; + }, + + // consumes and returns one char from the input + input:function () { + var ch = this._input[0]; + this.yytext += ch; + this.yyleng++; + this.offset++; + this.match += ch; + this.matched += ch; + var lines = ch.match(/(?:\r\n?|\n).*/g); + if (lines) { + this.yylineno++; + this.yylloc.last_line++; + } else { + this.yylloc.last_column++; + } + if (this.options.ranges) { + this.yylloc.range[1]++; + } + + this._input = this._input.slice(1); + return ch; + }, + + // unshifts one char (or a string) into the input + unput:function (ch) { + var len = ch.length; + var lines = ch.split(/(?:\r\n?|\n)/g); + + this._input = ch + this._input; + this.yytext = this.yytext.substr(0, this.yytext.length - len); + //this.yyleng -= len; + this.offset -= len; + var oldLines = this.match.split(/(?:\r\n?|\n)/g); + this.match = this.match.substr(0, this.match.length - 1); + this.matched = this.matched.substr(0, this.matched.length - 1); + + if (lines.length - 1) { + this.yylineno -= lines.length - 1; + } + var r = this.yylloc.range; + + this.yylloc = { + first_line: this.yylloc.first_line, + last_line: this.yylineno + 1, + first_column: this.yylloc.first_column, + last_column: lines ? + (lines.length === oldLines.length ? this.yylloc.first_column : 0) + + oldLines[oldLines.length - lines.length].length - lines[0].length : + this.yylloc.first_column - len + }; + + if (this.options.ranges) { + this.yylloc.range = [r[0], r[0] + this.yyleng - len]; + } + this.yyleng = this.yytext.length; + return this; + }, + + // When called from action, caches matched text and appends it on next action + more:function () { + this._more = true; + return this; + }, + + // When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead. + reject:function () { + if (this.options.backtrack_lexer) { + this._backtrack = true; + } else { + return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n' + this.showPosition(), { + text: "", + token: null, + line: this.yylineno + }); + + } + return this; + }, + + // retain first n characters of the match + less:function (n) { + this.unput(this.match.slice(n)); + }, + + // displays already matched input, i.e. for error messages + pastInput:function () { + var past = this.matched.substr(0, this.matched.length - this.match.length); + return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); + }, + + // displays upcoming input, i.e. for error messages + upcomingInput:function () { + var next = this.match; + if (next.length < 20) { + next += this._input.substr(0, 20-next.length); + } + return (next.substr(0,20) + (next.length > 20 ? '...' : '')).replace(/\n/g, ""); + }, + + // displays the character position where the lexing error occurred, i.e. for error messages + showPosition:function () { + var pre = this.pastInput(); + var c = new Array(pre.length + 1).join("-"); + return pre + this.upcomingInput() + "\n" + c + "^"; + }, + + // test the lexed token: return FALSE when not a match, otherwise return token + test_match:function (match, indexed_rule) { + var token, + lines, + backup; + + if (this.options.backtrack_lexer) { + // save context + backup = { + yylineno: this.yylineno, + yylloc: { + first_line: this.yylloc.first_line, + last_line: this.last_line, + first_column: this.yylloc.first_column, + last_column: this.yylloc.last_column + }, + yytext: this.yytext, + match: this.match, + matches: this.matches, + matched: this.matched, + yyleng: this.yyleng, + offset: this.offset, + _more: this._more, + _input: this._input, + yy: this.yy, + conditionStack: this.conditionStack.slice(0), + done: this.done + }; + if (this.options.ranges) { + backup.yylloc.range = this.yylloc.range.slice(0); + } + } + + lines = match[0].match(/(?:\r\n?|\n).*/g); + if (lines) { + this.yylineno += lines.length; + } + this.yylloc = { + first_line: this.yylloc.last_line, + last_line: this.yylineno + 1, + first_column: this.yylloc.last_column, + last_column: lines ? + lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : + this.yylloc.last_column + match[0].length + }; + this.yytext += match[0]; + this.match += match[0]; + this.matches = match; + this.yyleng = this.yytext.length; + if (this.options.ranges) { + this.yylloc.range = [this.offset, this.offset += this.yyleng]; + } + this._more = false; + this._backtrack = false; + this._input = this._input.slice(match[0].length); + this.matched += match[0]; + token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]); + if (this.done && this._input) { + this.done = false; + } + if (token) { + return token; + } else if (this._backtrack) { + // recover context + for (var k in backup) { + this[k] = backup[k]; + } + return false; // rule action called reject() implying the next rule should be tested instead. + } + return false; + }, + + // return next match in input + next:function () { + if (this.done) { + return this.EOF; + } + if (!this._input) { + this.done = true; + } + + var token, + match, + tempMatch, + index; + if (!this._more) { + this.yytext = ''; + this.match = ''; + } + var rules = this._currentRules(); + for (var i = 0; i < rules.length; i++) { + tempMatch = this._input.match(this.rules[rules[i]]); + if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { + match = tempMatch; + index = i; + if (this.options.backtrack_lexer) { + token = this.test_match(tempMatch, rules[i]); + if (token !== false) { + return token; + } else if (this._backtrack) { + match = false; + continue; // rule action called reject() implying a rule MISmatch. + } else { + // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) + return false; + } + } else if (!this.options.flex) { + break; + } + } + } + if (match) { + token = this.test_match(match, rules[index]); + if (token !== false) { + return token; + } + // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) + return false; + } + if (this._input === "") { + return this.EOF; + } else { + return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { + text: "", + token: null, + line: this.yylineno + }); + } + }, + + // return next match that has a token + lex:function lex() { + var r = this.next(); + if (r) { + return r; + } else { + return this.lex(); + } + }, + + // activates a new lexer condition state (pushes the new lexer condition state onto the condition stack) + begin:function begin(condition) { + this.conditionStack.push(condition); + }, + + // pop the previously active lexer condition state off the condition stack + popState:function popState() { + var n = this.conditionStack.length - 1; + if (n > 0) { + return this.conditionStack.pop(); + } else { + return this.conditionStack[0]; + } + }, + + // produce the lexer rule set which is active for the currently active lexer condition state + _currentRules:function _currentRules() { + if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) { + return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules; + } else { + return this.conditions["INITIAL"].rules; + } + }, + + // return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available + topState:function topState(n) { + n = this.conditionStack.length - 1 - Math.abs(n || 0); + if (n >= 0) { + return this.conditionStack[n]; + } else { + return "INITIAL"; + } + }, + + // alias for begin(condition) + pushState:function pushState(condition) { + this.begin(condition); + }, + + // return the number of states currently on the stack + stateStackSize:function stateStackSize() { + return this.conditionStack.length; + }, + options: {}, + performAction: function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { + switch($avoiding_name_collisions) { + case 0:/* skip whitespace */ + break; + case 1:return 6 + case 2:yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2); return 4 + case 3:return 17 + case 4:return 18 + case 5:return 23 + case 6:return 24 + case 7:return 22 + case 8:return 21 + case 9:return 10 + case 10:return 11 + case 11:return 8 + case 12:return 14 + case 13:return 'INVALID' + } + }, + rules: [/^(?:\s+)/,/^(?:(-?([0-9]|[1-9][0-9]+))(\.[0-9]+)?([eE][-+]?[0-9]+)?\b)/,/^(?:"(?:\\[\\"bfnrt/]|\\u[a-fA-F0-9]{4}|[^\\\0-\x09\x0a-\x1f"])*")/,/^(?:\{)/,/^(?:\})/,/^(?:\[)/,/^(?:\])/,/^(?:,)/,/^(?::)/,/^(?:true\b)/,/^(?:false\b)/,/^(?:null\b)/,/^(?:$)/,/^(?:.)/], + conditions: {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13],"inclusive":true}} + }); + return lexer; + })(); + parser.lexer = lexer; + function Parser () { + this.yy = {}; + } + Parser.prototype = parser;parser.Parser = Parser; + return new Parser; + })(); + + + if (typeof commonjsRequire !== 'undefined' && 'object' !== 'undefined') { + exports.parser = parser; + exports.Parser = parser.Parser; + exports.parse = function () { return parser.parse.apply(parser, arguments); }; + } + }); + var jsonlint_1 = jsonlint.parser; + var jsonlint_2 = jsonlint.Parser; + var jsonlint_3 = jsonlint.parse; + + function readStyle(style) { + if (style instanceof String || typeof style === 'string' || style instanceof Buffer) { + try { + return jsonlint.parse(style.toString()); + } catch (e) { + throw new ParsingError$1(e); + } + } + return style; + } + + function validateStyle(style, styleSpec) { + if (styleSpec === void 0) + styleSpec = v8; + var s = style; + try { + s = readStyle(s); + } catch (e) { + return [e]; + } + return validateStyleMin(s, styleSpec); + } + + var SUPPORTED_SPEC_VERSION = 8; + var MAX_SOURCES_IN_STYLE = 15; + function isValid(value, regex) { + if (!value || getType(value) !== 'string') { + return true; + } + return !!value.match(regex); + } + function getSourceCount(source) { + if (source.url) { + return source.url.split(',').length; + } else { + return 0; + } + } + function getAllowedKeyErrors(obj, keys, path) { + var allowed = new Set(keys); + var errors = []; + Object.keys(obj).forEach(function (k) { + if (!allowed.has(k)) { + var prop = path ? path + '.' + k : null; + errors.push(new ValidationError(prop, obj[k], 'Unsupported property "' + k + '"')); + } + }); + return errors; + } + function getSourceErrors(source, i) { + var errors = []; + var sourceKeys = [ + 'type', + 'url', + 'tileSize' + ]; + errors.push.apply(errors, getAllowedKeyErrors(source, sourceKeys, 'source')); + var sourceUrlPattern = /^mapbox:\/\/([^/]*)$/; + if (!isValid(source.url, sourceUrlPattern)) { + errors.push(new ValidationError('sources[' + i + ']', source.url, 'Source url must be a valid Mapbox tileset url')); + } + return errors; + } + function getSourcesErrors(sources) { + var errors = []; + var count = 0; + Object.keys(sources).forEach(function (s, i) { + var sourceErrors = getSourceErrors(sources[s], i); + if (!sourceErrors.length) { + count = count + getSourceCount(sources[s]); + } + errors.push.apply(errors, sourceErrors); + }); + if (count > MAX_SOURCES_IN_STYLE) { + errors.push(new ValidationError('sources', null, 'Styles must contain ' + MAX_SOURCES_IN_STYLE + ' or fewer sources')); + } + return errors; + } + function getRootErrors(style, specKeys) { + var errors = []; + var optionalRootProperties = [ + 'owner', + 'id', + 'cacheControl', + 'draft', + 'created', + 'modified', + 'visibility' + ]; + var allowedKeyErrors = getAllowedKeyErrors(style, specKeys.concat(optionalRootProperties)); + errors.push.apply(errors, allowedKeyErrors); + if (style.version > SUPPORTED_SPEC_VERSION || style.version < SUPPORTED_SPEC_VERSION) { + errors.push(new ValidationError('version', style.version, 'Style version must be ' + SUPPORTED_SPEC_VERSION)); + } + var glyphUrlPattern = /^mapbox:\/\/fonts\/([^/]*)\/{fontstack}\/{range}.pbf$/; + if (!isValid(style.glyphs, glyphUrlPattern)) { + errors.push(new ValidationError('glyphs', style.glyphs, 'Styles must reference glyphs hosted by Mapbox')); + } + var spriteUrlPattern = /^mapbox:\/\/sprites\/([^/]*)\/([^/]*)\/?([^/]*)?$/; + if (!isValid(style.sprite, spriteUrlPattern)) { + errors.push(new ValidationError('sprite', style.sprite, 'Styles must reference sprites hosted by Mapbox')); + } + var visibilityPattern = /^(public|private)$/; + if (!isValid(style.visibility, visibilityPattern)) { + errors.push(new ValidationError('visibility', style.visibility, 'Style visibility must be public or private')); + } + return errors; + } + function validateMapboxApiSupported(style) { + var s = style; + try { + s = readStyle(s); + } catch (e) { + return [e]; + } + var errors = validateStyleMin(s, v8).concat(getRootErrors(s, Object.keys(v8.$root))); + if (s.sources) { + errors = errors.concat(getSourcesErrors(s.sources)); + } + return errors; + } + + var expression$1 = { + StyleExpression: StyleExpression, + isExpression: isExpression, + isExpressionFilter: isExpressionFilter, + createExpression: createExpression, + createPropertyExpression: createPropertyExpression, + normalizePropertyExpression: normalizePropertyExpression, + ZoomConstantExpression: ZoomConstantExpression, + ZoomDependentExpression: ZoomDependentExpression, + StylePropertyFunction: StylePropertyFunction + }; + var styleFunction = { + convertFunction: convertFunction, + createFunction: createFunction, + isFunction: isFunction$1 + }; + var visit = { + eachSource: eachSource, + eachLayer: eachLayer, + eachProperty: eachProperty + }; + validateStyle.parsed = validateStyle; + validateStyle.latest = validateStyle; + + exports.Color = Color; + exports.ParsingError = ParsingError$1; + exports.ValidationError = ValidationError; + exports.composite = composite; + exports.convertFilter = convertFilter$1; + exports.derefLayers = derefLayers; + exports.diff = diffStyles; + exports.expression = expression$1; + exports.featureFilter = createFilter; + exports.format = format; + exports.function = styleFunction; + exports.latest = v8; + exports.migrate = migrate; + exports.v8 = v8; + exports.validate = validateStyle; + exports.validateMapboxApiSupported = validateMapboxApiSupported; + exports.visit = visit; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=index.js.map diff --git a/node_modules/mapbox-gl/src/style-spec/dist/index.js.map b/node_modules/mapbox-gl/src/style-spec/dist/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..18738b5bfcb76566218bb785d71e02a289b1f4c6 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../../../node_modules/json-stringify-pretty-compact/index.js","../format.js","../../../node_modules/url/node_modules/punycode/punycode.js","../../../node_modules/url/util.js","../../../node_modules/querystring/decode.js","../../../node_modules/querystring/encode.js","../../../node_modules/querystring/index.js","../../../node_modules/url/url.js","../visit.js","../migrate/v8.js","../util/extend.js","../expression/parsing_error.js","../expression/scope.js","../expression/types.js","../../../node_modules/csscolorparser/csscolorparser.js","../util/color.js","../expression/types/collator.js","../expression/types/formatted.js","../expression/types/resolved_image.js","../expression/values.js","../expression/definitions/literal.js","../expression/runtime_error.js","../expression/definitions/assertion.js","../expression/definitions/format.js","../expression/definitions/image.js","../expression/definitions/coercion.js","../expression/evaluation_context.js","../expression/compound_expression.js","../expression/definitions/collator.js","../expression/definitions/within.js","../expression/is_constant.js","../expression/definitions/var.js","../expression/parsing_context.js","../expression/stops.js","../expression/definitions/step.js","../../../node_modules/@mapbox/unitbezier/index.js","../util/interpolate.js","../util/color_spaces.js","../expression/definitions/interpolate.js","../expression/definitions/coalesce.js","../expression/definitions/let.js","../expression/definitions/at.js","../expression/definitions/in.js","../expression/definitions/index_of.js","../expression/definitions/match.js","../expression/definitions/case.js","../expression/definitions/slice.js","../expression/definitions/comparison.js","../expression/definitions/number_format.js","../expression/definitions/length.js","../expression/definitions/index.js","../util/result.js","../util/properties.js","../util/get_type.js","../function/index.js","../expression/index.js","../function/convert.js","../feature_filter/index.js","../feature_filter/convert.js","../migrate/expressions.js","../migrate.js","../composite.js","../util/ref_properties.js","../deref.js","../util/deep_equal.js","../diff.js","../error/validation_error.js","../error/parsing_error.js","../validate/validate_constants.js","../util/unbundle_jsonlint.js","../validate/validate_object.js","../validate/validate_array.js","../validate/validate_number.js","../validate/validate_function.js","../validate/validate_expression.js","../validate/validate_boolean.js","../validate/validate_color.js","../validate/validate_enum.js","../validate/validate_filter.js","../validate/validate_property.js","../validate/validate_paint_property.js","../validate/validate_layout_property.js","../validate/validate_layer.js","../validate/validate_string.js","../validate/validate_source.js","../validate/validate_light.js","../validate/validate_formatted.js","../validate/validate_image.js","../validate/validate.js","../validate/validate_glyphs_url.js","../validate_style.min.js","../../../node_modules/@mapbox/jsonlint-lines-primitives/lib/jsonlint.js","../read_style.js","../validate_style.js","../validate_mapbox_api_supported.js","../style-spec.js"],"sourcesContent":["\"use strict\";\n\n// Note: This regex matches even invalid JSON strings, but since we’re\n// working on the output of `JSON.stringify` we know that only valid strings\n// are present (unless the user supplied a weird `options.indent` but in\n// that case we don’t care since the output would be invalid anyway).\nvar stringOrChar = /(\"(?:[^\\\\\"]|\\\\.)*\")|[:,]/g;\n\nmodule.exports = function stringify(passedObj, options) {\n var indent, maxLength, replacer;\n\n options = options || {};\n indent = JSON.stringify(\n [1],\n undefined,\n options.indent === undefined ? 2 : options.indent\n ).slice(2, -3);\n maxLength =\n indent === \"\"\n ? Infinity\n : options.maxLength === undefined\n ? 80\n : options.maxLength;\n replacer = options.replacer;\n\n return (function _stringify(obj, currentIndent, reserved) {\n // prettier-ignore\n var end, index, items, key, keyPart, keys, length, nextIndent, prettified, start, string, value;\n\n if (obj && typeof obj.toJSON === \"function\") {\n obj = obj.toJSON();\n }\n\n string = JSON.stringify(obj, replacer);\n\n if (string === undefined) {\n return string;\n }\n\n length = maxLength - currentIndent.length - reserved;\n\n if (string.length <= length) {\n prettified = string.replace(stringOrChar, function(match, stringLiteral) {\n return stringLiteral || match + \" \";\n });\n if (prettified.length <= length) {\n return prettified;\n }\n }\n\n if (replacer != null) {\n obj = JSON.parse(string);\n replacer = undefined;\n }\n\n if (typeof obj === \"object\" && obj !== null) {\n nextIndent = currentIndent + indent;\n items = [];\n index = 0;\n\n if (Array.isArray(obj)) {\n start = \"[\";\n end = \"]\";\n length = obj.length;\n for (; index < length; index++) {\n items.push(\n _stringify(obj[index], nextIndent, index === length - 1 ? 0 : 1) ||\n \"null\"\n );\n }\n } else {\n start = \"{\";\n end = \"}\";\n keys = Object.keys(obj);\n length = keys.length;\n for (; index < length; index++) {\n key = keys[index];\n keyPart = JSON.stringify(key) + \": \";\n value = _stringify(\n obj[key],\n nextIndent,\n keyPart.length + (index === length - 1 ? 0 : 1)\n );\n if (value !== undefined) {\n items.push(keyPart + value);\n }\n }\n }\n\n if (items.length > 0) {\n return [start, indent + items.join(\",\\n\" + nextIndent), end].join(\n \"\\n\" + currentIndent\n );\n }\n }\n\n return string;\n })(passedObj, \"\", 0);\n};\n","\nimport reference from './reference/latest.js';\nimport stringifyPretty from 'json-stringify-pretty-compact';\n\nfunction sortKeysBy(obj, reference) {\n const result = {};\n for (const key in reference) {\n if (obj[key] !== undefined) {\n result[key] = obj[key];\n }\n }\n for (const key in obj) {\n if (result[key] === undefined) {\n result[key] = obj[key];\n }\n }\n return result;\n}\n\n/**\n * Format a Mapbox GL Style. Returns a stringified style with its keys\n * sorted in the same order as the reference style.\n *\n * The optional `space` argument is passed to\n * [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)\n * to generate formatted output.\n *\n * If `space` is unspecified, a default of `2` spaces will be used.\n *\n * @private\n * @param {Object} style a Mapbox GL Style\n * @param {number} [space] space argument to pass to `JSON.stringify`\n * @returns {string} stringified formatted JSON\n * @example\n * var fs = require('fs');\n * var format = require('mapbox-gl-style-spec').format;\n * var style = fs.readFileSync('./source.json', 'utf8');\n * fs.writeFileSync('./dest.json', format(style));\n * fs.writeFileSync('./dest.min.json', format(style, 0));\n */\nfunction format(style, space = 2) {\n style = sortKeysBy(style, reference.$root);\n\n if (style.layers) {\n style.layers = style.layers.map((layer) => sortKeysBy(layer, reference.layer));\n }\n\n return stringifyPretty(style, {indent: space});\n}\n\nexport default format;\n","/*! https://mths.be/punycode v1.3.2 by @mathias */\n;(function(root) {\n\n\t/** Detect free variables */\n\tvar freeExports = typeof exports == 'object' && exports &&\n\t\t!exports.nodeType && exports;\n\tvar freeModule = typeof module == 'object' && module &&\n\t\t!module.nodeType && module;\n\tvar freeGlobal = typeof global == 'object' && global;\n\tif (\n\t\tfreeGlobal.global === freeGlobal ||\n\t\tfreeGlobal.window === freeGlobal ||\n\t\tfreeGlobal.self === freeGlobal\n\t) {\n\t\troot = freeGlobal;\n\t}\n\n\t/**\n\t * The `punycode` object.\n\t * @name punycode\n\t * @type Object\n\t */\n\tvar punycode,\n\n\t/** Highest positive signed 32-bit float value */\n\tmaxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1\n\n\t/** Bootstring parameters */\n\tbase = 36,\n\ttMin = 1,\n\ttMax = 26,\n\tskew = 38,\n\tdamp = 700,\n\tinitialBias = 72,\n\tinitialN = 128, // 0x80\n\tdelimiter = '-', // '\\x2D'\n\n\t/** Regular expressions */\n\tregexPunycode = /^xn--/,\n\tregexNonASCII = /[^\\x20-\\x7E]/, // unprintable ASCII chars + non-ASCII chars\n\tregexSeparators = /[\\x2E\\u3002\\uFF0E\\uFF61]/g, // RFC 3490 separators\n\n\t/** Error messages */\n\terrors = {\n\t\t'overflow': 'Overflow: input needs wider integers to process',\n\t\t'not-basic': 'Illegal input >= 0x80 (not a basic code point)',\n\t\t'invalid-input': 'Invalid input'\n\t},\n\n\t/** Convenience shortcuts */\n\tbaseMinusTMin = base - tMin,\n\tfloor = Math.floor,\n\tstringFromCharCode = String.fromCharCode,\n\n\t/** Temporary variable */\n\tkey;\n\n\t/*--------------------------------------------------------------------------*/\n\n\t/**\n\t * A generic error utility function.\n\t * @private\n\t * @param {String} type The error type.\n\t * @returns {Error} Throws a `RangeError` with the applicable error message.\n\t */\n\tfunction error(type) {\n\t\tthrow RangeError(errors[type]);\n\t}\n\n\t/**\n\t * A generic `Array#map` utility function.\n\t * @private\n\t * @param {Array} array The array to iterate over.\n\t * @param {Function} callback The function that gets called for every array\n\t * item.\n\t * @returns {Array} A new array of values returned by the callback function.\n\t */\n\tfunction map(array, fn) {\n\t\tvar length = array.length;\n\t\tvar result = [];\n\t\twhile (length--) {\n\t\t\tresult[length] = fn(array[length]);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * A simple `Array#map`-like wrapper to work with domain name strings or email\n\t * addresses.\n\t * @private\n\t * @param {String} domain The domain name or email address.\n\t * @param {Function} callback The function that gets called for every\n\t * character.\n\t * @returns {Array} A new string of characters returned by the callback\n\t * function.\n\t */\n\tfunction mapDomain(string, fn) {\n\t\tvar parts = string.split('@');\n\t\tvar result = '';\n\t\tif (parts.length > 1) {\n\t\t\t// In email addresses, only the domain name should be punycoded. Leave\n\t\t\t// the local part (i.e. everything up to `@`) intact.\n\t\t\tresult = parts[0] + '@';\n\t\t\tstring = parts[1];\n\t\t}\n\t\t// Avoid `split(regex)` for IE8 compatibility. See #17.\n\t\tstring = string.replace(regexSeparators, '\\x2E');\n\t\tvar labels = string.split('.');\n\t\tvar encoded = map(labels, fn).join('.');\n\t\treturn result + encoded;\n\t}\n\n\t/**\n\t * Creates an array containing the numeric code points of each Unicode\n\t * character in the string. While JavaScript uses UCS-2 internally,\n\t * this function will convert a pair of surrogate halves (each of which\n\t * UCS-2 exposes as separate characters) into a single code point,\n\t * matching UTF-16.\n\t * @see `punycode.ucs2.encode`\n\t * @see \n\t * @memberOf punycode.ucs2\n\t * @name decode\n\t * @param {String} string The Unicode input string (UCS-2).\n\t * @returns {Array} The new array of code points.\n\t */\n\tfunction ucs2decode(string) {\n\t\tvar output = [],\n\t\t counter = 0,\n\t\t length = string.length,\n\t\t value,\n\t\t extra;\n\t\twhile (counter < length) {\n\t\t\tvalue = string.charCodeAt(counter++);\n\t\t\tif (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n\t\t\t\t// high surrogate, and there is a next character\n\t\t\t\textra = string.charCodeAt(counter++);\n\t\t\t\tif ((extra & 0xFC00) == 0xDC00) { // low surrogate\n\t\t\t\t\toutput.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n\t\t\t\t} else {\n\t\t\t\t\t// unmatched surrogate; only append this code unit, in case the next\n\t\t\t\t\t// code unit is the high surrogate of a surrogate pair\n\t\t\t\t\toutput.push(value);\n\t\t\t\t\tcounter--;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toutput.push(value);\n\t\t\t}\n\t\t}\n\t\treturn output;\n\t}\n\n\t/**\n\t * Creates a string based on an array of numeric code points.\n\t * @see `punycode.ucs2.decode`\n\t * @memberOf punycode.ucs2\n\t * @name encode\n\t * @param {Array} codePoints The array of numeric code points.\n\t * @returns {String} The new Unicode string (UCS-2).\n\t */\n\tfunction ucs2encode(array) {\n\t\treturn map(array, function(value) {\n\t\t\tvar output = '';\n\t\t\tif (value > 0xFFFF) {\n\t\t\t\tvalue -= 0x10000;\n\t\t\t\toutput += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);\n\t\t\t\tvalue = 0xDC00 | value & 0x3FF;\n\t\t\t}\n\t\t\toutput += stringFromCharCode(value);\n\t\t\treturn output;\n\t\t}).join('');\n\t}\n\n\t/**\n\t * Converts a basic code point into a digit/integer.\n\t * @see `digitToBasic()`\n\t * @private\n\t * @param {Number} codePoint The basic numeric code point value.\n\t * @returns {Number} The numeric value of a basic code point (for use in\n\t * representing integers) in the range `0` to `base - 1`, or `base` if\n\t * the code point does not represent a value.\n\t */\n\tfunction basicToDigit(codePoint) {\n\t\tif (codePoint - 48 < 10) {\n\t\t\treturn codePoint - 22;\n\t\t}\n\t\tif (codePoint - 65 < 26) {\n\t\t\treturn codePoint - 65;\n\t\t}\n\t\tif (codePoint - 97 < 26) {\n\t\t\treturn codePoint - 97;\n\t\t}\n\t\treturn base;\n\t}\n\n\t/**\n\t * Converts a digit/integer into a basic code point.\n\t * @see `basicToDigit()`\n\t * @private\n\t * @param {Number} digit The numeric value of a basic code point.\n\t * @returns {Number} The basic code point whose value (when used for\n\t * representing integers) is `digit`, which needs to be in the range\n\t * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is\n\t * used; else, the lowercase form is used. The behavior is undefined\n\t * if `flag` is non-zero and `digit` has no uppercase form.\n\t */\n\tfunction digitToBasic(digit, flag) {\n\t\t// 0..25 map to ASCII a..z or A..Z\n\t\t// 26..35 map to ASCII 0..9\n\t\treturn digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);\n\t}\n\n\t/**\n\t * Bias adaptation function as per section 3.4 of RFC 3492.\n\t * http://tools.ietf.org/html/rfc3492#section-3.4\n\t * @private\n\t */\n\tfunction adapt(delta, numPoints, firstTime) {\n\t\tvar k = 0;\n\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\tdelta += floor(delta / numPoints);\n\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t}\n\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t}\n\n\t/**\n\t * Converts a Punycode string of ASCII-only symbols to a string of Unicode\n\t * symbols.\n\t * @memberOf punycode\n\t * @param {String} input The Punycode string of ASCII-only symbols.\n\t * @returns {String} The resulting string of Unicode symbols.\n\t */\n\tfunction decode(input) {\n\t\t// Don't use UCS-2\n\t\tvar output = [],\n\t\t inputLength = input.length,\n\t\t out,\n\t\t i = 0,\n\t\t n = initialN,\n\t\t bias = initialBias,\n\t\t basic,\n\t\t j,\n\t\t index,\n\t\t oldi,\n\t\t w,\n\t\t k,\n\t\t digit,\n\t\t t,\n\t\t /** Cached calculation results */\n\t\t baseMinusT;\n\n\t\t// Handle the basic code points: let `basic` be the number of input code\n\t\t// points before the last delimiter, or `0` if there is none, then copy\n\t\t// the first basic code points to the output.\n\n\t\tbasic = input.lastIndexOf(delimiter);\n\t\tif (basic < 0) {\n\t\t\tbasic = 0;\n\t\t}\n\n\t\tfor (j = 0; j < basic; ++j) {\n\t\t\t// if it's not a basic code point\n\t\t\tif (input.charCodeAt(j) >= 0x80) {\n\t\t\t\terror('not-basic');\n\t\t\t}\n\t\t\toutput.push(input.charCodeAt(j));\n\t\t}\n\n\t\t// Main decoding loop: start just after the last delimiter if any basic code\n\t\t// points were copied; start at the beginning otherwise.\n\n\t\tfor (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {\n\n\t\t\t// `index` is the index of the next character to be consumed.\n\t\t\t// Decode a generalized variable-length integer into `delta`,\n\t\t\t// which gets added to `i`. The overflow checking is easier\n\t\t\t// if we increase `i` as we go, then subtract off its starting\n\t\t\t// value at the end to obtain `delta`.\n\t\t\tfor (oldi = i, w = 1, k = base; /* no condition */; k += base) {\n\n\t\t\t\tif (index >= inputLength) {\n\t\t\t\t\terror('invalid-input');\n\t\t\t\t}\n\n\t\t\t\tdigit = basicToDigit(input.charCodeAt(index++));\n\n\t\t\t\tif (digit >= base || digit > floor((maxInt - i) / w)) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\ti += digit * w;\n\t\t\t\tt = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\n\t\t\t\tif (digit < t) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tbaseMinusT = base - t;\n\t\t\t\tif (w > floor(maxInt / baseMinusT)) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\tw *= baseMinusT;\n\n\t\t\t}\n\n\t\t\tout = output.length + 1;\n\t\t\tbias = adapt(i - oldi, out, oldi == 0);\n\n\t\t\t// `i` was supposed to wrap around from `out` to `0`,\n\t\t\t// incrementing `n` each time, so we'll fix that now:\n\t\t\tif (floor(i / out) > maxInt - n) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tn += floor(i / out);\n\t\t\ti %= out;\n\n\t\t\t// Insert `n` at position `i` of the output\n\t\t\toutput.splice(i++, 0, n);\n\n\t\t}\n\n\t\treturn ucs2encode(output);\n\t}\n\n\t/**\n\t * Converts a string of Unicode symbols (e.g. a domain name label) to a\n\t * Punycode string of ASCII-only symbols.\n\t * @memberOf punycode\n\t * @param {String} input The string of Unicode symbols.\n\t * @returns {String} The resulting Punycode string of ASCII-only symbols.\n\t */\n\tfunction encode(input) {\n\t\tvar n,\n\t\t delta,\n\t\t handledCPCount,\n\t\t basicLength,\n\t\t bias,\n\t\t j,\n\t\t m,\n\t\t q,\n\t\t k,\n\t\t t,\n\t\t currentValue,\n\t\t output = [],\n\t\t /** `inputLength` will hold the number of code points in `input`. */\n\t\t inputLength,\n\t\t /** Cached calculation results */\n\t\t handledCPCountPlusOne,\n\t\t baseMinusT,\n\t\t qMinusT;\n\n\t\t// Convert the input in UCS-2 to Unicode\n\t\tinput = ucs2decode(input);\n\n\t\t// Cache the length\n\t\tinputLength = input.length;\n\n\t\t// Initialize the state\n\t\tn = initialN;\n\t\tdelta = 0;\n\t\tbias = initialBias;\n\n\t\t// Handle the basic code points\n\t\tfor (j = 0; j < inputLength; ++j) {\n\t\t\tcurrentValue = input[j];\n\t\t\tif (currentValue < 0x80) {\n\t\t\t\toutput.push(stringFromCharCode(currentValue));\n\t\t\t}\n\t\t}\n\n\t\thandledCPCount = basicLength = output.length;\n\n\t\t// `handledCPCount` is the number of code points that have been handled;\n\t\t// `basicLength` is the number of basic code points.\n\n\t\t// Finish the basic string - if it is not empty - with a delimiter\n\t\tif (basicLength) {\n\t\t\toutput.push(delimiter);\n\t\t}\n\n\t\t// Main encoding loop:\n\t\twhile (handledCPCount < inputLength) {\n\n\t\t\t// All non-basic code points < n have been handled already. Find the next\n\t\t\t// larger one:\n\t\t\tfor (m = maxInt, j = 0; j < inputLength; ++j) {\n\t\t\t\tcurrentValue = input[j];\n\t\t\t\tif (currentValue >= n && currentValue < m) {\n\t\t\t\t\tm = currentValue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Increase `delta` enough to advance the decoder's state to ,\n\t\t\t// but guard against overflow\n\t\t\thandledCPCountPlusOne = handledCPCount + 1;\n\t\t\tif (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tdelta += (m - n) * handledCPCountPlusOne;\n\t\t\tn = m;\n\n\t\t\tfor (j = 0; j < inputLength; ++j) {\n\t\t\t\tcurrentValue = input[j];\n\n\t\t\t\tif (currentValue < n && ++delta > maxInt) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\tif (currentValue == n) {\n\t\t\t\t\t// Represent delta as a generalized variable-length integer\n\t\t\t\t\tfor (q = delta, k = base; /* no condition */; k += base) {\n\t\t\t\t\t\tt = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\t\t\t\t\t\tif (q < t) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tqMinusT = q - t;\n\t\t\t\t\t\tbaseMinusT = base - t;\n\t\t\t\t\t\toutput.push(\n\t\t\t\t\t\t\tstringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))\n\t\t\t\t\t\t);\n\t\t\t\t\t\tq = floor(qMinusT / baseMinusT);\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(stringFromCharCode(digitToBasic(q, 0)));\n\t\t\t\t\tbias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);\n\t\t\t\t\tdelta = 0;\n\t\t\t\t\t++handledCPCount;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t++delta;\n\t\t\t++n;\n\n\t\t}\n\t\treturn output.join('');\n\t}\n\n\t/**\n\t * Converts a Punycode string representing a domain name or an email address\n\t * to Unicode. Only the Punycoded parts of the input will be converted, i.e.\n\t * it doesn't matter if you call it on a string that has already been\n\t * converted to Unicode.\n\t * @memberOf punycode\n\t * @param {String} input The Punycoded domain name or email address to\n\t * convert to Unicode.\n\t * @returns {String} The Unicode representation of the given Punycode\n\t * string.\n\t */\n\tfunction toUnicode(input) {\n\t\treturn mapDomain(input, function(string) {\n\t\t\treturn regexPunycode.test(string)\n\t\t\t\t? decode(string.slice(4).toLowerCase())\n\t\t\t\t: string;\n\t\t});\n\t}\n\n\t/**\n\t * Converts a Unicode string representing a domain name or an email address to\n\t * Punycode. Only the non-ASCII parts of the domain name will be converted,\n\t * i.e. it doesn't matter if you call it with a domain that's already in\n\t * ASCII.\n\t * @memberOf punycode\n\t * @param {String} input The domain name or email address to convert, as a\n\t * Unicode string.\n\t * @returns {String} The Punycode representation of the given domain name or\n\t * email address.\n\t */\n\tfunction toASCII(input) {\n\t\treturn mapDomain(input, function(string) {\n\t\t\treturn regexNonASCII.test(string)\n\t\t\t\t? 'xn--' + encode(string)\n\t\t\t\t: string;\n\t\t});\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\t/** Define the public API */\n\tpunycode = {\n\t\t/**\n\t\t * A string representing the current Punycode.js version number.\n\t\t * @memberOf punycode\n\t\t * @type String\n\t\t */\n\t\t'version': '1.3.2',\n\t\t/**\n\t\t * An object of methods to convert from JavaScript's internal character\n\t\t * representation (UCS-2) to Unicode code points, and back.\n\t\t * @see \n\t\t * @memberOf punycode\n\t\t * @type Object\n\t\t */\n\t\t'ucs2': {\n\t\t\t'decode': ucs2decode,\n\t\t\t'encode': ucs2encode\n\t\t},\n\t\t'decode': decode,\n\t\t'encode': encode,\n\t\t'toASCII': toASCII,\n\t\t'toUnicode': toUnicode\n\t};\n\n\t/** Expose `punycode` */\n\t// Some AMD build optimizers, like r.js, check for specific condition patterns\n\t// like the following:\n\tif (\n\t\ttypeof define == 'function' &&\n\t\ttypeof define.amd == 'object' &&\n\t\tdefine.amd\n\t) {\n\t\tdefine('punycode', function() {\n\t\t\treturn punycode;\n\t\t});\n\t} else if (freeExports && freeModule) {\n\t\tif (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+\n\t\t\tfreeModule.exports = punycode;\n\t\t} else { // in Narwhal or RingoJS v0.7.0-\n\t\t\tfor (key in punycode) {\n\t\t\t\tpunycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);\n\t\t\t}\n\t\t}\n\t} else { // in Rhino or a web browser\n\t\troot.punycode = punycode;\n\t}\n\n}(this));\n","'use strict';\n\nmodule.exports = {\n isString: function(arg) {\n return typeof(arg) === 'string';\n },\n isObject: function(arg) {\n return typeof(arg) === 'object' && arg !== null;\n },\n isNull: function(arg) {\n return arg === null;\n },\n isNullOrUndefined: function(arg) {\n return arg == null;\n }\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nmodule.exports = function(qs, sep, eq, options) {\n sep = sep || '&';\n eq = eq || '=';\n var obj = {};\n\n if (typeof qs !== 'string' || qs.length === 0) {\n return obj;\n }\n\n var regexp = /\\+/g;\n qs = qs.split(sep);\n\n var maxKeys = 1000;\n if (options && typeof options.maxKeys === 'number') {\n maxKeys = options.maxKeys;\n }\n\n var len = qs.length;\n // maxKeys <= 0 means that we should not limit keys count\n if (maxKeys > 0 && len > maxKeys) {\n len = maxKeys;\n }\n\n for (var i = 0; i < len; ++i) {\n var x = qs[i].replace(regexp, '%20'),\n idx = x.indexOf(eq),\n kstr, vstr, k, v;\n\n if (idx >= 0) {\n kstr = x.substr(0, idx);\n vstr = x.substr(idx + 1);\n } else {\n kstr = x;\n vstr = '';\n }\n\n k = decodeURIComponent(kstr);\n v = decodeURIComponent(vstr);\n\n if (!hasOwnProperty(obj, k)) {\n obj[k] = v;\n } else if (Array.isArray(obj[k])) {\n obj[k].push(v);\n } else {\n obj[k] = [obj[k], v];\n }\n }\n\n return obj;\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar stringifyPrimitive = function(v) {\n switch (typeof v) {\n case 'string':\n return v;\n\n case 'boolean':\n return v ? 'true' : 'false';\n\n case 'number':\n return isFinite(v) ? v : '';\n\n default:\n return '';\n }\n};\n\nmodule.exports = function(obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n\n if (typeof obj === 'object') {\n return Object.keys(obj).map(function(k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (Array.isArray(obj[k])) {\n return obj[k].map(function(v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).join(sep);\n\n }\n\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq +\n encodeURIComponent(stringifyPrimitive(obj));\n};\n","'use strict';\n\nexports.decode = exports.parse = require('./decode');\nexports.encode = exports.stringify = require('./encode');\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar punycode = require('punycode');\nvar util = require('./util');\n\nexports.parse = urlParse;\nexports.resolve = urlResolve;\nexports.resolveObject = urlResolveObject;\nexports.format = urlFormat;\n\nexports.Url = Url;\n\nfunction Url() {\n this.protocol = null;\n this.slashes = null;\n this.auth = null;\n this.host = null;\n this.port = null;\n this.hostname = null;\n this.hash = null;\n this.search = null;\n this.query = null;\n this.pathname = null;\n this.path = null;\n this.href = null;\n}\n\n// Reference: RFC 3986, RFC 1808, RFC 2396\n\n// define these here so at least they only have to be\n// compiled once on the first module load.\nvar protocolPattern = /^([a-z0-9.+-]+:)/i,\n portPattern = /:[0-9]*$/,\n\n // Special case for a simple path URL\n simplePathPattern = /^(\\/\\/?(?!\\/)[^\\?\\s]*)(\\?[^\\s]*)?$/,\n\n // RFC 2396: characters reserved for delimiting URLs.\n // We actually just auto-escape these.\n delims = ['<', '>', '\"', '`', ' ', '\\r', '\\n', '\\t'],\n\n // RFC 2396: characters not allowed for various reasons.\n unwise = ['{', '}', '|', '\\\\', '^', '`'].concat(delims),\n\n // Allowed by RFCs, but cause of XSS attacks. Always escape these.\n autoEscape = ['\\''].concat(unwise),\n // Characters that are never ever allowed in a hostname.\n // Note that any invalid chars are also handled, but these\n // are the ones that are *expected* to be seen, so we fast-path\n // them.\n nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),\n hostEndingChars = ['/', '?', '#'],\n hostnameMaxLen = 255,\n hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,\n hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,\n // protocols that can allow \"unsafe\" and \"unwise\" chars.\n unsafeProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that never have a hostname.\n hostlessProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that always contain a // bit.\n slashedProtocol = {\n 'http': true,\n 'https': true,\n 'ftp': true,\n 'gopher': true,\n 'file': true,\n 'http:': true,\n 'https:': true,\n 'ftp:': true,\n 'gopher:': true,\n 'file:': true\n },\n querystring = require('querystring');\n\nfunction urlParse(url, parseQueryString, slashesDenoteHost) {\n if (url && util.isObject(url) && url instanceof Url) return url;\n\n var u = new Url;\n u.parse(url, parseQueryString, slashesDenoteHost);\n return u;\n}\n\nUrl.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {\n if (!util.isString(url)) {\n throw new TypeError(\"Parameter 'url' must be a string, not \" + typeof url);\n }\n\n // Copy chrome, IE, opera backslash-handling behavior.\n // Back slashes before the query string get converted to forward slashes\n // See: https://code.google.com/p/chromium/issues/detail?id=25916\n var queryIndex = url.indexOf('?'),\n splitter =\n (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',\n uSplit = url.split(splitter),\n slashRegex = /\\\\/g;\n uSplit[0] = uSplit[0].replace(slashRegex, '/');\n url = uSplit.join(splitter);\n\n var rest = url;\n\n // trim before proceeding.\n // This is to support parse stuff like \" http://foo.com \\n\"\n rest = rest.trim();\n\n if (!slashesDenoteHost && url.split('#').length === 1) {\n // Try fast path regexp\n var simplePath = simplePathPattern.exec(rest);\n if (simplePath) {\n this.path = rest;\n this.href = rest;\n this.pathname = simplePath[1];\n if (simplePath[2]) {\n this.search = simplePath[2];\n if (parseQueryString) {\n this.query = querystring.parse(this.search.substr(1));\n } else {\n this.query = this.search.substr(1);\n }\n } else if (parseQueryString) {\n this.search = '';\n this.query = {};\n }\n return this;\n }\n }\n\n var proto = protocolPattern.exec(rest);\n if (proto) {\n proto = proto[0];\n var lowerProto = proto.toLowerCase();\n this.protocol = lowerProto;\n rest = rest.substr(proto.length);\n }\n\n // figure out if it's got a host\n // user@server is *always* interpreted as a hostname, and url\n // resolution will treat //foo/bar as host=foo,path=bar because that's\n // how the browser resolves relative URLs.\n if (slashesDenoteHost || proto || rest.match(/^\\/\\/[^@\\/]+@[^@\\/]+/)) {\n var slashes = rest.substr(0, 2) === '//';\n if (slashes && !(proto && hostlessProtocol[proto])) {\n rest = rest.substr(2);\n this.slashes = true;\n }\n }\n\n if (!hostlessProtocol[proto] &&\n (slashes || (proto && !slashedProtocol[proto]))) {\n\n // there's a hostname.\n // the first instance of /, ?, ;, or # ends the host.\n //\n // If there is an @ in the hostname, then non-host chars *are* allowed\n // to the left of the last @ sign, unless some host-ending character\n // comes *before* the @-sign.\n // URLs are obnoxious.\n //\n // ex:\n // http://a@b@c/ => user:a@b host:c\n // http://a@b?@c => user:a host:c path:/?@c\n\n // v0.12 TODO(isaacs): This is not quite how Chrome does things.\n // Review our test case against browsers more comprehensively.\n\n // find the first instance of any hostEndingChars\n var hostEnd = -1;\n for (var i = 0; i < hostEndingChars.length; i++) {\n var hec = rest.indexOf(hostEndingChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))\n hostEnd = hec;\n }\n\n // at this point, either we have an explicit point where the\n // auth portion cannot go past, or the last @ char is the decider.\n var auth, atSign;\n if (hostEnd === -1) {\n // atSign can be anywhere.\n atSign = rest.lastIndexOf('@');\n } else {\n // atSign must be in auth portion.\n // http://a@b/c@d => host:b auth:a path:/c@d\n atSign = rest.lastIndexOf('@', hostEnd);\n }\n\n // Now we have a portion which is definitely the auth.\n // Pull that off.\n if (atSign !== -1) {\n auth = rest.slice(0, atSign);\n rest = rest.slice(atSign + 1);\n this.auth = decodeURIComponent(auth);\n }\n\n // the host is the remaining to the left of the first non-host char\n hostEnd = -1;\n for (var i = 0; i < nonHostChars.length; i++) {\n var hec = rest.indexOf(nonHostChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))\n hostEnd = hec;\n }\n // if we still have not hit it, then the entire thing is a host.\n if (hostEnd === -1)\n hostEnd = rest.length;\n\n this.host = rest.slice(0, hostEnd);\n rest = rest.slice(hostEnd);\n\n // pull out port.\n this.parseHost();\n\n // we've indicated that there is a hostname,\n // so even if it's empty, it has to be present.\n this.hostname = this.hostname || '';\n\n // if hostname begins with [ and ends with ]\n // assume that it's an IPv6 address.\n var ipv6Hostname = this.hostname[0] === '[' &&\n this.hostname[this.hostname.length - 1] === ']';\n\n // validate a little.\n if (!ipv6Hostname) {\n var hostparts = this.hostname.split(/\\./);\n for (var i = 0, l = hostparts.length; i < l; i++) {\n var part = hostparts[i];\n if (!part) continue;\n if (!part.match(hostnamePartPattern)) {\n var newpart = '';\n for (var j = 0, k = part.length; j < k; j++) {\n if (part.charCodeAt(j) > 127) {\n // we replace non-ASCII char with a temporary placeholder\n // we need this to make sure size of hostname is not\n // broken by replacing non-ASCII by nothing\n newpart += 'x';\n } else {\n newpart += part[j];\n }\n }\n // we test again with ASCII char only\n if (!newpart.match(hostnamePartPattern)) {\n var validParts = hostparts.slice(0, i);\n var notHost = hostparts.slice(i + 1);\n var bit = part.match(hostnamePartStart);\n if (bit) {\n validParts.push(bit[1]);\n notHost.unshift(bit[2]);\n }\n if (notHost.length) {\n rest = '/' + notHost.join('.') + rest;\n }\n this.hostname = validParts.join('.');\n break;\n }\n }\n }\n }\n\n if (this.hostname.length > hostnameMaxLen) {\n this.hostname = '';\n } else {\n // hostnames are always lower case.\n this.hostname = this.hostname.toLowerCase();\n }\n\n if (!ipv6Hostname) {\n // IDNA Support: Returns a punycoded representation of \"domain\".\n // It only converts parts of the domain name that\n // have non-ASCII characters, i.e. it doesn't matter if\n // you call it with a domain that already is ASCII-only.\n this.hostname = punycode.toASCII(this.hostname);\n }\n\n var p = this.port ? ':' + this.port : '';\n var h = this.hostname || '';\n this.host = h + p;\n this.href += this.host;\n\n // strip [ and ] from the hostname\n // the host field still retains them, though\n if (ipv6Hostname) {\n this.hostname = this.hostname.substr(1, this.hostname.length - 2);\n if (rest[0] !== '/') {\n rest = '/' + rest;\n }\n }\n }\n\n // now rest is set to the post-host stuff.\n // chop off any delim chars.\n if (!unsafeProtocol[lowerProto]) {\n\n // First, make 100% sure that any \"autoEscape\" chars get\n // escaped, even if encodeURIComponent doesn't think they\n // need to be.\n for (var i = 0, l = autoEscape.length; i < l; i++) {\n var ae = autoEscape[i];\n if (rest.indexOf(ae) === -1)\n continue;\n var esc = encodeURIComponent(ae);\n if (esc === ae) {\n esc = escape(ae);\n }\n rest = rest.split(ae).join(esc);\n }\n }\n\n\n // chop off from the tail first.\n var hash = rest.indexOf('#');\n if (hash !== -1) {\n // got a fragment string.\n this.hash = rest.substr(hash);\n rest = rest.slice(0, hash);\n }\n var qm = rest.indexOf('?');\n if (qm !== -1) {\n this.search = rest.substr(qm);\n this.query = rest.substr(qm + 1);\n if (parseQueryString) {\n this.query = querystring.parse(this.query);\n }\n rest = rest.slice(0, qm);\n } else if (parseQueryString) {\n // no query string, but parseQueryString still requested\n this.search = '';\n this.query = {};\n }\n if (rest) this.pathname = rest;\n if (slashedProtocol[lowerProto] &&\n this.hostname && !this.pathname) {\n this.pathname = '/';\n }\n\n //to support http.request\n if (this.pathname || this.search) {\n var p = this.pathname || '';\n var s = this.search || '';\n this.path = p + s;\n }\n\n // finally, reconstruct the href based on what has been validated.\n this.href = this.format();\n return this;\n};\n\n// format a parsed object into a url string\nfunction urlFormat(obj) {\n // ensure it's an object, and not a string url.\n // If it's an obj, this is a no-op.\n // this way, you can call url_format() on strings\n // to clean up potentially wonky urls.\n if (util.isString(obj)) obj = urlParse(obj);\n if (!(obj instanceof Url)) return Url.prototype.format.call(obj);\n return obj.format();\n}\n\nUrl.prototype.format = function() {\n var auth = this.auth || '';\n if (auth) {\n auth = encodeURIComponent(auth);\n auth = auth.replace(/%3A/i, ':');\n auth += '@';\n }\n\n var protocol = this.protocol || '',\n pathname = this.pathname || '',\n hash = this.hash || '',\n host = false,\n query = '';\n\n if (this.host) {\n host = auth + this.host;\n } else if (this.hostname) {\n host = auth + (this.hostname.indexOf(':') === -1 ?\n this.hostname :\n '[' + this.hostname + ']');\n if (this.port) {\n host += ':' + this.port;\n }\n }\n\n if (this.query &&\n util.isObject(this.query) &&\n Object.keys(this.query).length) {\n query = querystring.stringify(this.query);\n }\n\n var search = this.search || (query && ('?' + query)) || '';\n\n if (protocol && protocol.substr(-1) !== ':') protocol += ':';\n\n // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.\n // unless they had them to begin with.\n if (this.slashes ||\n (!protocol || slashedProtocol[protocol]) && host !== false) {\n host = '//' + (host || '');\n if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;\n } else if (!host) {\n host = '';\n }\n\n if (hash && hash.charAt(0) !== '#') hash = '#' + hash;\n if (search && search.charAt(0) !== '?') search = '?' + search;\n\n pathname = pathname.replace(/[?#]/g, function(match) {\n return encodeURIComponent(match);\n });\n search = search.replace('#', '%23');\n\n return protocol + host + pathname + search + hash;\n};\n\nfunction urlResolve(source, relative) {\n return urlParse(source, false, true).resolve(relative);\n}\n\nUrl.prototype.resolve = function(relative) {\n return this.resolveObject(urlParse(relative, false, true)).format();\n};\n\nfunction urlResolveObject(source, relative) {\n if (!source) return relative;\n return urlParse(source, false, true).resolveObject(relative);\n}\n\nUrl.prototype.resolveObject = function(relative) {\n if (util.isString(relative)) {\n var rel = new Url();\n rel.parse(relative, false, true);\n relative = rel;\n }\n\n var result = new Url();\n var tkeys = Object.keys(this);\n for (var tk = 0; tk < tkeys.length; tk++) {\n var tkey = tkeys[tk];\n result[tkey] = this[tkey];\n }\n\n // hash is always overridden, no matter what.\n // even href=\"\" will remove it.\n result.hash = relative.hash;\n\n // if the relative url is empty, then there's nothing left to do here.\n if (relative.href === '') {\n result.href = result.format();\n return result;\n }\n\n // hrefs like //foo/bar always cut to the protocol.\n if (relative.slashes && !relative.protocol) {\n // take everything except the protocol from relative\n var rkeys = Object.keys(relative);\n for (var rk = 0; rk < rkeys.length; rk++) {\n var rkey = rkeys[rk];\n if (rkey !== 'protocol')\n result[rkey] = relative[rkey];\n }\n\n //urlParse appends trailing / to urls like http://www.example.com\n if (slashedProtocol[result.protocol] &&\n result.hostname && !result.pathname) {\n result.path = result.pathname = '/';\n }\n\n result.href = result.format();\n return result;\n }\n\n if (relative.protocol && relative.protocol !== result.protocol) {\n // if it's a known url protocol, then changing\n // the protocol does weird things\n // first, if it's not file:, then we MUST have a host,\n // and if there was a path\n // to begin with, then we MUST have a path.\n // if it is file:, then the host is dropped,\n // because that's known to be hostless.\n // anything else is assumed to be absolute.\n if (!slashedProtocol[relative.protocol]) {\n var keys = Object.keys(relative);\n for (var v = 0; v < keys.length; v++) {\n var k = keys[v];\n result[k] = relative[k];\n }\n result.href = result.format();\n return result;\n }\n\n result.protocol = relative.protocol;\n if (!relative.host && !hostlessProtocol[relative.protocol]) {\n var relPath = (relative.pathname || '').split('/');\n while (relPath.length && !(relative.host = relPath.shift()));\n if (!relative.host) relative.host = '';\n if (!relative.hostname) relative.hostname = '';\n if (relPath[0] !== '') relPath.unshift('');\n if (relPath.length < 2) relPath.unshift('');\n result.pathname = relPath.join('/');\n } else {\n result.pathname = relative.pathname;\n }\n result.search = relative.search;\n result.query = relative.query;\n result.host = relative.host || '';\n result.auth = relative.auth;\n result.hostname = relative.hostname || relative.host;\n result.port = relative.port;\n // to support http.request\n if (result.pathname || result.search) {\n var p = result.pathname || '';\n var s = result.search || '';\n result.path = p + s;\n }\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n }\n\n var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),\n isRelAbs = (\n relative.host ||\n relative.pathname && relative.pathname.charAt(0) === '/'\n ),\n mustEndAbs = (isRelAbs || isSourceAbs ||\n (result.host && relative.pathname)),\n removeAllDots = mustEndAbs,\n srcPath = result.pathname && result.pathname.split('/') || [],\n relPath = relative.pathname && relative.pathname.split('/') || [],\n psychotic = result.protocol && !slashedProtocol[result.protocol];\n\n // if the url is a non-slashed url, then relative\n // links like ../.. should be able\n // to crawl up to the hostname, as well. This is strange.\n // result.protocol has already been set by now.\n // Later on, put the first path part into the host field.\n if (psychotic) {\n result.hostname = '';\n result.port = null;\n if (result.host) {\n if (srcPath[0] === '') srcPath[0] = result.host;\n else srcPath.unshift(result.host);\n }\n result.host = '';\n if (relative.protocol) {\n relative.hostname = null;\n relative.port = null;\n if (relative.host) {\n if (relPath[0] === '') relPath[0] = relative.host;\n else relPath.unshift(relative.host);\n }\n relative.host = null;\n }\n mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');\n }\n\n if (isRelAbs) {\n // it's absolute.\n result.host = (relative.host || relative.host === '') ?\n relative.host : result.host;\n result.hostname = (relative.hostname || relative.hostname === '') ?\n relative.hostname : result.hostname;\n result.search = relative.search;\n result.query = relative.query;\n srcPath = relPath;\n // fall through to the dot-handling below.\n } else if (relPath.length) {\n // it's relative\n // throw away the existing file, and take the new path instead.\n if (!srcPath) srcPath = [];\n srcPath.pop();\n srcPath = srcPath.concat(relPath);\n result.search = relative.search;\n result.query = relative.query;\n } else if (!util.isNullOrUndefined(relative.search)) {\n // just pull out the search.\n // like href='?foo'.\n // Put this after the other two cases because it simplifies the booleans\n if (psychotic) {\n result.hostname = result.host = srcPath.shift();\n //occationaly the auth can get stuck only in host\n //this especially happens in cases like\n //url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n var authInHost = result.host && result.host.indexOf('@') > 0 ?\n result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.host = result.hostname = authInHost.shift();\n }\n }\n result.search = relative.search;\n result.query = relative.query;\n //to support http.request\n if (!util.isNull(result.pathname) || !util.isNull(result.search)) {\n result.path = (result.pathname ? result.pathname : '') +\n (result.search ? result.search : '');\n }\n result.href = result.format();\n return result;\n }\n\n if (!srcPath.length) {\n // no path at all. easy.\n // we've already handled the other stuff above.\n result.pathname = null;\n //to support http.request\n if (result.search) {\n result.path = '/' + result.search;\n } else {\n result.path = null;\n }\n result.href = result.format();\n return result;\n }\n\n // if a url ENDs in . or .., then it must get a trailing slash.\n // however, if it ends in anything else non-slashy,\n // then it must NOT get a trailing slash.\n var last = srcPath.slice(-1)[0];\n var hasTrailingSlash = (\n (result.host || relative.host || srcPath.length > 1) &&\n (last === '.' || last === '..') || last === '');\n\n // strip single dots, resolve double dots to parent dir\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = srcPath.length; i >= 0; i--) {\n last = srcPath[i];\n if (last === '.') {\n srcPath.splice(i, 1);\n } else if (last === '..') {\n srcPath.splice(i, 1);\n up++;\n } else if (up) {\n srcPath.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (!mustEndAbs && !removeAllDots) {\n for (; up--; up) {\n srcPath.unshift('..');\n }\n }\n\n if (mustEndAbs && srcPath[0] !== '' &&\n (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {\n srcPath.unshift('');\n }\n\n if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {\n srcPath.push('');\n }\n\n var isAbsolute = srcPath[0] === '' ||\n (srcPath[0] && srcPath[0].charAt(0) === '/');\n\n // put the host back\n if (psychotic) {\n result.hostname = result.host = isAbsolute ? '' :\n srcPath.length ? srcPath.shift() : '';\n //occationaly the auth can get stuck only in host\n //this especially happens in cases like\n //url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n var authInHost = result.host && result.host.indexOf('@') > 0 ?\n result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.host = result.hostname = authInHost.shift();\n }\n }\n\n mustEndAbs = mustEndAbs || (result.host && srcPath.length);\n\n if (mustEndAbs && !isAbsolute) {\n srcPath.unshift('');\n }\n\n if (!srcPath.length) {\n result.pathname = null;\n result.path = null;\n } else {\n result.pathname = srcPath.join('/');\n }\n\n //to support request.http\n if (!util.isNull(result.pathname) || !util.isNull(result.search)) {\n result.path = (result.pathname ? result.pathname : '') +\n (result.search ? result.search : '');\n }\n result.auth = relative.auth || result.auth;\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n};\n\nUrl.prototype.parseHost = function() {\n var host = this.host;\n var port = portPattern.exec(host);\n if (port) {\n port = port[0];\n if (port !== ':') {\n this.port = port.substr(1);\n }\n host = host.substr(0, host.length - port.length);\n }\n if (host) this.hostname = host;\n};\n","// @flow\n\nimport Reference from './reference/v8.json';\nimport type {StylePropertySpecification} from './style-spec';\nimport type {\n StyleSpecification,\n SourceSpecification,\n LayerSpecification,\n PropertyValueSpecification,\n DataDrivenPropertyValueSpecification\n} from './types';\n\nfunction getPropertyReference(propertyName): StylePropertySpecification {\n for (let i = 0; i < Reference.layout.length; i++) {\n for (const key in Reference[Reference.layout[i]]) {\n if (key === propertyName) return (Reference[Reference.layout[i]][key]: any);\n }\n }\n for (let i = 0; i < Reference.paint.length; i++) {\n for (const key in Reference[Reference.paint[i]]) {\n if (key === propertyName) return (Reference[Reference.paint[i]][key]: any);\n }\n }\n\n return (null: any);\n}\n\nexport function eachSource(style: StyleSpecification, callback: (_: SourceSpecification) => void) {\n for (const k in style.sources) {\n callback(style.sources[k]);\n }\n}\n\nexport function eachLayer(style: StyleSpecification, callback: (_: LayerSpecification) => void) {\n for (const layer of style.layers) {\n callback(layer);\n }\n}\n\ntype PropertyCallback = ({\n path: [string, 'paint' | 'layout', string], // [layerid, paint/layout, property key]\n key: string,\n value: PropertyValueSpecification | DataDrivenPropertyValueSpecification,\n reference: StylePropertySpecification,\n set: (PropertyValueSpecification | DataDrivenPropertyValueSpecification) => void\n}) => void;\n\nexport function eachProperty(\n style: StyleSpecification,\n options: {paint?: boolean, layout?: boolean},\n callback: PropertyCallback\n) {\n function inner(layer, propertyType: 'paint' | 'layout') {\n const properties = (layer[propertyType]: any);\n if (!properties) return;\n Object.keys(properties).forEach((key) => {\n callback({\n path: [layer.id, propertyType, key],\n key,\n value: properties[key],\n reference: getPropertyReference(key),\n set(x) {\n properties[key] = x;\n }\n });\n });\n }\n\n eachLayer(style, (layer) => {\n if (options.paint) {\n inner(layer, 'paint');\n }\n if (options.layout) {\n inner(layer, 'layout');\n }\n });\n}\n","\nimport URL from 'url';\nimport {eachSource, eachLayer, eachProperty} from '../visit';\n\nfunction eachLayout(layer, callback) {\n for (const k in layer) {\n if (k.indexOf('layout') === 0) {\n callback(layer[k], k);\n }\n }\n}\n\nfunction eachPaint(layer, callback) {\n for (const k in layer) {\n if (k.indexOf('paint') === 0) {\n callback(layer[k], k);\n }\n }\n}\n\nfunction resolveConstant(style, value) {\n if (typeof value === 'string' && value[0] === '@') {\n return resolveConstant(style, style.constants[value]);\n } else {\n return value;\n }\n}\n\nfunction isFunction(value) {\n return Array.isArray(value.stops);\n}\n\nfunction renameProperty(obj, from, to) {\n obj[to] = obj[from]; delete obj[from];\n}\n\nexport default function(style) {\n style.version = 8;\n\n // Rename properties, reverse coordinates in source and layers\n eachSource(style, (source) => {\n if (source.type === 'video' && source.url !== undefined) {\n renameProperty(source, 'url', 'urls');\n }\n if (source.type === 'video') {\n source.coordinates.forEach((coord) => {\n return coord.reverse();\n });\n }\n });\n\n eachLayer(style, (layer) => {\n eachLayout(layer, (layout) => {\n if (layout['symbol-min-distance'] !== undefined) {\n renameProperty(layout, 'symbol-min-distance', 'symbol-spacing');\n }\n });\n\n eachPaint(layer, (paint) => {\n if (paint['background-image'] !== undefined) {\n renameProperty(paint, 'background-image', 'background-pattern');\n }\n if (paint['line-image'] !== undefined) {\n renameProperty(paint, 'line-image', 'line-pattern');\n }\n if (paint['fill-image'] !== undefined) {\n renameProperty(paint, 'fill-image', 'fill-pattern');\n }\n });\n });\n\n // Inline Constants\n eachProperty(style, {paint: true, layout: true}, (property) => {\n const value = resolveConstant(style, property.value);\n\n if (isFunction(value)) {\n value.stops.forEach((stop) => {\n stop[1] = resolveConstant(style, stop[1]);\n });\n }\n\n property.set(value);\n });\n delete style.constants;\n\n eachLayer(style, (layer) => {\n // get rid of text-max-size, icon-max-size\n // turn text-size, icon-size into layout properties\n // https://github.com/mapbox/mapbox-gl-style-spec/issues/255\n\n eachLayout(layer, (layout) => {\n delete layout['text-max-size'];\n delete layout['icon-max-size'];\n });\n\n eachPaint(layer, (paint) => {\n if (paint['text-size']) {\n if (!layer.layout) layer.layout = {};\n layer.layout['text-size'] = paint['text-size'];\n delete paint['text-size'];\n }\n\n if (paint['icon-size']) {\n if (!layer.layout) layer.layout = {};\n layer.layout['icon-size'] = paint['icon-size'];\n delete paint['icon-size'];\n }\n });\n });\n\n function migrateFontstackURL(input) {\n const inputParsed = URL.parse(input);\n const inputPathnameParts = inputParsed.pathname.split('/');\n\n if (inputParsed.protocol !== 'mapbox:') {\n return input;\n\n } else if (inputParsed.hostname === 'fontstack') {\n assert(decodeURI(inputParsed.pathname) === '/{fontstack}/{range}.pbf');\n return 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf';\n\n } else if (inputParsed.hostname === 'fonts') {\n assert(inputPathnameParts[1] === 'v1');\n assert(decodeURI(inputPathnameParts[3]) === '{fontstack}');\n assert(decodeURI(inputPathnameParts[4]) === '{range}.pbf');\n return `mapbox://fonts/${inputPathnameParts[2]}/{fontstack}/{range}.pbf`;\n\n } else {\n assert(false);\n }\n\n function assert(predicate) {\n if (!predicate) {\n throw new Error(`Invalid font url: \"${input}\"`);\n }\n }\n }\n\n if (style.glyphs) {\n style.glyphs = migrateFontstackURL(style.glyphs);\n }\n\n function migrateFontStack(font) {\n function splitAndTrim(string) {\n return string.split(',').map((s) => {\n return s.trim();\n });\n }\n\n if (Array.isArray(font)) {\n // Assume it's a previously migrated font-array.\n return font;\n\n } else if (typeof font === 'string') {\n return splitAndTrim(font);\n\n } else if (typeof font === 'object') {\n font.stops.forEach((stop) => {\n stop[1] = splitAndTrim(stop[1]);\n });\n return font;\n\n } else {\n throw new Error(\"unexpected font value\");\n }\n }\n\n eachLayer(style, (layer) => {\n eachLayout(layer, (layout) => {\n if (layout['text-font']) {\n layout['text-font'] = migrateFontStack(layout['text-font']);\n }\n });\n });\n\n // Reverse order of symbol layers. This is an imperfect migration.\n //\n // The order of a symbol layer in the layers list affects two things:\n // - how it is drawn relative to other layers (like oneway arrows below bridges)\n // - the placement priority compared to other layers\n //\n // It's impossible to reverse the placement priority without breaking the draw order\n // in some cases. This migration only reverses the order of symbol layers that\n // are above all other types of layers.\n //\n // Symbol layers that are at the top of the map preserve their priority.\n // Symbol layers that are below another type (line, fill) of layer preserve their draw order.\n\n let firstSymbolLayer = 0;\n for (let i = style.layers.length - 1; i >= 0; i--) {\n const layer = style.layers[i];\n if (layer.type !== 'symbol') {\n firstSymbolLayer = i + 1;\n break;\n }\n }\n\n const symbolLayers = style.layers.splice(firstSymbolLayer);\n symbolLayers.reverse();\n style.layers = style.layers.concat(symbolLayers);\n\n return style;\n}\n","// @flow\n\nexport default function (output: any, ...inputs: Array) {\n for (const input of inputs) {\n for (const k in input) {\n output[k] = input[k];\n }\n }\n return output;\n}\n","// @flow\n\nclass ParsingError extends Error {\n key: string;\n message: string;\n constructor(key: string, message: string) {\n super(message);\n this.message = message;\n this.key = key;\n }\n}\n\nexport default ParsingError;\n","// @flow\n\nimport type {Expression} from './expression';\n\n/**\n * Tracks `let` bindings during expression parsing.\n * @private\n */\nclass Scope {\n parent: ?Scope;\n bindings: {[_: string]: Expression};\n constructor(parent?: Scope, bindings: Array<[string, Expression]> = []) {\n this.parent = parent;\n this.bindings = {};\n for (const [name, expression] of bindings) {\n this.bindings[name] = expression;\n }\n }\n\n concat(bindings: Array<[string, Expression]>) {\n return new Scope(this, bindings);\n }\n\n get(name: string): Expression {\n if (this.bindings[name]) { return this.bindings[name]; }\n if (this.parent) { return this.parent.get(name); }\n throw new Error(`${name} not found in scope.`);\n }\n\n has(name: string): boolean {\n if (this.bindings[name]) return true;\n return this.parent ? this.parent.has(name) : false;\n }\n}\n\nexport default Scope;\n","// @flow\n\nexport type NullTypeT = { kind: 'null' };\nexport type NumberTypeT = { kind: 'number' };\nexport type StringTypeT = { kind: 'string' };\nexport type BooleanTypeT = { kind: 'boolean' };\nexport type ColorTypeT = { kind: 'color' };\nexport type ObjectTypeT = { kind: 'object' };\nexport type ValueTypeT = { kind: 'value' };\nexport type ErrorTypeT = { kind: 'error' };\nexport type CollatorTypeT = { kind: 'collator' };\nexport type FormattedTypeT = { kind: 'formatted' };\nexport type ResolvedImageTypeT = { kind: 'resolvedImage' };\n\nexport type EvaluationKind = 'constant' | 'source' | 'camera' | 'composite';\n\nexport type Type =\n NullTypeT |\n NumberTypeT |\n StringTypeT |\n BooleanTypeT |\n ColorTypeT |\n ObjectTypeT |\n ValueTypeT |\n ArrayType | // eslint-disable-line no-use-before-define\n ErrorTypeT |\n CollatorTypeT |\n FormattedTypeT |\n ResolvedImageTypeT\n\nexport type ArrayType = {\n kind: 'array',\n itemType: Type,\n N: ?number\n}\n\nexport type NativeType = 'number' | 'string' | 'boolean' | 'null' | 'array' | 'object'\n\nexport const NullType = {kind: 'null'};\nexport const NumberType = {kind: 'number'};\nexport const StringType = {kind: 'string'};\nexport const BooleanType = {kind: 'boolean'};\nexport const ColorType = {kind: 'color'};\nexport const ObjectType = {kind: 'object'};\nexport const ValueType = {kind: 'value'};\nexport const ErrorType = {kind: 'error'};\nexport const CollatorType = {kind: 'collator'};\nexport const FormattedType = {kind: 'formatted'};\nexport const ResolvedImageType = {kind: 'resolvedImage'};\n\nexport function array(itemType: Type, N: ?number): ArrayType {\n return {\n kind: 'array',\n itemType,\n N\n };\n}\n\nexport function toString(type: Type): string {\n if (type.kind === 'array') {\n const itemType = toString(type.itemType);\n return typeof type.N === 'number' ?\n `array<${itemType}, ${type.N}>` :\n type.itemType.kind === 'value' ? 'array' : `array<${itemType}>`;\n } else {\n return type.kind;\n }\n}\n\nconst valueMemberTypes = [\n NullType,\n NumberType,\n StringType,\n BooleanType,\n ColorType,\n FormattedType,\n ObjectType,\n array(ValueType),\n ResolvedImageType\n];\n\n/**\n * Returns null if `t` is a subtype of `expected`; otherwise returns an\n * error message.\n * @private\n */\nexport function checkSubtype(expected: Type, t: Type): ?string {\n if (t.kind === 'error') {\n // Error is a subtype of every type\n return null;\n } else if (expected.kind === 'array') {\n if (t.kind === 'array' &&\n ((t.N === 0 && t.itemType.kind === 'value') || !checkSubtype(expected.itemType, t.itemType)) &&\n (typeof expected.N !== 'number' || expected.N === t.N)) {\n return null;\n }\n } else if (expected.kind === t.kind) {\n return null;\n } else if (expected.kind === 'value') {\n for (const memberType of valueMemberTypes) {\n if (!checkSubtype(memberType, t)) {\n return null;\n }\n }\n }\n\n return `Expected ${toString(expected)} but found ${toString(t)} instead.`;\n}\n\nexport function isValidType(provided: Type, allowedTypes: Array): boolean {\n return allowedTypes.some(t => t.kind === provided.kind);\n}\n\nexport function isValidNativeType(provided: any, allowedTypes: Array): boolean {\n return allowedTypes.some(t => {\n if (t === 'null') {\n return provided === null;\n } else if (t === 'array') {\n return Array.isArray(provided);\n } else if (t === 'object') {\n return provided && !Array.isArray(provided) && typeof provided === 'object';\n } else {\n return t === typeof provided;\n }\n });\n}\n","// (c) Dean McNamee , 2012.\n//\n// https://github.com/deanm/css-color-parser-js\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n\n// http://www.w3.org/TR/css3-color/\nvar kCSSColorTable = {\n \"transparent\": [0,0,0,0], \"aliceblue\": [240,248,255,1],\n \"antiquewhite\": [250,235,215,1], \"aqua\": [0,255,255,1],\n \"aquamarine\": [127,255,212,1], \"azure\": [240,255,255,1],\n \"beige\": [245,245,220,1], \"bisque\": [255,228,196,1],\n \"black\": [0,0,0,1], \"blanchedalmond\": [255,235,205,1],\n \"blue\": [0,0,255,1], \"blueviolet\": [138,43,226,1],\n \"brown\": [165,42,42,1], \"burlywood\": [222,184,135,1],\n \"cadetblue\": [95,158,160,1], \"chartreuse\": [127,255,0,1],\n \"chocolate\": [210,105,30,1], \"coral\": [255,127,80,1],\n \"cornflowerblue\": [100,149,237,1], \"cornsilk\": [255,248,220,1],\n \"crimson\": [220,20,60,1], \"cyan\": [0,255,255,1],\n \"darkblue\": [0,0,139,1], \"darkcyan\": [0,139,139,1],\n \"darkgoldenrod\": [184,134,11,1], \"darkgray\": [169,169,169,1],\n \"darkgreen\": [0,100,0,1], \"darkgrey\": [169,169,169,1],\n \"darkkhaki\": [189,183,107,1], \"darkmagenta\": [139,0,139,1],\n \"darkolivegreen\": [85,107,47,1], \"darkorange\": [255,140,0,1],\n \"darkorchid\": [153,50,204,1], \"darkred\": [139,0,0,1],\n \"darksalmon\": [233,150,122,1], \"darkseagreen\": [143,188,143,1],\n \"darkslateblue\": [72,61,139,1], \"darkslategray\": [47,79,79,1],\n \"darkslategrey\": [47,79,79,1], \"darkturquoise\": [0,206,209,1],\n \"darkviolet\": [148,0,211,1], \"deeppink\": [255,20,147,1],\n \"deepskyblue\": [0,191,255,1], \"dimgray\": [105,105,105,1],\n \"dimgrey\": [105,105,105,1], \"dodgerblue\": [30,144,255,1],\n \"firebrick\": [178,34,34,1], \"floralwhite\": [255,250,240,1],\n \"forestgreen\": [34,139,34,1], \"fuchsia\": [255,0,255,1],\n \"gainsboro\": [220,220,220,1], \"ghostwhite\": [248,248,255,1],\n \"gold\": [255,215,0,1], \"goldenrod\": [218,165,32,1],\n \"gray\": [128,128,128,1], \"green\": [0,128,0,1],\n \"greenyellow\": [173,255,47,1], \"grey\": [128,128,128,1],\n \"honeydew\": [240,255,240,1], \"hotpink\": [255,105,180,1],\n \"indianred\": [205,92,92,1], \"indigo\": [75,0,130,1],\n \"ivory\": [255,255,240,1], \"khaki\": [240,230,140,1],\n \"lavender\": [230,230,250,1], \"lavenderblush\": [255,240,245,1],\n \"lawngreen\": [124,252,0,1], \"lemonchiffon\": [255,250,205,1],\n \"lightblue\": [173,216,230,1], \"lightcoral\": [240,128,128,1],\n \"lightcyan\": [224,255,255,1], \"lightgoldenrodyellow\": [250,250,210,1],\n \"lightgray\": [211,211,211,1], \"lightgreen\": [144,238,144,1],\n \"lightgrey\": [211,211,211,1], \"lightpink\": [255,182,193,1],\n \"lightsalmon\": [255,160,122,1], \"lightseagreen\": [32,178,170,1],\n \"lightskyblue\": [135,206,250,1], \"lightslategray\": [119,136,153,1],\n \"lightslategrey\": [119,136,153,1], \"lightsteelblue\": [176,196,222,1],\n \"lightyellow\": [255,255,224,1], \"lime\": [0,255,0,1],\n \"limegreen\": [50,205,50,1], \"linen\": [250,240,230,1],\n \"magenta\": [255,0,255,1], \"maroon\": [128,0,0,1],\n \"mediumaquamarine\": [102,205,170,1], \"mediumblue\": [0,0,205,1],\n \"mediumorchid\": [186,85,211,1], \"mediumpurple\": [147,112,219,1],\n \"mediumseagreen\": [60,179,113,1], \"mediumslateblue\": [123,104,238,1],\n \"mediumspringgreen\": [0,250,154,1], \"mediumturquoise\": [72,209,204,1],\n \"mediumvioletred\": [199,21,133,1], \"midnightblue\": [25,25,112,1],\n \"mintcream\": [245,255,250,1], \"mistyrose\": [255,228,225,1],\n \"moccasin\": [255,228,181,1], \"navajowhite\": [255,222,173,1],\n \"navy\": [0,0,128,1], \"oldlace\": [253,245,230,1],\n \"olive\": [128,128,0,1], \"olivedrab\": [107,142,35,1],\n \"orange\": [255,165,0,1], \"orangered\": [255,69,0,1],\n \"orchid\": [218,112,214,1], \"palegoldenrod\": [238,232,170,1],\n \"palegreen\": [152,251,152,1], \"paleturquoise\": [175,238,238,1],\n \"palevioletred\": [219,112,147,1], \"papayawhip\": [255,239,213,1],\n \"peachpuff\": [255,218,185,1], \"peru\": [205,133,63,1],\n \"pink\": [255,192,203,1], \"plum\": [221,160,221,1],\n \"powderblue\": [176,224,230,1], \"purple\": [128,0,128,1],\n \"rebeccapurple\": [102,51,153,1],\n \"red\": [255,0,0,1], \"rosybrown\": [188,143,143,1],\n \"royalblue\": [65,105,225,1], \"saddlebrown\": [139,69,19,1],\n \"salmon\": [250,128,114,1], \"sandybrown\": [244,164,96,1],\n \"seagreen\": [46,139,87,1], \"seashell\": [255,245,238,1],\n \"sienna\": [160,82,45,1], \"silver\": [192,192,192,1],\n \"skyblue\": [135,206,235,1], \"slateblue\": [106,90,205,1],\n \"slategray\": [112,128,144,1], \"slategrey\": [112,128,144,1],\n \"snow\": [255,250,250,1], \"springgreen\": [0,255,127,1],\n \"steelblue\": [70,130,180,1], \"tan\": [210,180,140,1],\n \"teal\": [0,128,128,1], \"thistle\": [216,191,216,1],\n \"tomato\": [255,99,71,1], \"turquoise\": [64,224,208,1],\n \"violet\": [238,130,238,1], \"wheat\": [245,222,179,1],\n \"white\": [255,255,255,1], \"whitesmoke\": [245,245,245,1],\n \"yellow\": [255,255,0,1], \"yellowgreen\": [154,205,50,1]}\n\nfunction clamp_css_byte(i) { // Clamp to integer 0 .. 255.\n i = Math.round(i); // Seems to be what Chrome does (vs truncation).\n return i < 0 ? 0 : i > 255 ? 255 : i;\n}\n\nfunction clamp_css_float(f) { // Clamp to float 0.0 .. 1.0.\n return f < 0 ? 0 : f > 1 ? 1 : f;\n}\n\nfunction parse_css_int(str) { // int or percentage.\n if (str[str.length - 1] === '%')\n return clamp_css_byte(parseFloat(str) / 100 * 255);\n return clamp_css_byte(parseInt(str));\n}\n\nfunction parse_css_float(str) { // float or percentage.\n if (str[str.length - 1] === '%')\n return clamp_css_float(parseFloat(str) / 100);\n return clamp_css_float(parseFloat(str));\n}\n\nfunction css_hue_to_rgb(m1, m2, h) {\n if (h < 0) h += 1;\n else if (h > 1) h -= 1;\n\n if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;\n if (h * 2 < 1) return m2;\n if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6;\n return m1;\n}\n\nfunction parseCSSColor(css_str) {\n // Remove all whitespace, not compliant, but should just be more accepting.\n var str = css_str.replace(/ /g, '').toLowerCase();\n\n // Color keywords (and transparent) lookup.\n if (str in kCSSColorTable) return kCSSColorTable[str].slice(); // dup.\n\n // #abc and #abc123 syntax.\n if (str[0] === '#') {\n if (str.length === 4) {\n var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.\n if (!(iv >= 0 && iv <= 0xfff)) return null; // Covers NaN.\n return [((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),\n (iv & 0xf0) | ((iv & 0xf0) >> 4),\n (iv & 0xf) | ((iv & 0xf) << 4),\n 1];\n } else if (str.length === 7) {\n var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.\n if (!(iv >= 0 && iv <= 0xffffff)) return null; // Covers NaN.\n return [(iv & 0xff0000) >> 16,\n (iv & 0xff00) >> 8,\n iv & 0xff,\n 1];\n }\n\n return null;\n }\n\n var op = str.indexOf('('), ep = str.indexOf(')');\n if (op !== -1 && ep + 1 === str.length) {\n var fname = str.substr(0, op);\n var params = str.substr(op+1, ep-(op+1)).split(',');\n var alpha = 1; // To allow case fallthrough.\n switch (fname) {\n case 'rgba':\n if (params.length !== 4) return null;\n alpha = parse_css_float(params.pop());\n // Fall through.\n case 'rgb':\n if (params.length !== 3) return null;\n return [parse_css_int(params[0]),\n parse_css_int(params[1]),\n parse_css_int(params[2]),\n alpha];\n case 'hsla':\n if (params.length !== 4) return null;\n alpha = parse_css_float(params.pop());\n // Fall through.\n case 'hsl':\n if (params.length !== 3) return null;\n var h = (((parseFloat(params[0]) % 360) + 360) % 360) / 360; // 0 .. 1\n // NOTE(deanm): According to the CSS spec s/l should only be\n // percentages, but we don't bother and let float or percentage.\n var s = parse_css_float(params[1]);\n var l = parse_css_float(params[2]);\n var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;\n var m1 = l * 2 - m2;\n return [clamp_css_byte(css_hue_to_rgb(m1, m2, h+1/3) * 255),\n clamp_css_byte(css_hue_to_rgb(m1, m2, h) * 255),\n clamp_css_byte(css_hue_to_rgb(m1, m2, h-1/3) * 255),\n alpha];\n default:\n return null;\n }\n }\n\n return null;\n}\n\ntry { exports.parseCSSColor = parseCSSColor } catch(e) { }\n","// @flow\n\nimport {parseCSSColor} from 'csscolorparser';\n\n/**\n * An RGBA color value. Create instances from color strings using the static\n * method `Color.parse`. The constructor accepts RGB channel values in the range\n * `[0, 1]`, premultiplied by A.\n *\n * @param {number} r The red channel.\n * @param {number} g The green channel.\n * @param {number} b The blue channel.\n * @param {number} a The alpha channel.\n * @private\n */\nclass Color {\n r: number;\n g: number;\n b: number;\n a: number;\n\n constructor(r: number, g: number, b: number, a: number = 1) {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n }\n\n static black: Color;\n static white: Color;\n static transparent: Color;\n static red: Color;\n\n /**\n * Parses valid CSS color strings and returns a `Color` instance.\n * @returns A `Color` instance, or `undefined` if the input is not a valid color string.\n */\n static parse(input?: string | Color | null): Color | void {\n if (!input) {\n return undefined;\n }\n\n if (input instanceof Color) {\n return input;\n }\n\n if (typeof input !== 'string') {\n return undefined;\n }\n\n const rgba = parseCSSColor(input);\n if (!rgba) {\n return undefined;\n }\n\n return new Color(\n rgba[0] / 255 * rgba[3],\n rgba[1] / 255 * rgba[3],\n rgba[2] / 255 * rgba[3],\n rgba[3]\n );\n }\n\n /**\n * Returns an RGBA string representing the color value.\n *\n * @returns An RGBA string.\n * @example\n * var purple = new Color.parse('purple');\n * purple.toString; // = \"rgba(128,0,128,1)\"\n * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)');\n * translucentGreen.toString(); // = \"rgba(26,207,26,0.73)\"\n */\n toString(): string {\n const [r, g, b, a] = this.toArray();\n return `rgba(${Math.round(r)},${Math.round(g)},${Math.round(b)},${a})`;\n }\n\n toArray(): [number, number, number, number] {\n const {r, g, b, a} = this;\n return a === 0 ? [0, 0, 0, 0] : [\n r * 255 / a,\n g * 255 / a,\n b * 255 / a,\n a\n ];\n }\n}\n\nColor.black = new Color(0, 0, 0, 1);\nColor.white = new Color(1, 1, 1, 1);\nColor.transparent = new Color(0, 0, 0, 0);\nColor.red = new Color(1, 0, 0, 1);\n\nexport default Color;\n","// @flow\n\n// Flow type declarations for Intl cribbed from\n// https://github.com/facebook/flow/issues/1270\n\ndeclare var Intl: {\n Collator: Class\n};\n\ndeclare class Intl$Collator {\n constructor (\n locales?: string | string[],\n options?: CollatorOptions\n ): Intl$Collator;\n\n static (\n locales?: string | string[],\n options?: CollatorOptions\n ): Intl$Collator;\n\n compare (a: string, b: string): number;\n\n resolvedOptions(): any;\n}\n\ntype CollatorOptions = {\n localeMatcher?: 'lookup' | 'best fit',\n usage?: 'sort' | 'search',\n sensitivity?: 'base' | 'accent' | 'case' | 'variant',\n ignorePunctuation?: boolean,\n numeric?: boolean,\n caseFirst?: 'upper' | 'lower' | 'false'\n}\n\nexport default class Collator {\n locale: string | null;\n sensitivity: 'base' | 'accent' | 'case' | 'variant';\n collator: Intl$Collator;\n\n constructor(caseSensitive: boolean, diacriticSensitive: boolean, locale: string | null) {\n if (caseSensitive)\n this.sensitivity = diacriticSensitive ? 'variant' : 'case';\n else\n this.sensitivity = diacriticSensitive ? 'accent' : 'base';\n\n this.locale = locale;\n this.collator = new Intl.Collator(this.locale ? this.locale : [],\n {sensitivity: this.sensitivity, usage: 'search'});\n }\n\n compare(lhs: string, rhs: string): number {\n return this.collator.compare(lhs, rhs);\n }\n\n resolvedLocale(): string {\n // We create a Collator without \"usage: search\" because we don't want\n // the search options encoded in our result (e.g. \"en-u-co-search\")\n return new Intl.Collator(this.locale ? this.locale : [])\n .resolvedOptions().locale;\n }\n}\n","// @flow\nimport type Color from '../../util/color';\nimport type ResolvedImage from '../types/resolved_image';\n\nexport class FormattedSection {\n text: string;\n image: ResolvedImage | null;\n scale: number | null;\n fontStack: string | null;\n textColor: Color | null;\n\n constructor(text: string, image: ResolvedImage | null, scale: number | null, fontStack: string | null, textColor: Color | null) {\n this.text = text;\n this.image = image;\n this.scale = scale;\n this.fontStack = fontStack;\n this.textColor = textColor;\n }\n}\n\nexport default class Formatted {\n sections: Array;\n\n constructor(sections: Array) {\n this.sections = sections;\n }\n\n static fromString(unformatted: string): Formatted {\n return new Formatted([new FormattedSection(unformatted, null, null, null, null)]);\n }\n\n isEmpty(): boolean {\n if (this.sections.length === 0) return true;\n return !this.sections.some(section => section.text.length !== 0 ||\n (section.image && section.image.name.length !== 0));\n }\n\n static factory(text: Formatted | string): Formatted {\n if (text instanceof Formatted) {\n return text;\n } else {\n return Formatted.fromString(text);\n }\n }\n\n toString(): string {\n if (this.sections.length === 0) return '';\n return this.sections.map(section => section.text).join('');\n }\n\n serialize(): Array {\n const serialized: Array = [\"format\"];\n for (const section of this.sections) {\n if (section.image) {\n serialized.push([\"image\", section.image.name]);\n continue;\n }\n serialized.push(section.text);\n const options: { [key: string]: mixed } = {};\n if (section.fontStack) {\n options[\"text-font\"] = [\"literal\", section.fontStack.split(',')];\n }\n if (section.scale) {\n options[\"font-scale\"] = section.scale;\n }\n if (section.textColor) {\n options[\"text-color\"] = ([\"rgba\"]: Array).concat(section.textColor.toArray());\n }\n serialized.push(options);\n }\n return serialized;\n }\n}\n","// @flow\n\nexport type ResolvedImageOptions = {\n name: string,\n available: boolean\n};\n\nexport default class ResolvedImage {\n name: string;\n available: boolean;\n\n constructor(options: ResolvedImageOptions) {\n this.name = options.name;\n this.available = options.available;\n }\n\n toString(): string {\n return this.name;\n }\n\n static fromString(name: string): ResolvedImage | null {\n if (!name) return null; // treat empty values as no image\n return new ResolvedImage({name, available: false});\n }\n\n serialize(): Array {\n return [\"image\", this.name];\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport Color from '../util/color';\nimport Collator from './types/collator';\nimport Formatted from './types/formatted';\nimport ResolvedImage from './types/resolved_image';\nimport {NullType, NumberType, StringType, BooleanType, ColorType, ObjectType, ValueType, CollatorType, FormattedType, ResolvedImageType, array} from './types';\n\nimport type {Type} from './types';\n\nexport function validateRGBA(r: mixed, g: mixed, b: mixed, a?: mixed): string | null {\n if (!(\n typeof r === 'number' && r >= 0 && r <= 255 &&\n typeof g === 'number' && g >= 0 && g <= 255 &&\n typeof b === 'number' && b >= 0 && b <= 255\n )) {\n const value = typeof a === 'number' ? [r, g, b, a] : [r, g, b];\n return `Invalid rgba value [${value.join(', ')}]: 'r', 'g', and 'b' must be between 0 and 255.`;\n }\n\n if (!(\n typeof a === 'undefined' || (typeof a === 'number' && a >= 0 && a <= 1)\n )) {\n return `Invalid rgba value [${[r, g, b, a].join(', ')}]: 'a' must be between 0 and 1.`;\n }\n\n return null;\n}\n\nexport type Value = null | string | boolean | number | Color | Collator | Formatted | ResolvedImage | $ReadOnlyArray | { +[string]: Value }\n\nexport function isValue(mixed: mixed): boolean {\n if (mixed === null) {\n return true;\n } else if (typeof mixed === 'string') {\n return true;\n } else if (typeof mixed === 'boolean') {\n return true;\n } else if (typeof mixed === 'number') {\n return true;\n } else if (mixed instanceof Color) {\n return true;\n } else if (mixed instanceof Collator) {\n return true;\n } else if (mixed instanceof Formatted) {\n return true;\n } else if (mixed instanceof ResolvedImage) {\n return true;\n } else if (Array.isArray(mixed)) {\n for (const item of mixed) {\n if (!isValue(item)) {\n return false;\n }\n }\n return true;\n } else if (typeof mixed === 'object') {\n for (const key in mixed) {\n if (!isValue(mixed[key])) {\n return false;\n }\n }\n return true;\n } else {\n return false;\n }\n}\n\nexport function typeOf(value: Value): Type {\n if (value === null) {\n return NullType;\n } else if (typeof value === 'string') {\n return StringType;\n } else if (typeof value === 'boolean') {\n return BooleanType;\n } else if (typeof value === 'number') {\n return NumberType;\n } else if (value instanceof Color) {\n return ColorType;\n } else if (value instanceof Collator) {\n return CollatorType;\n } else if (value instanceof Formatted) {\n return FormattedType;\n } else if (value instanceof ResolvedImage) {\n return ResolvedImageType;\n } else if (Array.isArray(value)) {\n const length = value.length;\n let itemType: Type | typeof undefined;\n\n for (const item of value) {\n const t = typeOf(item);\n if (!itemType) {\n itemType = t;\n } else if (itemType === t) {\n continue;\n } else {\n itemType = ValueType;\n break;\n }\n }\n\n return array(itemType || ValueType, length);\n } else {\n assert(typeof value === 'object');\n return ObjectType;\n }\n}\n\nexport function toString(value: Value) {\n const type = typeof value;\n if (value === null) {\n return '';\n } else if (type === 'string' || type === 'number' || type === 'boolean') {\n return String(value);\n } else if (value instanceof Color || value instanceof Formatted || value instanceof ResolvedImage) {\n return value.toString();\n } else {\n return JSON.stringify(value);\n }\n}\n\nexport {Color, Collator};\n","// @flow\n\nimport assert from 'assert';\nimport {isValue, typeOf, Color} from '../values';\nimport Formatted from '../types/formatted';\n\nimport type {Type} from '../types';\nimport type {Value} from '../values';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\n\nclass Literal implements Expression {\n type: Type;\n value: Value;\n\n constructor(type: Type, value: Value) {\n this.type = type;\n this.value = value;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 2)\n return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`);\n\n if (!isValue(args[1]))\n return context.error(`invalid value`);\n\n const value = (args[1]: any);\n let type = typeOf(value);\n\n // special case: infer the item type if possible for zero-length arrays\n const expected = context.expectedType;\n if (\n type.kind === 'array' &&\n type.N === 0 &&\n expected &&\n expected.kind === 'array' &&\n (typeof expected.N !== 'number' || expected.N === 0)\n ) {\n type = expected;\n }\n\n return new Literal(type, value);\n }\n\n evaluate() {\n return this.value;\n }\n\n eachChild() {}\n\n outputDefined() {\n return true;\n }\n\n serialize(): Array {\n if (this.type.kind === 'array' || this.type.kind === 'object') {\n return [\"literal\", this.value];\n } else if (this.value instanceof Color) {\n // Constant-folding can generate Literal expressions that you\n // couldn't actually generate with a \"literal\" expression,\n // so we have to implement an equivalent serialization here\n return [\"rgba\"].concat(this.value.toArray());\n } else if (this.value instanceof Formatted) {\n // Same as Color\n return this.value.serialize();\n } else {\n assert(this.value === null ||\n typeof this.value === 'string' ||\n typeof this.value === 'number' ||\n typeof this.value === 'boolean');\n return (this.value: any);\n }\n }\n}\n\nexport default Literal;\n","// @flow\n\nclass RuntimeError {\n name: string;\n message: string;\n\n constructor(message: string) {\n this.name = 'ExpressionEvaluationError';\n this.message = message;\n }\n\n toJSON() {\n return this.message;\n }\n}\n\nexport default RuntimeError;\n","// @flow\n\nimport assert from 'assert';\n\nimport {\n ObjectType,\n ValueType,\n StringType,\n NumberType,\n BooleanType,\n checkSubtype,\n toString,\n array\n} from '../types';\nimport RuntimeError from '../runtime_error';\nimport {typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nconst types = {\n string: StringType,\n number: NumberType,\n boolean: BooleanType,\n object: ObjectType\n};\n\nclass Assertion implements Expression {\n type: Type;\n args: Array;\n\n constructor(type: Type, args: Array) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length < 2)\n return context.error(`Expected at least one argument.`);\n\n let i = 1;\n let type;\n\n const name: string = (args[0]: any);\n if (name === 'array') {\n let itemType;\n if (args.length > 2) {\n const type = args[1];\n if (typeof type !== 'string' || !(type in types) || type === 'object')\n return context.error('The item type argument of \"array\" must be one of string, number, boolean', 1);\n itemType = types[type];\n i++;\n } else {\n itemType = ValueType;\n }\n\n let N;\n if (args.length > 3) {\n if (args[2] !== null &&\n (typeof args[2] !== 'number' ||\n args[2] < 0 ||\n args[2] !== Math.floor(args[2]))\n ) {\n return context.error('The length argument to \"array\" must be a positive integer literal', 2);\n }\n N = args[2];\n i++;\n }\n\n type = array(itemType, N);\n } else {\n assert(types[name], name);\n type = types[name];\n }\n\n const parsed = [];\n for (; i < args.length; i++) {\n const input = context.parse(args[i], i, ValueType);\n if (!input) return null;\n parsed.push(input);\n }\n\n return new Assertion(type, parsed);\n }\n\n evaluate(ctx: EvaluationContext) {\n for (let i = 0; i < this.args.length; i++) {\n const value = this.args[i].evaluate(ctx);\n const error = checkSubtype(this.type, typeOf(value));\n if (!error) {\n return value;\n } else if (i === this.args.length - 1) {\n throw new RuntimeError(`Expected value to be of type ${toString(this.type)}, but found ${toString(typeOf(value))} instead.`);\n }\n }\n\n assert(false);\n return null;\n }\n\n eachChild(fn: (_: Expression) => void) {\n this.args.forEach(fn);\n }\n\n outputDefined(): boolean {\n return this.args.every(arg => arg.outputDefined());\n }\n\n serialize(): Array {\n const type = this.type;\n const serialized = [type.kind];\n if (type.kind === 'array') {\n const itemType = type.itemType;\n if (itemType.kind === 'string' ||\n itemType.kind === 'number' ||\n itemType.kind === 'boolean') {\n serialized.push(itemType.kind);\n const N = type.N;\n if (typeof N === 'number' || this.args.length > 1) {\n serialized.push(N);\n }\n }\n }\n return serialized.concat(this.args.map(arg => arg.serialize()));\n }\n}\n\nexport default Assertion;\n","// @flow\n\nimport {NumberType, ValueType, FormattedType, array, StringType, ColorType, ResolvedImageType} from '../types';\nimport Formatted, {FormattedSection} from '../types/formatted';\nimport {toString, typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\n\ntype FormattedSectionExpression = {\n // Content of a section may be Image expression or other\n // type of expression that is coercable to 'string'.\n content: Expression,\n scale: Expression | null;\n font: Expression | null;\n textColor: Expression | null;\n}\n\nexport default class FormatExpression implements Expression {\n type: Type;\n sections: Array;\n\n constructor(sections: Array) {\n this.type = FormattedType;\n this.sections = sections;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length < 2) {\n return context.error(`Expected at least one argument.`);\n }\n\n const firstArg = args[1];\n if (!Array.isArray(firstArg) && typeof firstArg === 'object') {\n return context.error(`First argument must be an image or text section.`);\n }\n\n const sections: Array = [];\n let nextTokenMayBeObject = false;\n for (let i = 1; i <= args.length - 1; ++i) {\n const arg = (args[i]: any);\n\n if (nextTokenMayBeObject && typeof arg === \"object\" && !Array.isArray(arg)) {\n nextTokenMayBeObject = false;\n\n let scale = null;\n if (arg['font-scale']) {\n scale = context.parse(arg['font-scale'], 1, NumberType);\n if (!scale) return null;\n }\n\n let font = null;\n if (arg['text-font']) {\n font = context.parse(arg['text-font'], 1, array(StringType));\n if (!font) return null;\n }\n\n let textColor = null;\n if (arg['text-color']) {\n textColor = context.parse(arg['text-color'], 1, ColorType);\n if (!textColor) return null;\n }\n\n const lastExpression = sections[sections.length - 1];\n lastExpression.scale = scale;\n lastExpression.font = font;\n lastExpression.textColor = textColor;\n } else {\n const content = context.parse(args[i], 1, ValueType);\n if (!content) return null;\n\n const kind = content.type.kind;\n if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage')\n return context.error(`Formatted text type must be 'string', 'value', 'image' or 'null'.`);\n\n nextTokenMayBeObject = true;\n sections.push({content, scale: null, font: null, textColor: null});\n }\n }\n\n return new FormatExpression(sections);\n }\n\n evaluate(ctx: EvaluationContext) {\n const evaluateSection = section => {\n const evaluatedContent = section.content.evaluate(ctx);\n if (typeOf(evaluatedContent) === ResolvedImageType) {\n return new FormattedSection('', evaluatedContent, null, null, null);\n }\n\n return new FormattedSection(\n toString(evaluatedContent),\n null,\n section.scale ? section.scale.evaluate(ctx) : null,\n section.font ? section.font.evaluate(ctx).join(',') : null,\n section.textColor ? section.textColor.evaluate(ctx) : null\n );\n };\n\n return new Formatted(this.sections.map(evaluateSection));\n }\n\n eachChild(fn: (_: Expression) => void) {\n for (const section of this.sections) {\n fn(section.content);\n if (section.scale) {\n fn(section.scale);\n }\n if (section.font) {\n fn(section.font);\n }\n if (section.textColor) {\n fn(section.textColor);\n }\n }\n }\n\n outputDefined() {\n // Technically the combinatoric set of all children\n // Usually, this.text will be undefined anyway\n return false;\n }\n\n serialize() {\n const serialized = [\"format\"];\n for (const section of this.sections) {\n serialized.push(section.content.serialize());\n const options = {};\n if (section.scale) {\n options['font-scale'] = section.scale.serialize();\n }\n if (section.font) {\n options['text-font'] = section.font.serialize();\n }\n if (section.textColor) {\n options['text-color'] = section.textColor.serialize();\n }\n serialized.push(options);\n }\n return serialized;\n }\n}\n","// @flow\n\nimport {ResolvedImageType, StringType} from '../types';\nimport ResolvedImage from '../types/resolved_image';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\n\nexport default class ImageExpression implements Expression {\n type: Type;\n input: Expression;\n\n constructor(input: Expression) {\n this.type = ResolvedImageType;\n this.input = input;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length !== 2) {\n return context.error(`Expected two arguments.`);\n }\n\n const name = context.parse(args[1], 1, StringType);\n if (!name) return context.error(`No image name provided.`);\n\n return new ImageExpression(name);\n }\n\n evaluate(ctx: EvaluationContext) {\n const evaluatedImageName = this.input.evaluate(ctx);\n\n const value = ResolvedImage.fromString(evaluatedImageName);\n if (value && ctx.availableImages) value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1;\n\n return value;\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n }\n\n outputDefined() {\n // The output of image is determined by the list of available images in the evaluation context\n return false;\n }\n\n serialize() {\n return [\"image\", this.input.serialize()];\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport {BooleanType, ColorType, NumberType, StringType, ValueType} from '../types';\nimport {Color, toString as valueToString, validateRGBA} from '../values';\nimport RuntimeError from '../runtime_error';\nimport Formatted from '../types/formatted';\nimport FormatExpression from '../definitions/format';\nimport ImageExpression from '../definitions/image';\nimport ResolvedImage from '../types/resolved_image';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nconst types = {\n 'to-boolean': BooleanType,\n 'to-color': ColorType,\n 'to-number': NumberType,\n 'to-string': StringType\n};\n\n/**\n * Special form for error-coalescing coercion expressions \"to-number\",\n * \"to-color\". Since these coercions can fail at runtime, they accept multiple\n * arguments, only evaluating one at a time until one succeeds.\n *\n * @private\n */\nclass Coercion implements Expression {\n type: Type;\n args: Array;\n\n constructor(type: Type, args: Array) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length < 2)\n return context.error(`Expected at least one argument.`);\n\n const name: string = (args[0]: any);\n assert(types[name], name);\n\n if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2)\n return context.error(`Expected one argument.`);\n\n const type = types[name];\n\n const parsed = [];\n for (let i = 1; i < args.length; i++) {\n const input = context.parse(args[i], i, ValueType);\n if (!input) return null;\n parsed.push(input);\n }\n\n return new Coercion(type, parsed);\n }\n\n evaluate(ctx: EvaluationContext) {\n if (this.type.kind === 'boolean') {\n return Boolean(this.args[0].evaluate(ctx));\n } else if (this.type.kind === 'color') {\n let input;\n let error;\n for (const arg of this.args) {\n input = arg.evaluate(ctx);\n error = null;\n if (input instanceof Color) {\n return input;\n } else if (typeof input === 'string') {\n const c = ctx.parseColor(input);\n if (c) return c;\n } else if (Array.isArray(input)) {\n if (input.length < 3 || input.length > 4) {\n error = `Invalid rbga value ${JSON.stringify(input)}: expected an array containing either three or four numeric values.`;\n } else {\n error = validateRGBA(input[0], input[1], input[2], input[3]);\n }\n if (!error) {\n return new Color((input[0]: any) / 255, (input[1]: any) / 255, (input[2]: any) / 255, (input[3]: any));\n }\n }\n }\n throw new RuntimeError(error || `Could not parse color from value '${typeof input === 'string' ? input : String(JSON.stringify(input))}'`);\n } else if (this.type.kind === 'number') {\n let value = null;\n for (const arg of this.args) {\n value = arg.evaluate(ctx);\n if (value === null) return 0;\n const num = Number(value);\n if (isNaN(num)) continue;\n return num;\n }\n throw new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`);\n } else if (this.type.kind === 'formatted') {\n // There is no explicit 'to-formatted' but this coercion can be implicitly\n // created by properties that expect the 'formatted' type.\n return Formatted.fromString(valueToString(this.args[0].evaluate(ctx)));\n } else if (this.type.kind === 'resolvedImage') {\n return ResolvedImage.fromString(valueToString(this.args[0].evaluate(ctx)));\n } else {\n return valueToString(this.args[0].evaluate(ctx));\n }\n }\n\n eachChild(fn: (_: Expression) => void) {\n this.args.forEach(fn);\n }\n\n outputDefined(): boolean {\n return this.args.every(arg => arg.outputDefined());\n }\n\n serialize() {\n if (this.type.kind === 'formatted') {\n return new FormatExpression([{content: this.args[0], scale: null, font: null, textColor: null}]).serialize();\n }\n\n if (this.type.kind === 'resolvedImage') {\n return new ImageExpression(this.args[0]).serialize();\n }\n\n const serialized = [`to-${this.type.kind}`];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Coercion;\n","// @flow\n\nimport {Color} from './values';\nimport type {FormattedSection} from './types/formatted';\nimport type {GlobalProperties, Feature, FeatureState} from './index';\nimport type {CanonicalTileID} from '../../source/tile_id';\n\nconst geometryTypes = ['Unknown', 'Point', 'LineString', 'Polygon'];\n\nclass EvaluationContext {\n globals: GlobalProperties;\n feature: ?Feature;\n featureState: ?FeatureState;\n formattedSection: ?FormattedSection;\n availableImages: ?Array;\n canonical: ?CanonicalTileID;\n\n _parseColorCache: {[_: string]: ?Color};\n\n constructor() {\n this.globals = (null: any);\n this.feature = null;\n this.featureState = null;\n this.formattedSection = null;\n this._parseColorCache = {};\n this.availableImages = null;\n this.canonical = null;\n }\n\n id() {\n return this.feature && 'id' in this.feature ? this.feature.id : null;\n }\n\n geometryType() {\n return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null;\n }\n\n geometry() {\n return this.feature && 'geometry' in this.feature ? this.feature.geometry : null;\n }\n\n canonicalID() {\n return this.canonical;\n }\n\n properties() {\n return this.feature && this.feature.properties || {};\n }\n\n parseColor(input: string): ?Color {\n let cached = this._parseColorCache[input];\n if (!cached) {\n cached = this._parseColorCache[input] = Color.parse(input);\n }\n return cached;\n }\n}\n\nexport default EvaluationContext;\n","// @flow\n\nimport {toString} from './types';\n\nimport ParsingContext from './parsing_context';\nimport EvaluationContext from './evaluation_context';\nimport assert from 'assert';\n\nimport type {Expression, ExpressionRegistry} from './expression';\nimport type {Type} from './types';\nimport type {Value} from './values';\n\nexport type Varargs = {| type: Type |};\ntype Signature = Array | Varargs;\ntype Evaluate = (EvaluationContext, Array) => Value;\ntype Definition = [Type, Signature, Evaluate] |\n {|type: Type, overloads: Array<[Signature, Evaluate]>|};\n\nclass CompoundExpression implements Expression {\n name: string;\n type: Type;\n _evaluate: Evaluate;\n args: Array;\n\n static definitions: {[_: string]: Definition };\n\n constructor(name: string, type: Type, evaluate: Evaluate, args: Array) {\n this.name = name;\n this.type = type;\n this._evaluate = evaluate;\n this.args = args;\n }\n\n evaluate(ctx: EvaluationContext) {\n return this._evaluate(ctx, this.args);\n }\n\n eachChild(fn: (_: Expression) => void) {\n this.args.forEach(fn);\n }\n\n outputDefined() {\n return false;\n }\n\n serialize(): Array {\n return [this.name].concat(this.args.map(arg => arg.serialize()));\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n const op: string = (args[0]: any);\n const definition = CompoundExpression.definitions[op];\n if (!definition) {\n return context.error(`Unknown expression \"${op}\". If you wanted a literal array, use [\"literal\", [...]].`, 0);\n }\n\n // Now check argument types against each signature\n const type = Array.isArray(definition) ?\n definition[0] : definition.type;\n\n const availableOverloads = Array.isArray(definition) ?\n [[definition[1], definition[2]]] :\n definition.overloads;\n\n const overloads = availableOverloads.filter(([signature]) => (\n !Array.isArray(signature) || // varags\n signature.length === args.length - 1 // correct param count\n ));\n\n let signatureContext: ParsingContext = (null: any);\n\n for (const [params, evaluate] of overloads) {\n // Use a fresh context for each attempted signature so that, if\n // we eventually succeed, we haven't polluted `context.errors`.\n signatureContext = new ParsingContext(context.registry, context.path, null, context.scope);\n\n // First parse all the args, potentially coercing to the\n // types expected by this overload.\n const parsedArgs: Array = [];\n let argParseFailed = false;\n for (let i = 1; i < args.length; i++) {\n const arg = args[i];\n const expectedType = Array.isArray(params) ?\n params[i - 1] :\n params.type;\n\n const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType);\n if (!parsed) {\n argParseFailed = true;\n break;\n }\n parsedArgs.push(parsed);\n }\n if (argParseFailed) {\n // Couldn't coerce args of this overload to expected type, move\n // on to next one.\n continue;\n }\n\n if (Array.isArray(params)) {\n if (params.length !== parsedArgs.length) {\n signatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`);\n continue;\n }\n }\n\n for (let i = 0; i < parsedArgs.length; i++) {\n const expected = Array.isArray(params) ? params[i] : params.type;\n const arg = parsedArgs[i];\n signatureContext.concat(i + 1).checkSubtype(expected, arg.type);\n }\n\n if (signatureContext.errors.length === 0) {\n return new CompoundExpression(op, type, evaluate, parsedArgs);\n }\n }\n\n assert(!signatureContext || signatureContext.errors.length > 0);\n\n if (overloads.length === 1) {\n context.errors.push(...signatureContext.errors);\n } else {\n const expected = overloads.length ? overloads : availableOverloads;\n const signatures = expected\n .map(([params]) => stringifySignature(params))\n .join(' | ');\n\n const actualTypes = [];\n // For error message, re-parse arguments without trying to\n // apply any coercions\n for (let i = 1; i < args.length; i++) {\n const parsed = context.parse(args[i], 1 + actualTypes.length);\n if (!parsed) return null;\n actualTypes.push(toString(parsed.type));\n }\n context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(', ')}) instead.`);\n }\n\n return null;\n }\n\n static register(\n registry: ExpressionRegistry,\n definitions: {[_: string]: Definition }\n ) {\n assert(!CompoundExpression.definitions);\n CompoundExpression.definitions = definitions;\n for (const name in definitions) {\n registry[name] = CompoundExpression;\n }\n }\n}\n\nfunction stringifySignature(signature: Signature): string {\n if (Array.isArray(signature)) {\n return `(${signature.map(toString).join(', ')})`;\n } else {\n return `(${toString(signature.type)}...)`;\n }\n}\n\nexport default CompoundExpression;\n","// @flow\n\nimport {StringType, BooleanType, CollatorType} from '../types';\nimport Collator from '../types/collator';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\n\nexport default class CollatorExpression implements Expression {\n type: Type;\n caseSensitive: Expression;\n diacriticSensitive: Expression;\n locale: Expression | null;\n\n constructor(caseSensitive: Expression, diacriticSensitive: Expression, locale: Expression | null) {\n this.type = CollatorType;\n this.locale = locale;\n this.caseSensitive = caseSensitive;\n this.diacriticSensitive = diacriticSensitive;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length !== 2)\n return context.error(`Expected one argument.`);\n\n const options = (args[1]: any);\n if (typeof options !== \"object\" || Array.isArray(options))\n return context.error(`Collator options argument must be an object.`);\n\n const caseSensitive = context.parse(\n options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType);\n if (!caseSensitive) return null;\n\n const diacriticSensitive = context.parse(\n options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType);\n if (!diacriticSensitive) return null;\n\n let locale = null;\n if (options['locale']) {\n locale = context.parse(options['locale'], 1, StringType);\n if (!locale) return null;\n }\n\n return new CollatorExpression(caseSensitive, diacriticSensitive, locale);\n }\n\n evaluate(ctx: EvaluationContext) {\n return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.caseSensitive);\n fn(this.diacriticSensitive);\n if (this.locale) {\n fn(this.locale);\n }\n }\n\n outputDefined() {\n // Technically the set of possible outputs is the combinatoric set of Collators produced\n // by all possible outputs of locale/caseSensitive/diacriticSensitive\n // But for the primary use of Collators in comparison operators, we ignore the Collator's\n // possible outputs anyway, so we can get away with leaving this false for now.\n return false;\n }\n\n serialize() {\n const options = {};\n options['case-sensitive'] = this.caseSensitive.serialize();\n options['diacritic-sensitive'] = this.diacriticSensitive.serialize();\n if (this.locale) {\n options['locale'] = this.locale.serialize();\n }\n return [\"collator\", options];\n }\n}\n","// @flow\n\nimport {isValue} from '../values';\nimport type {Type} from '../types';\nimport {BooleanType} from '../types';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {GeoJSON, GeoJSONPolygon, GeoJSONMultiPolygon} from '@mapbox/geojson-types';\nimport Point from '@mapbox/point-geometry';\nimport type {CanonicalTileID} from '../../../source/tile_id';\n\ntype GeoJSONPolygons =| GeoJSONPolygon | GeoJSONMultiPolygon;\n\n// minX, minY, maxX, maxY\ntype BBox = [number, number, number, number];\nconst EXTENT = 8192;\n\nfunction updateBBox(bbox: BBox, coord: Point) {\n bbox[0] = Math.min(bbox[0], coord[0]);\n bbox[1] = Math.min(bbox[1], coord[1]);\n bbox[2] = Math.max(bbox[2], coord[0]);\n bbox[3] = Math.max(bbox[3], coord[1]);\n}\n\nfunction mercatorXfromLng(lng: number) {\n return (180 + lng) / 360;\n}\n\nfunction mercatorYfromLat(lat: number) {\n return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360;\n}\n\nfunction boxWithinBox(bbox1: BBox, bbox2: BBox) {\n if (bbox1[0] <= bbox2[0]) return false;\n if (bbox1[2] >= bbox2[2]) return false;\n if (bbox1[1] <= bbox2[1]) return false;\n if (bbox1[3] >= bbox2[3]) return false;\n return true;\n}\n\nfunction getTileCoordinates(p, canonical: CanonicalTileID) {\n const x = mercatorXfromLng(p[0]);\n const y = mercatorYfromLat(p[1]);\n const tilesAtZoom = Math.pow(2, canonical.z);\n return [Math.round(x * tilesAtZoom * EXTENT), Math.round(y * tilesAtZoom * EXTENT)];\n}\n\nfunction onBoundary(p, p1, p2) {\n const x1 = p[0] - p1[0];\n const y1 = p[1] - p1[1];\n const x2 = p[0] - p2[0];\n const y2 = p[1] - p2[1];\n return (x1 * y2 - x2 * y1 === 0) && (x1 * x2 <= 0) && (y1 * y2 <= 0);\n}\n\nfunction rayIntersect(p, p1, p2) {\n return ((p1[1] > p[1]) !== (p2[1] > p[1])) && (p[0] < (p2[0] - p1[0]) * (p[1] - p1[1]) / (p2[1] - p1[1]) + p1[0]);\n}\n\n// ray casting algorithm for detecting if point is in polygon\nfunction pointWithinPolygon(point, rings) {\n let inside = false;\n for (let i = 0, len = rings.length; i < len; i++) {\n const ring = rings[i];\n for (let j = 0, len2 = ring.length; j < len2 - 1; j++) {\n if (onBoundary(point, ring[j], ring[j + 1])) return false;\n if (rayIntersect(point, ring[j], ring[j + 1])) inside = !inside;\n }\n }\n return inside;\n}\n\nfunction pointWithinPolygons(point, polygons) {\n for (let i = 0; i < polygons.length; i++) {\n if (pointWithinPolygon(point, polygons[i])) return true;\n }\n return false;\n}\n\nfunction perp(v1, v2) {\n return (v1[0] * v2[1] - v1[1] * v2[0]);\n}\n\n// check if p1 and p2 are in different sides of line segment q1->q2\nfunction twoSided(p1, p2, q1, q2) {\n // q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3)\n const x1 = p1[0] - q1[0];\n const y1 = p1[1] - q1[1];\n const x2 = p2[0] - q1[0];\n const y2 = p2[1] - q1[1];\n const x3 = q2[0] - q1[0];\n const y3 = q2[1] - q1[1];\n const det1 = (x1 * y3 - x3 * y1);\n const det2 = (x2 * y3 - x3 * y2);\n if ((det1 > 0 && det2 < 0) || (det1 < 0 && det2 > 0)) return true;\n return false;\n}\n// a, b are end points for line segment1, c and d are end points for line segment2\nfunction lineIntersectLine(a, b, c, d) {\n // check if two segments are parallel or not\n // precondition is end point a, b is inside polygon, if line a->b is\n // parallel to polygon edge c->d, then a->b won't intersect with c->d\n const vectorP = [b[0] - a[0], b[1] - a[1]];\n const vectorQ = [d[0] - c[0], d[1] - c[1]];\n if (perp(vectorQ, vectorP) === 0) return false;\n\n // If lines are intersecting with each other, the relative location should be:\n // a and b lie in different sides of segment c->d\n // c and d lie in different sides of segment a->b\n if (twoSided(a, b, c, d) && twoSided(c, d, a, b)) return true;\n return false;\n}\n\nfunction lineIntersectPolygon(p1, p2, polygon) {\n for (const ring of polygon) {\n // loop through every edge of the ring\n for (let j = 0; j < ring.length - 1; ++j) {\n if (lineIntersectLine(p1, p2, ring[j], ring[j + 1])) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction lineStringWithinPolygon(line, polygon) {\n // First, check if geometry points of line segments are all inside polygon\n for (let i = 0; i < line.length; ++i) {\n if (!pointWithinPolygon(line[i], polygon)) {\n return false;\n }\n }\n\n // Second, check if there is line segment intersecting polygon edge\n for (let i = 0; i < line.length - 1; ++i) {\n if (lineIntersectPolygon(line[i], line[i + 1], polygon)) {\n return false;\n }\n }\n return true;\n}\n\nfunction lineStringWithinPolygons(line, polygons) {\n for (let i = 0; i < polygons.length; i++) {\n if (lineStringWithinPolygon(line, polygons[i])) return true;\n }\n return false;\n}\n\nfunction getTilePolygon(coordinates, bbox, canonical) {\n const polygon = [];\n for (let i = 0; i < coordinates.length; i++) {\n const ring = [];\n for (let j = 0; j < coordinates[i].length; j++) {\n const coord = getTileCoordinates(coordinates[i][j], canonical);\n updateBBox(bbox, coord);\n ring.push(coord);\n }\n polygon.push(ring);\n }\n return polygon;\n}\n\nfunction getTilePolygons(coordinates, bbox, canonical) {\n const polygons = [];\n for (let i = 0; i < coordinates.length; i++) {\n const polygon = getTilePolygon(coordinates[i], bbox, canonical);\n polygons.push(polygon);\n }\n return polygons;\n}\n\nfunction updatePoint(p, bbox, polyBBox, worldSize) {\n if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) {\n const halfWorldSize = worldSize * 0.5;\n let shift = (p[0] - polyBBox[0] > halfWorldSize) ? -worldSize : (polyBBox[0] - p[0] > halfWorldSize) ? worldSize : 0;\n if (shift === 0) {\n shift = (p[0] - polyBBox[2] > halfWorldSize) ? -worldSize : (polyBBox[2] - p[0] > halfWorldSize) ? worldSize : 0;\n }\n p[0] += shift;\n }\n updateBBox(bbox, p);\n}\n\nfunction resetBBox(bbox) {\n bbox[0] = bbox[1] = Infinity;\n bbox[2] = bbox[3] = -Infinity;\n}\n\nfunction getTilePoints(geometry, pointBBox, polyBBox, canonical) {\n const worldSize = Math.pow(2, canonical.z) * EXTENT;\n const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];\n const tilePoints = [];\n for (const points of geometry) {\n for (const point of points) {\n const p = [point.x + shifts[0], point.y + shifts[1]];\n updatePoint(p, pointBBox, polyBBox, worldSize);\n tilePoints.push(p);\n }\n }\n return tilePoints;\n}\n\nfunction getTileLines(geometry, lineBBox, polyBBox, canonical) {\n const worldSize = Math.pow(2, canonical.z) * EXTENT;\n const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];\n const tileLines = [];\n for (const line of geometry) {\n const tileLine = [];\n for (const point of line) {\n const p = [point.x + shifts[0], point.y + shifts[1]];\n updateBBox(lineBBox, p);\n tileLine.push(p);\n }\n tileLines.push(tileLine);\n }\n if (lineBBox[2] - lineBBox[0] <= worldSize / 2) {\n resetBBox(lineBBox);\n for (const line of tileLines) {\n for (const p of line) {\n updatePoint(p, lineBBox, polyBBox, worldSize);\n }\n }\n }\n return tileLines;\n}\n\nfunction pointsWithinPolygons(ctx: EvaluationContext, polygonGeometry: GeoJSONPolygons) {\n const pointBBox = [Infinity, Infinity, -Infinity, -Infinity];\n const polyBBox = [Infinity, Infinity, -Infinity, -Infinity];\n\n const canonical = ctx.canonicalID();\n\n if (polygonGeometry.type === 'Polygon') {\n const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);\n const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);\n if (!boxWithinBox(pointBBox, polyBBox)) return false;\n\n for (const point of tilePoints) {\n if (!pointWithinPolygon(point, tilePolygon)) return false;\n }\n }\n if (polygonGeometry.type === 'MultiPolygon') {\n const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);\n const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);\n if (!boxWithinBox(pointBBox, polyBBox)) return false;\n\n for (const point of tilePoints) {\n if (!pointWithinPolygons(point, tilePolygons)) return false;\n }\n }\n\n return true;\n}\n\nfunction linesWithinPolygons(ctx: EvaluationContext, polygonGeometry: GeoJSONPolygons) {\n const lineBBox = [Infinity, Infinity, -Infinity, -Infinity];\n const polyBBox = [Infinity, Infinity, -Infinity, -Infinity];\n\n const canonical = ctx.canonicalID();\n\n if (polygonGeometry.type === 'Polygon') {\n const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);\n const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);\n if (!boxWithinBox(lineBBox, polyBBox)) return false;\n\n for (const line of tileLines) {\n if (!lineStringWithinPolygon(line, tilePolygon)) return false;\n }\n }\n if (polygonGeometry.type === 'MultiPolygon') {\n const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);\n const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);\n if (!boxWithinBox(lineBBox, polyBBox)) return false;\n\n for (const line of tileLines) {\n if (!lineStringWithinPolygons(line, tilePolygons)) return false;\n }\n }\n return true;\n}\n\nclass Within implements Expression {\n type: Type;\n geojson: GeoJSON\n geometries: GeoJSONPolygons;\n\n constructor(geojson: GeoJSON, geometries: GeoJSONPolygons) {\n this.type = BooleanType;\n this.geojson = geojson;\n this.geometries = geometries;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 2)\n return context.error(`'within' expression requires exactly one argument, but found ${args.length - 1} instead.`);\n if (isValue(args[1])) {\n const geojson = (args[1]: Object);\n if (geojson.type === 'FeatureCollection') {\n for (let i = 0; i < geojson.features.length; ++i) {\n const type = geojson.features[i].geometry.type;\n if (type === 'Polygon' || type === 'MultiPolygon') {\n return new Within(geojson, geojson.features[i].geometry);\n }\n }\n } else if (geojson.type === 'Feature') {\n const type = geojson.geometry.type;\n if (type === 'Polygon' || type === 'MultiPolygon') {\n return new Within(geojson, geojson.geometry);\n }\n } else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') {\n return new Within(geojson, geojson);\n }\n }\n return context.error(`'within' expression requires valid geojson object that contains polygon geometry type.`);\n }\n\n evaluate(ctx: EvaluationContext) {\n if (ctx.geometry() != null && ctx.canonicalID() != null) {\n if (ctx.geometryType() === 'Point') {\n return pointsWithinPolygons(ctx, this.geometries);\n } else if (ctx.geometryType() === 'LineString') {\n return linesWithinPolygons(ctx, this.geometries);\n }\n }\n return false;\n }\n\n eachChild() {}\n\n outputDefined(): boolean {\n return true;\n }\n\n serialize(): Array {\n return [\"within\", this.geojson];\n }\n\n}\n\nexport default Within;\n","// @flow\n\nimport CompoundExpression from './compound_expression';\nimport Within from './definitions/within';\nimport type {Expression} from './expression.js';\n\nfunction isFeatureConstant(e: Expression) {\n if (e instanceof CompoundExpression) {\n if (e.name === 'get' && e.args.length === 1) {\n return false;\n } else if (e.name === 'feature-state') {\n return false;\n } else if (e.name === 'has' && e.args.length === 1) {\n return false;\n } else if (\n e.name === 'properties' ||\n e.name === 'geometry-type' ||\n e.name === 'id'\n ) {\n return false;\n } else if (/^filter-/.test(e.name)) {\n return false;\n }\n }\n\n if (e instanceof Within) {\n return false;\n }\n\n let result = true;\n e.eachChild(arg => {\n if (result && !isFeatureConstant(arg)) { result = false; }\n });\n return result;\n}\n\nfunction isStateConstant(e: Expression) {\n if (e instanceof CompoundExpression) {\n if (e.name === 'feature-state') {\n return false;\n }\n }\n let result = true;\n e.eachChild(arg => {\n if (result && !isStateConstant(arg)) { result = false; }\n });\n return result;\n}\n\nfunction isGlobalPropertyConstant(e: Expression, properties: Array) {\n if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) { return false; }\n let result = true;\n e.eachChild((arg) => {\n if (result && !isGlobalPropertyConstant(arg, properties)) { result = false; }\n });\n return result;\n}\n\nexport {isFeatureConstant, isGlobalPropertyConstant, isStateConstant};\n","// @flow\n\nimport type {Type} from '../types';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\n\nclass Var implements Expression {\n type: Type;\n name: string;\n boundExpression: Expression;\n\n constructor(name: string, boundExpression: Expression) {\n this.type = boundExpression.type;\n this.name = name;\n this.boundExpression = boundExpression;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 2 || typeof args[1] !== 'string')\n return context.error(`'var' expression requires exactly one string literal argument.`);\n\n const name = args[1];\n if (!context.scope.has(name)) {\n return context.error(`Unknown variable \"${name}\". Make sure \"${name}\" has been bound in an enclosing \"let\" expression before using it.`, 1);\n }\n\n return new Var(name, context.scope.get(name));\n }\n\n evaluate(ctx: EvaluationContext) {\n return this.boundExpression.evaluate(ctx);\n }\n\n eachChild() {}\n\n outputDefined() {\n return false;\n }\n\n serialize() {\n return [\"var\", this.name];\n }\n}\n\nexport default Var;\n","// @flow\n\nimport Scope from './scope';\nimport {checkSubtype} from './types';\nimport ParsingError from './parsing_error';\nimport Literal from './definitions/literal';\nimport Assertion from './definitions/assertion';\nimport Coercion from './definitions/coercion';\nimport EvaluationContext from './evaluation_context';\nimport CompoundExpression from './compound_expression';\nimport CollatorExpression from './definitions/collator';\nimport Within from './definitions/within';\nimport {isGlobalPropertyConstant, isFeatureConstant} from './is_constant';\nimport Var from './definitions/var';\n\nimport type {Expression, ExpressionRegistry} from './expression';\nimport type {Type} from './types';\n\n/**\n * State associated parsing at a given point in an expression tree.\n * @private\n */\nclass ParsingContext {\n registry: ExpressionRegistry;\n path: Array;\n key: string;\n scope: Scope;\n errors: Array;\n\n // The expected type of this expression. Provided only to allow Expression\n // implementations to infer argument types: Expression#parse() need not\n // check that the output type of the parsed expression matches\n // `expectedType`.\n expectedType: ?Type;\n\n constructor(\n registry: ExpressionRegistry,\n path: Array = [],\n expectedType: ?Type,\n scope: Scope = new Scope(),\n errors: Array = []\n ) {\n this.registry = registry;\n this.path = path;\n this.key = path.map(part => `[${part}]`).join('');\n this.scope = scope;\n this.errors = errors;\n this.expectedType = expectedType;\n }\n\n /**\n * @param expr the JSON expression to parse\n * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed\n * @param options\n * @param options.omitTypeAnnotations set true to omit inferred type annotations. Caller beware: with this option set, the parsed expression's type will NOT satisfy `expectedType` if it would normally be wrapped in an inferred annotation.\n * @private\n */\n parse(\n expr: mixed,\n index?: number,\n expectedType?: ?Type,\n bindings?: Array<[string, Expression]>,\n options: {typeAnnotation?: 'assert' | 'coerce' | 'omit'} = {}\n ): ?Expression {\n if (index) {\n return this.concat(index, expectedType, bindings)._parse(expr, options);\n }\n return this._parse(expr, options);\n }\n\n _parse(expr: mixed, options: {typeAnnotation?: 'assert' | 'coerce' | 'omit'}): ?Expression {\n if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') {\n expr = ['literal', expr];\n }\n\n function annotate(parsed, type, typeAnnotation: 'assert' | 'coerce' | 'omit') {\n if (typeAnnotation === 'assert') {\n return new Assertion(type, [parsed]);\n } else if (typeAnnotation === 'coerce') {\n return new Coercion(type, [parsed]);\n } else {\n return parsed;\n }\n }\n\n if (Array.isArray(expr)) {\n if (expr.length === 0) {\n return this.error(`Expected an array with at least one element. If you wanted a literal array, use [\"literal\", []].`);\n }\n\n const op = expr[0];\n if (typeof op !== 'string') {\n this.error(`Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use [\"literal\", [...]].`, 0);\n return null;\n }\n\n const Expr = this.registry[op];\n if (Expr) {\n let parsed = Expr.parse(expr, this);\n if (!parsed) return null;\n\n if (this.expectedType) {\n const expected = this.expectedType;\n const actual = parsed.type;\n\n // When we expect a number, string, boolean, or array but have a value, wrap it in an assertion.\n // When we expect a color or formatted string, but have a string or value, wrap it in a coercion.\n // Otherwise, we do static type-checking.\n //\n // These behaviors are overridable for:\n // * The \"coalesce\" operator, which needs to omit type annotations.\n // * String-valued properties (e.g. `text-field`), where coercion is more convenient than assertion.\n //\n if ((expected.kind === 'string' || expected.kind === 'number' || expected.kind === 'boolean' || expected.kind === 'object' || expected.kind === 'array') && actual.kind === 'value') {\n parsed = annotate(parsed, expected, options.typeAnnotation || 'assert');\n } else if ((expected.kind === 'color' || expected.kind === 'formatted' || expected.kind === 'resolvedImage') && (actual.kind === 'value' || actual.kind === 'string')) {\n parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce');\n } else if (this.checkSubtype(expected, actual)) {\n return null;\n }\n }\n\n // If an expression's arguments are all literals, we can evaluate\n // it immediately and replace it with a literal value in the\n // parsed/compiled result. Expressions that expect an image should\n // not be resolved here so we can later get the available images.\n if (!(parsed instanceof Literal) && (parsed.type.kind !== 'resolvedImage') && isConstant(parsed)) {\n const ec = new EvaluationContext();\n try {\n parsed = new Literal(parsed.type, parsed.evaluate(ec));\n } catch (e) {\n this.error(e.message);\n return null;\n }\n }\n\n return parsed;\n }\n\n return this.error(`Unknown expression \"${op}\". If you wanted a literal array, use [\"literal\", [...]].`, 0);\n } else if (typeof expr === 'undefined') {\n return this.error(`'undefined' value invalid. Use null instead.`);\n } else if (typeof expr === 'object') {\n return this.error(`Bare objects invalid. Use [\"literal\", {...}] instead.`);\n } else {\n return this.error(`Expected an array, but found ${typeof expr} instead.`);\n }\n }\n\n /**\n * Returns a copy of this context suitable for parsing the subexpression at\n * index `index`, optionally appending to 'let' binding map.\n *\n * Note that `errors` property, intended for collecting errors while\n * parsing, is copied by reference rather than cloned.\n * @private\n */\n concat(index: number, expectedType?: ?Type, bindings?: Array<[string, Expression]>) {\n const path = typeof index === 'number' ? this.path.concat(index) : this.path;\n const scope = bindings ? this.scope.concat(bindings) : this.scope;\n return new ParsingContext(\n this.registry,\n path,\n expectedType || null,\n scope,\n this.errors\n );\n }\n\n /**\n * Push a parsing (or type checking) error into the `this.errors`\n * @param error The message\n * @param keys Optionally specify the source of the error at a child\n * of the current expression at `this.key`.\n * @private\n */\n error(error: string, ...keys: Array) {\n const key = `${this.key}${keys.map(k => `[${k}]`).join('')}`;\n this.errors.push(new ParsingError(key, error));\n }\n\n /**\n * Returns null if `t` is a subtype of `expected`; otherwise returns an\n * error message and also pushes it to `this.errors`.\n */\n checkSubtype(expected: Type, t: Type): ?string {\n const error = checkSubtype(expected, t);\n if (error) this.error(error);\n return error;\n }\n}\n\nexport default ParsingContext;\n\nfunction isConstant(expression: Expression) {\n if (expression instanceof Var) {\n return isConstant(expression.boundExpression);\n } else if (expression instanceof CompoundExpression && expression.name === 'error') {\n return false;\n } else if (expression instanceof CollatorExpression) {\n // Although the results of a Collator expression with fixed arguments\n // generally shouldn't change between executions, we can't serialize them\n // as constant expressions because results change based on environment.\n return false;\n } else if (expression instanceof Within) {\n return false;\n }\n\n const isTypeAnnotation = expression instanceof Coercion ||\n expression instanceof Assertion;\n\n let childrenConstant = true;\n expression.eachChild(child => {\n // We can _almost_ assume that if `expressions` children are constant,\n // they would already have been evaluated to Literal values when they\n // were parsed. Type annotations are the exception, because they might\n // have been inferred and added after a child was parsed.\n\n // So we recurse into isConstant() for the children of type annotations,\n // but otherwise simply check whether they are Literals.\n if (isTypeAnnotation) {\n childrenConstant = childrenConstant && isConstant(child);\n } else {\n childrenConstant = childrenConstant && child instanceof Literal;\n }\n });\n if (!childrenConstant) {\n return false;\n }\n\n return isFeatureConstant(expression) &&\n isGlobalPropertyConstant(expression, ['zoom', 'heatmap-density', 'line-progress', 'accumulated', 'is-supported-script']);\n}\n","// @flow\n\nimport RuntimeError from './runtime_error';\n\nimport type {Expression} from './expression';\n\nexport type Stops = Array<[number, Expression]>;\n\n/**\n * Returns the index of the last stop <= input, or 0 if it doesn't exist.\n * @private\n */\nexport function findStopLessThanOrEqualTo(stops: Array, input: number) {\n const lastIndex = stops.length - 1;\n let lowerIndex = 0;\n let upperIndex = lastIndex;\n let currentIndex = 0;\n let currentValue, nextValue;\n\n while (lowerIndex <= upperIndex) {\n currentIndex = Math.floor((lowerIndex + upperIndex) / 2);\n currentValue = stops[currentIndex];\n nextValue = stops[currentIndex + 1];\n\n if (currentValue <= input) {\n if (currentIndex === lastIndex || input < nextValue) { // Search complete\n return currentIndex;\n }\n\n lowerIndex = currentIndex + 1;\n } else if (currentValue > input) {\n upperIndex = currentIndex - 1;\n } else {\n throw new RuntimeError('Input is not a number.');\n }\n }\n\n return 0;\n}\n","// @flow\n\nimport {NumberType} from '../types';\n\nimport {findStopLessThanOrEqualTo} from '../stops';\n\nimport type {Stops} from '../stops';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nclass Step implements Expression {\n type: Type;\n\n input: Expression;\n labels: Array;\n outputs: Array;\n\n constructor(type: Type, input: Expression, stops: Stops) {\n this.type = type;\n this.input = input;\n\n this.labels = [];\n this.outputs = [];\n for (const [label, expression] of stops) {\n this.labels.push(label);\n this.outputs.push(expression);\n }\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length - 1 < 4) {\n return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n }\n\n if ((args.length - 1) % 2 !== 0) {\n return context.error(`Expected an even number of arguments.`);\n }\n\n const input = context.parse(args[1], 1, NumberType);\n if (!input) return null;\n\n const stops: Stops = [];\n\n let outputType: Type = (null: any);\n if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n\n for (let i = 1; i < args.length; i += 2) {\n const label = i === 1 ? -Infinity : args[i];\n const value = args[i + 1];\n\n const labelKey = i;\n const valueKey = i + 1;\n\n if (typeof label !== 'number') {\n return context.error('Input/output pairs for \"step\" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey);\n }\n\n if (stops.length && stops[stops.length - 1][0] >= label) {\n return context.error('Input/output pairs for \"step\" expressions must be arranged with input values in strictly ascending order.', labelKey);\n }\n\n const parsed = context.parse(value, valueKey, outputType);\n if (!parsed) return null;\n outputType = outputType || parsed.type;\n stops.push([label, parsed]);\n }\n\n return new Step(outputType, input, stops);\n }\n\n evaluate(ctx: EvaluationContext) {\n const labels = this.labels;\n const outputs = this.outputs;\n\n if (labels.length === 1) {\n return outputs[0].evaluate(ctx);\n }\n\n const value = ((this.input.evaluate(ctx): any): number);\n if (value <= labels[0]) {\n return outputs[0].evaluate(ctx);\n }\n\n const stopCount = labels.length;\n if (value >= labels[stopCount - 1]) {\n return outputs[stopCount - 1].evaluate(ctx);\n }\n\n const index = findStopLessThanOrEqualTo(labels, value);\n return outputs[index].evaluate(ctx);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n for (const expression of this.outputs) {\n fn(expression);\n }\n }\n\n outputDefined(): boolean {\n return this.outputs.every(out => out.outputDefined());\n }\n\n serialize() {\n const serialized = [\"step\", this.input.serialize()];\n for (let i = 0; i < this.labels.length; i++) {\n if (i > 0) {\n serialized.push(this.labels[i]);\n }\n serialized.push(this.outputs[i].serialize());\n }\n return serialized;\n }\n}\n\nexport default Step;\n","/*\n * Copyright (C) 2008 Apple Inc. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Ported from Webkit\n * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h\n */\n\nmodule.exports = UnitBezier;\n\nfunction UnitBezier(p1x, p1y, p2x, p2y) {\n // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).\n this.cx = 3.0 * p1x;\n this.bx = 3.0 * (p2x - p1x) - this.cx;\n this.ax = 1.0 - this.cx - this.bx;\n\n this.cy = 3.0 * p1y;\n this.by = 3.0 * (p2y - p1y) - this.cy;\n this.ay = 1.0 - this.cy - this.by;\n\n this.p1x = p1x;\n this.p1y = p2y;\n this.p2x = p2x;\n this.p2y = p2y;\n}\n\nUnitBezier.prototype.sampleCurveX = function(t) {\n // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.\n return ((this.ax * t + this.bx) * t + this.cx) * t;\n};\n\nUnitBezier.prototype.sampleCurveY = function(t) {\n return ((this.ay * t + this.by) * t + this.cy) * t;\n};\n\nUnitBezier.prototype.sampleCurveDerivativeX = function(t) {\n return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;\n};\n\nUnitBezier.prototype.solveCurveX = function(x, epsilon) {\n if (typeof epsilon === 'undefined') epsilon = 1e-6;\n\n var t0, t1, t2, x2, i;\n\n // First try a few iterations of Newton's method -- normally very fast.\n for (t2 = x, i = 0; i < 8; i++) {\n\n x2 = this.sampleCurveX(t2) - x;\n if (Math.abs(x2) < epsilon) return t2;\n\n var d2 = this.sampleCurveDerivativeX(t2);\n if (Math.abs(d2) < 1e-6) break;\n\n t2 = t2 - x2 / d2;\n }\n\n // Fall back to the bisection method for reliability.\n t0 = 0.0;\n t1 = 1.0;\n t2 = x;\n\n if (t2 < t0) return t0;\n if (t2 > t1) return t1;\n\n while (t0 < t1) {\n\n x2 = this.sampleCurveX(t2);\n if (Math.abs(x2 - x) < epsilon) return t2;\n\n if (x > x2) {\n t0 = t2;\n } else {\n t1 = t2;\n }\n\n t2 = (t1 - t0) * 0.5 + t0;\n }\n\n // Failure.\n return t2;\n};\n\nUnitBezier.prototype.solve = function(x, epsilon) {\n return this.sampleCurveY(this.solveCurveX(x, epsilon));\n};\n","// @flow\n\nimport Color from './color';\n\nexport function number(a: number, b: number, t: number) {\n return (a * (1 - t)) + (b * t);\n}\n\nexport function color(from: Color, to: Color, t: number) {\n return new Color(\n number(from.r, to.r, t),\n number(from.g, to.g, t),\n number(from.b, to.b, t),\n number(from.a, to.a, t)\n );\n}\n\nexport function array(from: Array, to: Array, t: number): Array {\n return from.map((d, i) => {\n return number(d, to[i], t);\n });\n}\n","// @flow\n\nimport Color from './color';\n\nimport {number as interpolateNumber} from './interpolate';\n\ntype LABColor = {\n l: number,\n a: number,\n b: number,\n alpha: number\n};\n\ntype HCLColor = {\n h: number,\n c: number,\n l: number,\n alpha: number\n};\n\n// Constants\nconst Xn = 0.950470, // D65 standard referent\n Yn = 1,\n Zn = 1.088830,\n t0 = 4 / 29,\n t1 = 6 / 29,\n t2 = 3 * t1 * t1,\n t3 = t1 * t1 * t1,\n deg2rad = Math.PI / 180,\n rad2deg = 180 / Math.PI;\n\n// Utilities\nfunction xyz2lab(t: number) {\n return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;\n}\n\nfunction lab2xyz(t: number) {\n return t > t1 ? t * t * t : t2 * (t - t0);\n}\n\nfunction xyz2rgb(x: number) {\n return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);\n}\n\nfunction rgb2xyz(x: number) {\n x /= 255;\n return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);\n}\n\n// LAB\nfunction rgbToLab(rgbColor: Color): LABColor {\n const b = rgb2xyz(rgbColor.r),\n a = rgb2xyz(rgbColor.g),\n l = rgb2xyz(rgbColor.b),\n x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn),\n y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.0721750 * l) / Yn),\n z = xyz2lab((0.0193339 * b + 0.1191920 * a + 0.9503041 * l) / Zn);\n\n return {\n l: 116 * y - 16,\n a: 500 * (x - y),\n b: 200 * (y - z),\n alpha: rgbColor.a\n };\n}\n\nfunction labToRgb(labColor: LABColor): Color {\n let y = (labColor.l + 16) / 116,\n x = isNaN(labColor.a) ? y : y + labColor.a / 500,\n z = isNaN(labColor.b) ? y : y - labColor.b / 200;\n y = Yn * lab2xyz(y);\n x = Xn * lab2xyz(x);\n z = Zn * lab2xyz(z);\n return new Color(\n xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z), // D65 -> sRGB\n xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z),\n xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z),\n labColor.alpha\n );\n}\n\nfunction interpolateLab(from: LABColor, to: LABColor, t: number) {\n return {\n l: interpolateNumber(from.l, to.l, t),\n a: interpolateNumber(from.a, to.a, t),\n b: interpolateNumber(from.b, to.b, t),\n alpha: interpolateNumber(from.alpha, to.alpha, t)\n };\n}\n\n// HCL\nfunction rgbToHcl(rgbColor: Color): HCLColor {\n const {l, a, b} = rgbToLab(rgbColor);\n const h = Math.atan2(b, a) * rad2deg;\n return {\n h: h < 0 ? h + 360 : h,\n c: Math.sqrt(a * a + b * b),\n l,\n alpha: rgbColor.a\n };\n}\n\nfunction hclToRgb(hclColor: HCLColor): Color {\n const h = hclColor.h * deg2rad,\n c = hclColor.c,\n l = hclColor.l;\n return labToRgb({\n l,\n a: Math.cos(h) * c,\n b: Math.sin(h) * c,\n alpha: hclColor.alpha\n });\n}\n\nfunction interpolateHue(a: number, b: number, t: number) {\n const d = b - a;\n return a + t * (d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d);\n}\n\nfunction interpolateHcl(from: HCLColor, to: HCLColor, t: number) {\n return {\n h: interpolateHue(from.h, to.h, t),\n c: interpolateNumber(from.c, to.c, t),\n l: interpolateNumber(from.l, to.l, t),\n alpha: interpolateNumber(from.alpha, to.alpha, t)\n };\n}\n\nexport const lab = {\n forward: rgbToLab,\n reverse: labToRgb,\n interpolate: interpolateLab\n};\n\nexport const hcl = {\n forward: rgbToHcl,\n reverse: hclToRgb,\n interpolate: interpolateHcl\n};\n","// @flow\n\nimport UnitBezier from '@mapbox/unitbezier';\n\nimport * as interpolate from '../../util/interpolate';\nimport {toString, NumberType, ColorType} from '../types';\nimport {findStopLessThanOrEqualTo} from '../stops';\nimport {hcl, lab} from '../../util/color_spaces';\n\nimport type {Stops} from '../stops';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nexport type InterpolationType =\n { name: 'linear' } |\n { name: 'exponential', base: number } |\n { name: 'cubic-bezier', controlPoints: [number, number, number, number] };\n\nclass Interpolate implements Expression {\n type: Type;\n\n operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab';\n interpolation: InterpolationType;\n input: Expression;\n labels: Array;\n outputs: Array;\n\n constructor(type: Type, operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab', interpolation: InterpolationType, input: Expression, stops: Stops) {\n this.type = type;\n this.operator = operator;\n this.interpolation = interpolation;\n this.input = input;\n\n this.labels = [];\n this.outputs = [];\n for (const [label, expression] of stops) {\n this.labels.push(label);\n this.outputs.push(expression);\n }\n }\n\n static interpolationFactor(interpolation: InterpolationType, input: number, lower: number, upper: number) {\n let t = 0;\n if (interpolation.name === 'exponential') {\n t = exponentialInterpolation(input, interpolation.base, lower, upper);\n } else if (interpolation.name === 'linear') {\n t = exponentialInterpolation(input, 1, lower, upper);\n } else if (interpolation.name === 'cubic-bezier') {\n const c = interpolation.controlPoints;\n const ub = new UnitBezier(c[0], c[1], c[2], c[3]);\n t = ub.solve(exponentialInterpolation(input, 1, lower, upper));\n }\n return t;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n let [operator, interpolation, input, ...rest] = args;\n\n if (!Array.isArray(interpolation) || interpolation.length === 0) {\n return context.error(`Expected an interpolation type expression.`, 1);\n }\n\n if (interpolation[0] === 'linear') {\n interpolation = {name: 'linear'};\n } else if (interpolation[0] === 'exponential') {\n const base = interpolation[1];\n if (typeof base !== 'number')\n return context.error(`Exponential interpolation requires a numeric base.`, 1, 1);\n interpolation = {\n name: 'exponential',\n base\n };\n } else if (interpolation[0] === 'cubic-bezier') {\n const controlPoints = interpolation.slice(1);\n if (\n controlPoints.length !== 4 ||\n controlPoints.some(t => typeof t !== 'number' || t < 0 || t > 1)\n ) {\n return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1);\n }\n\n interpolation = {\n name: 'cubic-bezier',\n controlPoints: (controlPoints: any)\n };\n } else {\n return context.error(`Unknown interpolation type ${String(interpolation[0])}`, 1, 0);\n }\n\n if (args.length - 1 < 4) {\n return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n }\n\n if ((args.length - 1) % 2 !== 0) {\n return context.error(`Expected an even number of arguments.`);\n }\n\n input = context.parse(input, 2, NumberType);\n if (!input) return null;\n\n const stops: Stops = [];\n\n let outputType: Type = (null: any);\n if (operator === 'interpolate-hcl' || operator === 'interpolate-lab') {\n outputType = ColorType;\n } else if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n\n for (let i = 0; i < rest.length; i += 2) {\n const label = rest[i];\n const value = rest[i + 1];\n\n const labelKey = i + 3;\n const valueKey = i + 4;\n\n if (typeof label !== 'number') {\n return context.error('Input/output pairs for \"interpolate\" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey);\n }\n\n if (stops.length && stops[stops.length - 1][0] >= label) {\n return context.error('Input/output pairs for \"interpolate\" expressions must be arranged with input values in strictly ascending order.', labelKey);\n }\n\n const parsed = context.parse(value, valueKey, outputType);\n if (!parsed) return null;\n outputType = outputType || parsed.type;\n stops.push([label, parsed]);\n }\n\n if (outputType.kind !== 'number' &&\n outputType.kind !== 'color' &&\n !(\n outputType.kind === 'array' &&\n outputType.itemType.kind === 'number' &&\n typeof outputType.N === 'number'\n )\n ) {\n return context.error(`Type ${toString(outputType)} is not interpolatable.`);\n }\n\n return new Interpolate(outputType, (operator: any), interpolation, input, stops);\n }\n\n evaluate(ctx: EvaluationContext) {\n const labels = this.labels;\n const outputs = this.outputs;\n\n if (labels.length === 1) {\n return outputs[0].evaluate(ctx);\n }\n\n const value = ((this.input.evaluate(ctx): any): number);\n if (value <= labels[0]) {\n return outputs[0].evaluate(ctx);\n }\n\n const stopCount = labels.length;\n if (value >= labels[stopCount - 1]) {\n return outputs[stopCount - 1].evaluate(ctx);\n }\n\n const index = findStopLessThanOrEqualTo(labels, value);\n const lower = labels[index];\n const upper = labels[index + 1];\n const t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper);\n\n const outputLower = outputs[index].evaluate(ctx);\n const outputUpper = outputs[index + 1].evaluate(ctx);\n\n if (this.operator === 'interpolate') {\n return (interpolate[this.type.kind.toLowerCase()]: any)(outputLower, outputUpper, t); // eslint-disable-line import/namespace\n } else if (this.operator === 'interpolate-hcl') {\n return hcl.reverse(hcl.interpolate(hcl.forward(outputLower), hcl.forward(outputUpper), t));\n } else {\n return lab.reverse(lab.interpolate(lab.forward(outputLower), lab.forward(outputUpper), t));\n }\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n for (const expression of this.outputs) {\n fn(expression);\n }\n }\n\n outputDefined(): boolean {\n return this.outputs.every(out => out.outputDefined());\n }\n\n serialize(): Array {\n let interpolation;\n if (this.interpolation.name === 'linear') {\n interpolation = [\"linear\"];\n } else if (this.interpolation.name === 'exponential') {\n if (this.interpolation.base === 1) {\n interpolation = [\"linear\"];\n } else {\n interpolation = [\"exponential\", this.interpolation.base];\n }\n } else {\n interpolation = [\"cubic-bezier\" ].concat(this.interpolation.controlPoints);\n }\n\n const serialized = [this.operator, interpolation, this.input.serialize()];\n\n for (let i = 0; i < this.labels.length; i++) {\n serialized.push(\n this.labels[i],\n this.outputs[i].serialize()\n );\n }\n return serialized;\n }\n}\n\n/**\n * Returns a ratio that can be used to interpolate between exponential function\n * stops.\n * How it works: Two consecutive stop values define a (scaled and shifted) exponential function `f(x) = a * base^x + b`, where `base` is the user-specified base,\n * and `a` and `b` are constants affording sufficient degrees of freedom to fit\n * the function to the given stops.\n *\n * Here's a bit of algebra that lets us compute `f(x)` directly from the stop\n * values without explicitly solving for `a` and `b`:\n *\n * First stop value: `f(x0) = y0 = a * base^x0 + b`\n * Second stop value: `f(x1) = y1 = a * base^x1 + b`\n * => `y1 - y0 = a(base^x1 - base^x0)`\n * => `a = (y1 - y0)/(base^x1 - base^x0)`\n *\n * Desired value: `f(x) = y = a * base^x + b`\n * => `f(x) = y0 + a * (base^x - base^x0)`\n *\n * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a\n * little algebra:\n * ```\n * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0)\n * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0)\n * ```\n *\n * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have\n * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as\n * an interpolation factor between the two stops' output values.\n *\n * (Note: a slightly different form for `ratio`,\n * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer\n * expensive `Math.pow()` operations.)\n *\n * @private\n*/\nfunction exponentialInterpolation(input, base, lowerValue, upperValue) {\n const difference = upperValue - lowerValue;\n const progress = input - lowerValue;\n\n if (difference === 0) {\n return 0;\n } else if (base === 1) {\n return progress / difference;\n } else {\n return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);\n }\n}\n\nexport default Interpolate;\n","// @flow\n\nimport assert from 'assert';\n\nimport {checkSubtype, ValueType} from '../types';\nimport ResolvedImage from '../types/resolved_image';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nclass Coalesce implements Expression {\n type: Type;\n args: Array;\n\n constructor(type: Type, args: Array) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length < 2) {\n return context.error(\"Expectected at least one argument.\");\n }\n let outputType: Type = (null: any);\n const expectedType = context.expectedType;\n if (expectedType && expectedType.kind !== 'value') {\n outputType = expectedType;\n }\n const parsedArgs = [];\n\n for (const arg of args.slice(1)) {\n const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, {typeAnnotation: 'omit'});\n if (!parsed) return null;\n outputType = outputType || parsed.type;\n parsedArgs.push(parsed);\n }\n assert(outputType);\n\n // Above, we parse arguments without inferred type annotation so that\n // they don't produce a runtime error for `null` input, which would\n // preempt the desired null-coalescing behavior.\n // Thus, if any of our arguments would have needed an annotation, we\n // need to wrap the enclosing coalesce expression with it instead.\n const needsAnnotation = expectedType &&\n parsedArgs.some(arg => checkSubtype(expectedType, arg.type));\n\n return needsAnnotation ?\n new Coalesce(ValueType, parsedArgs) :\n new Coalesce((outputType: any), parsedArgs);\n }\n\n evaluate(ctx: EvaluationContext) {\n let result = null;\n let argCount = 0;\n let requestedImageName;\n for (const arg of this.args) {\n argCount++;\n result = arg.evaluate(ctx);\n // we need to keep track of the first requested image in a coalesce statement\n // if coalesce can't find a valid image, we return the first image name so styleimagemissing can fire\n if (result && result instanceof ResolvedImage && !result.available) {\n if (!requestedImageName) {\n requestedImageName = result.name;\n }\n result = null;\n if (argCount === this.args.length) {\n result = requestedImageName;\n }\n }\n\n if (result !== null) break;\n }\n return result;\n }\n\n eachChild(fn: (_: Expression) => void) {\n this.args.forEach(fn);\n }\n\n outputDefined(): boolean {\n return this.args.every(arg => arg.outputDefined());\n }\n\n serialize() {\n const serialized = [\"coalesce\"];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Coalesce;\n","// @flow\n\nimport type {Type} from '../types';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\n\nclass Let implements Expression {\n type: Type;\n bindings: Array<[string, Expression]>;\n result: Expression;\n\n constructor(bindings: Array<[string, Expression]>, result: Expression) {\n this.type = result.type;\n this.bindings = [].concat(bindings);\n this.result = result;\n }\n\n evaluate(ctx: EvaluationContext) {\n return this.result.evaluate(ctx);\n }\n\n eachChild(fn: (_: Expression) => void) {\n for (const binding of this.bindings) {\n fn(binding[1]);\n }\n fn(this.result);\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length < 4)\n return context.error(`Expected at least 3 arguments, but found ${args.length - 1} instead.`);\n\n const bindings: Array<[string, Expression]> = [];\n for (let i = 1; i < args.length - 1; i += 2) {\n const name = args[i];\n\n if (typeof name !== 'string') {\n return context.error(`Expected string, but found ${typeof name} instead.`, i);\n }\n\n if (/[^a-zA-Z0-9_]/.test(name)) {\n return context.error(`Variable names must contain only alphanumeric characters or '_'.`, i);\n }\n\n const value = context.parse(args[i + 1], i + 1);\n if (!value) return null;\n\n bindings.push([name, value]);\n }\n\n const result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings);\n if (!result) return null;\n\n return new Let(bindings, result);\n }\n\n outputDefined() {\n return this.result.outputDefined();\n }\n\n serialize() {\n const serialized = [\"let\"];\n for (const [name, expr] of this.bindings) {\n serialized.push(name, expr.serialize());\n }\n serialized.push(this.result.serialize());\n return serialized;\n }\n}\n\nexport default Let;\n","// @flow\n\nimport {array, ValueType, NumberType} from '../types';\n\nimport RuntimeError from '../runtime_error';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type, ArrayType} from '../types';\nimport type {Value} from '../values';\n\nclass At implements Expression {\n type: Type;\n index: Expression;\n input: Expression;\n\n constructor(type: Type, index: Expression, input: Expression) {\n this.type = type;\n this.index = index;\n this.input = input;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 3)\n return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`);\n\n const index = context.parse(args[1], 1, NumberType);\n const input = context.parse(args[2], 2, array(context.expectedType || ValueType));\n\n if (!index || !input) return null;\n\n const t: ArrayType = (input.type: any);\n return new At(t.itemType, index, input);\n }\n\n evaluate(ctx: EvaluationContext) {\n const index = ((this.index.evaluate(ctx): any): number);\n const array = ((this.input.evaluate(ctx): any): Array);\n\n if (index < 0) {\n throw new RuntimeError(`Array index out of bounds: ${index} < 0.`);\n }\n\n if (index >= array.length) {\n throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`);\n }\n\n if (index !== Math.floor(index)) {\n throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`);\n }\n\n return array[index];\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.index);\n fn(this.input);\n }\n\n outputDefined() {\n return false;\n }\n\n serialize() {\n return [\"at\", this.index.serialize(), this.input.serialize()];\n }\n}\n\nexport default At;\n","// @flow\n\nimport {BooleanType, StringType, ValueType, NullType, toString, NumberType, isValidType, isValidNativeType} from '../types';\nimport RuntimeError from '../runtime_error';\nimport {typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nclass In implements Expression {\n type: Type;\n needle: Expression;\n haystack: Expression;\n\n constructor(needle: Expression, haystack: Expression) {\n this.type = BooleanType;\n this.needle = needle;\n this.haystack = haystack;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 3) {\n return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`);\n }\n\n const needle = context.parse(args[1], 1, ValueType);\n\n const haystack = context.parse(args[2], 2, ValueType);\n\n if (!needle || !haystack) return null;\n\n if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) {\n return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString(needle.type)} instead`);\n }\n\n return new In(needle, haystack);\n }\n\n evaluate(ctx: EvaluationContext) {\n const needle = (this.needle.evaluate(ctx): any);\n const haystack = (this.haystack.evaluate(ctx): any);\n\n if (!haystack) return false;\n\n if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) {\n throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString(typeOf(needle))} instead.`);\n }\n\n if (!isValidNativeType(haystack, ['string', 'array'])) {\n throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString(typeOf(haystack))} instead.`);\n }\n\n return haystack.indexOf(needle) >= 0;\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.needle);\n fn(this.haystack);\n }\n\n outputDefined() {\n return true;\n }\n\n serialize() {\n return [\"in\", this.needle.serialize(), this.haystack.serialize()];\n }\n}\n\nexport default In;\n","// @flow\n\nimport {BooleanType, StringType, ValueType, NullType, toString, NumberType, isValidType, isValidNativeType} from '../types';\nimport RuntimeError from '../runtime_error';\nimport {typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nclass IndexOf implements Expression {\n type: Type;\n needle: Expression;\n haystack: Expression;\n fromIndex: ?Expression;\n\n constructor(needle: Expression, haystack: Expression, fromIndex?: Expression) {\n this.type = NumberType;\n this.needle = needle;\n this.haystack = haystack;\n this.fromIndex = fromIndex;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length <= 2 || args.length >= 5) {\n return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`);\n }\n\n const needle = context.parse(args[1], 1, ValueType);\n\n const haystack = context.parse(args[2], 2, ValueType);\n\n if (!needle || !haystack) return null;\n if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) {\n return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString(needle.type)} instead`);\n }\n\n if (args.length === 4) {\n const fromIndex = context.parse(args[3], 3, NumberType);\n if (!fromIndex) return null;\n return new IndexOf(needle, haystack, fromIndex);\n } else {\n return new IndexOf(needle, haystack);\n }\n }\n\n evaluate(ctx: EvaluationContext) {\n const needle = (this.needle.evaluate(ctx): any);\n const haystack = (this.haystack.evaluate(ctx): any);\n\n if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) {\n throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString(typeOf(needle))} instead.`);\n }\n\n if (!isValidNativeType(haystack, ['string', 'array'])) {\n throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString(typeOf(haystack))} instead.`);\n }\n\n if (this.fromIndex) {\n const fromIndex = (this.fromIndex.evaluate(ctx): number);\n return haystack.indexOf(needle, fromIndex);\n }\n\n return haystack.indexOf(needle);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.needle);\n fn(this.haystack);\n if (this.fromIndex) {\n fn(this.fromIndex);\n }\n }\n\n outputDefined() {\n return false;\n }\n\n serialize() {\n if (this.fromIndex != null && this.fromIndex !== undefined) {\n const fromIndex = this.fromIndex.serialize();\n return [\"index-of\", this.needle.serialize(), this.haystack.serialize(), fromIndex];\n }\n return [\"index-of\", this.needle.serialize(), this.haystack.serialize()];\n }\n}\n\nexport default IndexOf;\n","// @flow\n\nimport assert from 'assert';\n\nimport {typeOf} from '../values';\nimport {ValueType, type Type} from '../types';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\n\n// Map input label values to output expression index\ntype Cases = {[number | string]: number};\n\nclass Match implements Expression {\n type: Type;\n inputType: Type;\n\n input: Expression;\n cases: Cases;\n outputs: Array;\n otherwise: Expression;\n\n constructor(inputType: Type, outputType: Type, input: Expression, cases: Cases, outputs: Array, otherwise: Expression) {\n this.inputType = inputType;\n this.type = outputType;\n this.input = input;\n this.cases = cases;\n this.outputs = outputs;\n this.otherwise = otherwise;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length < 5)\n return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n if (args.length % 2 !== 1)\n return context.error(`Expected an even number of arguments.`);\n\n let inputType;\n let outputType;\n if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n const cases = {};\n const outputs = [];\n for (let i = 2; i < args.length - 1; i += 2) {\n let labels = args[i];\n const value = args[i + 1];\n\n if (!Array.isArray(labels)) {\n labels = [labels];\n }\n\n const labelContext = context.concat(i);\n if (labels.length === 0) {\n return labelContext.error('Expected at least one branch label.');\n }\n\n for (const label of labels) {\n if (typeof label !== 'number' && typeof label !== 'string') {\n return labelContext.error(`Branch labels must be numbers or strings.`);\n } else if (typeof label === 'number' && Math.abs(label) > Number.MAX_SAFE_INTEGER) {\n return labelContext.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);\n\n } else if (typeof label === 'number' && Math.floor(label) !== label) {\n return labelContext.error(`Numeric branch labels must be integer values.`);\n\n } else if (!inputType) {\n inputType = typeOf(label);\n } else if (labelContext.checkSubtype(inputType, typeOf(label))) {\n return null;\n }\n\n if (typeof cases[String(label)] !== 'undefined') {\n return labelContext.error('Branch labels must be unique.');\n }\n\n cases[String(label)] = outputs.length;\n }\n\n const result = context.parse(value, i, outputType);\n if (!result) return null;\n outputType = outputType || result.type;\n outputs.push(result);\n }\n\n const input = context.parse(args[1], 1, ValueType);\n if (!input) return null;\n\n const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);\n if (!otherwise) return null;\n\n assert(inputType && outputType);\n\n if (input.type.kind !== 'value' && context.concat(1).checkSubtype((inputType: any), input.type)) {\n return null;\n }\n\n return new Match((inputType: any), (outputType: any), input, cases, outputs, otherwise);\n }\n\n evaluate(ctx: EvaluationContext) {\n const input = (this.input.evaluate(ctx): any);\n const output = (typeOf(input) === this.inputType && this.outputs[this.cases[input]]) || this.otherwise;\n return output.evaluate(ctx);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n this.outputs.forEach(fn);\n fn(this.otherwise);\n }\n\n outputDefined(): boolean {\n return this.outputs.every(out => out.outputDefined()) && this.otherwise.outputDefined();\n }\n\n serialize(): Array {\n const serialized = [\"match\", this.input.serialize()];\n\n // Sort so serialization has an arbitrary defined order, even though\n // branch order doesn't affect evaluation\n const sortedLabels = Object.keys(this.cases).sort();\n\n // Group branches by unique match expression to support condensed\n // serializations of the form [case1, case2, ...] -> matchExpression\n const groupedByOutput: Array<[number, Array]> = [];\n const outputLookup: {[index: number]: number} = {}; // lookup index into groupedByOutput for a given output expression\n for (const label of sortedLabels) {\n const outputIndex = outputLookup[this.cases[label]];\n if (outputIndex === undefined) {\n // First time seeing this output, add it to the end of the grouped list\n outputLookup[this.cases[label]] = groupedByOutput.length;\n groupedByOutput.push([this.cases[label], [label]]);\n } else {\n // We've seen this expression before, add the label to that output's group\n groupedByOutput[outputIndex][1].push(label);\n }\n }\n\n const coerceLabel = (label) => this.inputType.kind === 'number' ? Number(label) : label;\n\n for (const [outputIndex, labels] of groupedByOutput) {\n if (labels.length === 1) {\n // Only a single label matches this output expression\n serialized.push(coerceLabel(labels[0]));\n } else {\n // Array of literal labels pointing to this output expression\n serialized.push(labels.map(coerceLabel));\n }\n serialized.push(this.outputs[outputIndex].serialize());\n }\n serialized.push(this.otherwise.serialize());\n return serialized;\n }\n}\n\nexport default Match;\n","// @flow\n\nimport assert from 'assert';\n\nimport {BooleanType} from '../types';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\ntype Branches = Array<[Expression, Expression]>;\n\nclass Case implements Expression {\n type: Type;\n\n branches: Branches;\n otherwise: Expression;\n\n constructor(type: Type, branches: Branches, otherwise: Expression) {\n this.type = type;\n this.branches = branches;\n this.otherwise = otherwise;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length < 4)\n return context.error(`Expected at least 3 arguments, but found only ${args.length - 1}.`);\n if (args.length % 2 !== 0)\n return context.error(`Expected an odd number of arguments.`);\n\n let outputType: ?Type;\n if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n\n const branches = [];\n for (let i = 1; i < args.length - 1; i += 2) {\n const test = context.parse(args[i], i, BooleanType);\n if (!test) return null;\n\n const result = context.parse(args[i + 1], i + 1, outputType);\n if (!result) return null;\n\n branches.push([test, result]);\n\n outputType = outputType || result.type;\n }\n\n const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);\n if (!otherwise) return null;\n\n assert(outputType);\n return new Case((outputType: any), branches, otherwise);\n }\n\n evaluate(ctx: EvaluationContext) {\n for (const [test, expression] of this.branches) {\n if (test.evaluate(ctx)) {\n return expression.evaluate(ctx);\n }\n }\n return this.otherwise.evaluate(ctx);\n }\n\n eachChild(fn: (_: Expression) => void) {\n for (const [test, expression] of this.branches) {\n fn(test);\n fn(expression);\n }\n fn(this.otherwise);\n }\n\n outputDefined(): boolean {\n return this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined();\n }\n\n serialize() {\n const serialized = [\"case\"];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Case;\n","// @flow\n\nimport {ValueType, NumberType, StringType, array, toString, isValidType, isValidNativeType} from '../types';\nimport RuntimeError from '../runtime_error';\nimport {typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nclass Slice implements Expression {\n type: Type;\n input: Expression;\n beginIndex: Expression;\n endIndex: ?Expression;\n\n constructor(type: Type, input: Expression, beginIndex: Expression, endIndex?: Expression) {\n this.type = type;\n this.input = input;\n this.beginIndex = beginIndex;\n this.endIndex = endIndex;\n\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length <= 2 || args.length >= 5) {\n return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`);\n }\n\n const input = context.parse(args[1], 1, ValueType);\n const beginIndex = context.parse(args[2], 2, NumberType);\n\n if (!input || !beginIndex) return null;\n\n if (!isValidType(input.type, [array(ValueType), StringType, ValueType])) {\n return context.error(`Expected first argument to be of type array or string, but found ${toString(input.type)} instead`);\n }\n\n if (args.length === 4) {\n const endIndex = context.parse(args[3], 3, NumberType);\n if (!endIndex) return null;\n return new Slice(input.type, input, beginIndex, endIndex);\n } else {\n return new Slice(input.type, input, beginIndex);\n }\n }\n\n evaluate(ctx: EvaluationContext) {\n const input = (this.input.evaluate(ctx): any);\n const beginIndex = (this.beginIndex.evaluate(ctx): number);\n\n if (!isValidNativeType(input, ['string', 'array'])) {\n throw new RuntimeError(`Expected first argument to be of type array or string, but found ${toString(typeOf(input))} instead.`);\n }\n\n if (this.endIndex) {\n const endIndex = (this.endIndex.evaluate(ctx): number);\n return input.slice(beginIndex, endIndex);\n }\n\n return input.slice(beginIndex);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n fn(this.beginIndex);\n if (this.endIndex) {\n fn(this.endIndex);\n }\n }\n\n outputDefined() {\n return false;\n }\n\n serialize() {\n if (this.endIndex != null && this.endIndex !== undefined) {\n const endIndex = this.endIndex.serialize();\n return [\"slice\", this.input.serialize(), this.beginIndex.serialize(), endIndex];\n }\n return [\"slice\", this.input.serialize(), this.beginIndex.serialize()];\n }\n}\n\nexport default Slice;\n","// @flow\n\nimport {toString, ValueType, BooleanType, CollatorType} from '../types';\nimport Assertion from './assertion';\nimport {typeOf} from '../values';\nimport RuntimeError from '../runtime_error';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\n\ntype ComparisonOperator = '==' | '!=' | '<' | '>' | '<=' | '>=' ;\n\nfunction isComparableType(op: ComparisonOperator, type: Type) {\n if (op === '==' || op === '!=') {\n // equality operator\n return type.kind === 'boolean' ||\n type.kind === 'string' ||\n type.kind === 'number' ||\n type.kind === 'null' ||\n type.kind === 'value';\n } else {\n // ordering operator\n return type.kind === 'string' ||\n type.kind === 'number' ||\n type.kind === 'value';\n }\n}\n\nfunction eq(ctx, a, b) { return a === b; }\nfunction neq(ctx, a, b) { return a !== b; }\nfunction lt(ctx, a, b) { return a < b; }\nfunction gt(ctx, a, b) { return a > b; }\nfunction lteq(ctx, a, b) { return a <= b; }\nfunction gteq(ctx, a, b) { return a >= b; }\n\nfunction eqCollate(ctx, a, b, c) { return c.compare(a, b) === 0; }\nfunction neqCollate(ctx, a, b, c) { return !eqCollate(ctx, a, b, c); }\nfunction ltCollate(ctx, a, b, c) { return c.compare(a, b) < 0; }\nfunction gtCollate(ctx, a, b, c) { return c.compare(a, b) > 0; }\nfunction lteqCollate(ctx, a, b, c) { return c.compare(a, b) <= 0; }\nfunction gteqCollate(ctx, a, b, c) { return c.compare(a, b) >= 0; }\n\n/**\n * Special form for comparison operators, implementing the signatures:\n * - (T, T, ?Collator) => boolean\n * - (T, value, ?Collator) => boolean\n * - (value, T, ?Collator) => boolean\n *\n * For inequalities, T must be either value, string, or number. For ==/!=, it\n * can also be boolean or null.\n *\n * Equality semantics are equivalent to Javascript's strict equality (===/!==)\n * -- i.e., when the arguments' types don't match, == evaluates to false, != to\n * true.\n *\n * When types don't match in an ordering comparison, a runtime error is thrown.\n *\n * @private\n */\nfunction makeComparison(op: ComparisonOperator, compareBasic, compareWithCollator) {\n const isOrderComparison = op !== '==' && op !== '!=';\n\n return class Comparison implements Expression {\n type: Type;\n lhs: Expression;\n rhs: Expression;\n collator: ?Expression;\n hasUntypedArgument: boolean;\n\n constructor(lhs: Expression, rhs: Expression, collator: ?Expression) {\n this.type = BooleanType;\n this.lhs = lhs;\n this.rhs = rhs;\n this.collator = collator;\n this.hasUntypedArgument = lhs.type.kind === 'value' || rhs.type.kind === 'value';\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length !== 3 && args.length !== 4)\n return context.error(`Expected two or three arguments.`);\n\n const op: ComparisonOperator = (args[0]: any);\n\n let lhs = context.parse(args[1], 1, ValueType);\n if (!lhs) return null;\n if (!isComparableType(op, lhs.type)) {\n return context.concat(1).error(`\"${op}\" comparisons are not supported for type '${toString(lhs.type)}'.`);\n }\n let rhs = context.parse(args[2], 2, ValueType);\n if (!rhs) return null;\n if (!isComparableType(op, rhs.type)) {\n return context.concat(2).error(`\"${op}\" comparisons are not supported for type '${toString(rhs.type)}'.`);\n }\n\n if (\n lhs.type.kind !== rhs.type.kind &&\n lhs.type.kind !== 'value' &&\n rhs.type.kind !== 'value'\n ) {\n return context.error(`Cannot compare types '${toString(lhs.type)}' and '${toString(rhs.type)}'.`);\n }\n\n if (isOrderComparison) {\n // typing rules specific to less/greater than operators\n if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') {\n // (value, T)\n lhs = new Assertion(rhs.type, [lhs]);\n } else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') {\n // (T, value)\n rhs = new Assertion(lhs.type, [rhs]);\n }\n }\n\n let collator = null;\n if (args.length === 4) {\n if (\n lhs.type.kind !== 'string' &&\n rhs.type.kind !== 'string' &&\n lhs.type.kind !== 'value' &&\n rhs.type.kind !== 'value'\n ) {\n return context.error(`Cannot use collator to compare non-string types.`);\n }\n collator = context.parse(args[3], 3, CollatorType);\n if (!collator) return null;\n }\n\n return new Comparison(lhs, rhs, collator);\n }\n\n evaluate(ctx: EvaluationContext) {\n const lhs = this.lhs.evaluate(ctx);\n const rhs = this.rhs.evaluate(ctx);\n\n if (isOrderComparison && this.hasUntypedArgument) {\n const lt = typeOf(lhs);\n const rt = typeOf(rhs);\n // check that type is string or number, and equal\n if (lt.kind !== rt.kind || !(lt.kind === 'string' || lt.kind === 'number')) {\n throw new RuntimeError(`Expected arguments for \"${op}\" to be (string, string) or (number, number), but found (${lt.kind}, ${rt.kind}) instead.`);\n }\n }\n\n if (this.collator && !isOrderComparison && this.hasUntypedArgument) {\n const lt = typeOf(lhs);\n const rt = typeOf(rhs);\n if (lt.kind !== 'string' || rt.kind !== 'string') {\n return compareBasic(ctx, lhs, rhs);\n }\n }\n\n return this.collator ?\n compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) :\n compareBasic(ctx, lhs, rhs);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.lhs);\n fn(this.rhs);\n if (this.collator) {\n fn(this.collator);\n }\n }\n\n outputDefined(): boolean {\n return true;\n }\n\n serialize() {\n const serialized = [op];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n };\n}\n\nexport const Equals = makeComparison('==', eq, eqCollate);\nexport const NotEquals = makeComparison('!=', neq, neqCollate);\nexport const LessThan = makeComparison('<', lt, ltCollate);\nexport const GreaterThan = makeComparison('>', gt, gtCollate);\nexport const LessThanOrEqual = makeComparison('<=', lteq, lteqCollate);\nexport const GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate);\n","// @flow\n\nimport {StringType, NumberType} from '../types';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\n\ndeclare var Intl: {\n NumberFormat: Class\n};\n\ndeclare class Intl$NumberFormat {\n constructor (\n locales?: string | string[],\n options?: NumberFormatOptions\n ): Intl$NumberFormat;\n\n static (\n locales?: string | string[],\n options?: NumberFormatOptions\n ): Intl$NumberFormat;\n\n format(a: number): string;\n\n resolvedOptions(): any;\n}\n\ntype NumberFormatOptions = {\n style?: 'decimal' | 'currency' | 'percent';\n currency?: null | string;\n minimumFractionDigits?: null | string;\n maximumFractionDigits?: null | string;\n};\n\nexport default class NumberFormat implements Expression {\n type: Type;\n number: Expression;\n locale: Expression | null; // BCP 47 language tag\n currency: Expression | null; // ISO 4217 currency code, required if style=currency\n minFractionDigits: Expression | null; // Default 0\n maxFractionDigits: Expression | null; // Default 3\n\n constructor(number: Expression,\n locale: Expression | null,\n currency: Expression | null,\n minFractionDigits: Expression | null,\n maxFractionDigits: Expression | null) {\n this.type = StringType;\n this.number = number;\n this.locale = locale;\n this.currency = currency;\n this.minFractionDigits = minFractionDigits;\n this.maxFractionDigits = maxFractionDigits;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression {\n if (args.length !== 3)\n return context.error(`Expected two arguments.`);\n\n const number = context.parse(args[1], 1, NumberType);\n if (!number) return null;\n\n const options = (args[2]: any);\n if (typeof options !== \"object\" || Array.isArray(options))\n return context.error(`NumberFormat options argument must be an object.`);\n\n let locale = null;\n if (options['locale']) {\n locale = context.parse(options['locale'], 1, StringType);\n if (!locale) return null;\n }\n\n let currency = null;\n if (options['currency']) {\n currency = context.parse(options['currency'], 1, StringType);\n if (!currency) return null;\n }\n\n let minFractionDigits = null;\n if (options['min-fraction-digits']) {\n minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType);\n if (!minFractionDigits) return null;\n }\n\n let maxFractionDigits = null;\n if (options['max-fraction-digits']) {\n maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType);\n if (!maxFractionDigits) return null;\n }\n\n return new NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits);\n }\n\n evaluate(ctx: EvaluationContext) {\n return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [],\n {\n style: this.currency ? \"currency\" : \"decimal\",\n currency: this.currency ? this.currency.evaluate(ctx) : undefined,\n minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : undefined,\n maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : undefined,\n }).format(this.number.evaluate(ctx));\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.number);\n if (this.locale) {\n fn(this.locale);\n }\n if (this.currency) {\n fn(this.currency);\n }\n if (this.minFractionDigits) {\n fn(this.minFractionDigits);\n }\n if (this.maxFractionDigits) {\n fn(this.maxFractionDigits);\n }\n }\n\n outputDefined() {\n return false;\n }\n\n serialize() {\n const options = {};\n if (this.locale) {\n options['locale'] = this.locale.serialize();\n }\n if (this.currency) {\n options['currency'] = this.currency.serialize();\n }\n if (this.minFractionDigits) {\n options['min-fraction-digits'] = this.minFractionDigits.serialize();\n }\n if (this.maxFractionDigits) {\n options['max-fraction-digits'] = this.maxFractionDigits.serialize();\n }\n return [\"number-format\", this.number.serialize(), options];\n }\n}\n","// @flow\n\nimport {NumberType, toString} from '../types';\n\nimport {typeOf} from '../values';\nimport RuntimeError from '../runtime_error';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nclass Length implements Expression {\n type: Type;\n input: Expression;\n\n constructor(input: Expression) {\n this.type = NumberType;\n this.input = input;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\n if (args.length !== 2)\n return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`);\n\n const input = context.parse(args[1], 1);\n if (!input) return null;\n\n if (input.type.kind !== 'array' && input.type.kind !== 'string' && input.type.kind !== 'value')\n return context.error(`Expected argument of type string or array, but found ${toString(input.type)} instead.`);\n\n return new Length(input);\n }\n\n evaluate(ctx: EvaluationContext) {\n const input = this.input.evaluate(ctx);\n if (typeof input === 'string') {\n return input.length;\n } else if (Array.isArray(input)) {\n return input.length;\n } else {\n throw new RuntimeError(`Expected value to be of type string or array, but found ${toString(typeOf(input))} instead.`);\n }\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n }\n\n outputDefined() {\n return false;\n }\n\n serialize() {\n const serialized = [\"length\"];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Length;\n","// @flow\n\nimport {\n type Type,\n NumberType,\n StringType,\n BooleanType,\n ColorType,\n ObjectType,\n ValueType,\n ErrorType,\n CollatorType,\n array,\n toString as typeToString\n} from '../types';\n\nimport {typeOf, Color, validateRGBA, toString as valueToString} from '../values';\nimport CompoundExpression from '../compound_expression';\nimport RuntimeError from '../runtime_error';\nimport Let from './let';\nimport Var from './var';\nimport Literal from './literal';\nimport Assertion from './assertion';\nimport Coercion from './coercion';\nimport At from './at';\nimport In from './in';\nimport IndexOf from './index_of';\nimport Match from './match';\nimport Case from './case';\nimport Slice from './slice';\nimport Step from './step';\nimport Interpolate from './interpolate';\nimport Coalesce from './coalesce';\nimport {\n Equals,\n NotEquals,\n LessThan,\n GreaterThan,\n LessThanOrEqual,\n GreaterThanOrEqual\n} from './comparison';\nimport CollatorExpression from './collator';\nimport NumberFormat from './number_format';\nimport FormatExpression from './format';\nimport ImageExpression from './image';\nimport Length from './length';\nimport Within from './within';\n\nimport type {Varargs} from '../compound_expression';\nimport type {ExpressionRegistry} from '../expression';\n\nconst expressions: ExpressionRegistry = {\n // special forms\n '==': Equals,\n '!=': NotEquals,\n '>': GreaterThan,\n '<': LessThan,\n '>=': GreaterThanOrEqual,\n '<=': LessThanOrEqual,\n 'array': Assertion,\n 'at': At,\n 'boolean': Assertion,\n 'case': Case,\n 'coalesce': Coalesce,\n 'collator': CollatorExpression,\n 'format': FormatExpression,\n 'image': ImageExpression,\n 'in': In,\n 'index-of': IndexOf,\n 'interpolate': Interpolate,\n 'interpolate-hcl': Interpolate,\n 'interpolate-lab': Interpolate,\n 'length': Length,\n 'let': Let,\n 'literal': Literal,\n 'match': Match,\n 'number': Assertion,\n 'number-format': NumberFormat,\n 'object': Assertion,\n 'slice': Slice,\n 'step': Step,\n 'string': Assertion,\n 'to-boolean': Coercion,\n 'to-color': Coercion,\n 'to-number': Coercion,\n 'to-string': Coercion,\n 'var': Var,\n 'within': Within\n};\n\nfunction rgba(ctx, [r, g, b, a]) {\n r = r.evaluate(ctx);\n g = g.evaluate(ctx);\n b = b.evaluate(ctx);\n const alpha = a ? a.evaluate(ctx) : 1;\n const error = validateRGBA(r, g, b, alpha);\n if (error) throw new RuntimeError(error);\n return new Color(r / 255 * alpha, g / 255 * alpha, b / 255 * alpha, alpha);\n}\n\nfunction has(key, obj) {\n return key in obj;\n}\n\nfunction get(key, obj) {\n const v = obj[key];\n return typeof v === 'undefined' ? null : v;\n}\n\nfunction binarySearch(v, a, i, j) {\n while (i <= j) {\n const m = (i + j) >> 1;\n if (a[m] === v)\n return true;\n if (a[m] > v)\n j = m - 1;\n else\n i = m + 1;\n }\n return false;\n}\n\nfunction varargs(type: Type): Varargs {\n return {type};\n}\n\nCompoundExpression.register(expressions, {\n 'error': [\n ErrorType,\n [StringType],\n (ctx, [v]) => { throw new RuntimeError(v.evaluate(ctx)); }\n ],\n 'typeof': [\n StringType,\n [ValueType],\n (ctx, [v]) => typeToString(typeOf(v.evaluate(ctx)))\n ],\n 'to-rgba': [\n array(NumberType, 4),\n [ColorType],\n (ctx, [v]) => {\n return v.evaluate(ctx).toArray();\n }\n ],\n 'rgb': [\n ColorType,\n [NumberType, NumberType, NumberType],\n rgba\n ],\n 'rgba': [\n ColorType,\n [NumberType, NumberType, NumberType, NumberType],\n rgba\n ],\n 'has': {\n type: BooleanType,\n overloads: [\n [\n [StringType],\n (ctx, [key]) => has(key.evaluate(ctx), ctx.properties())\n ], [\n [StringType, ObjectType],\n (ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx))\n ]\n ]\n },\n 'get': {\n type: ValueType,\n overloads: [\n [\n [StringType],\n (ctx, [key]) => get(key.evaluate(ctx), ctx.properties())\n ], [\n [StringType, ObjectType],\n (ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx))\n ]\n ]\n },\n 'feature-state': [\n ValueType,\n [StringType],\n (ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {})\n ],\n 'properties': [\n ObjectType,\n [],\n (ctx) => ctx.properties()\n ],\n 'geometry-type': [\n StringType,\n [],\n (ctx) => ctx.geometryType()\n ],\n 'id': [\n ValueType,\n [],\n (ctx) => ctx.id()\n ],\n 'zoom': [\n NumberType,\n [],\n (ctx) => ctx.globals.zoom\n ],\n 'heatmap-density': [\n NumberType,\n [],\n (ctx) => ctx.globals.heatmapDensity || 0\n ],\n 'line-progress': [\n NumberType,\n [],\n (ctx) => ctx.globals.lineProgress || 0\n ],\n 'accumulated': [\n ValueType,\n [],\n (ctx) => ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated\n ],\n '+': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => {\n let result = 0;\n for (const arg of args) {\n result += arg.evaluate(ctx);\n }\n return result;\n }\n ],\n '*': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => {\n let result = 1;\n for (const arg of args) {\n result *= arg.evaluate(ctx);\n }\n return result;\n }\n ],\n '-': {\n type: NumberType,\n overloads: [\n [\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx)\n ], [\n [NumberType],\n (ctx, [a]) => -a.evaluate(ctx)\n ]\n ]\n },\n '/': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx)\n ],\n '%': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx)\n ],\n 'ln2': [\n NumberType,\n [],\n () => Math.LN2\n ],\n 'pi': [\n NumberType,\n [],\n () => Math.PI\n ],\n 'e': [\n NumberType,\n [],\n () => Math.E\n ],\n '^': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx))\n ],\n 'sqrt': [\n NumberType,\n [NumberType],\n (ctx, [x]) => Math.sqrt(x.evaluate(ctx))\n ],\n 'log10': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10\n ],\n 'ln': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx))\n ],\n 'log2': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2\n ],\n 'sin': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.sin(n.evaluate(ctx))\n ],\n 'cos': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.cos(n.evaluate(ctx))\n ],\n 'tan': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.tan(n.evaluate(ctx))\n ],\n 'asin': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.asin(n.evaluate(ctx))\n ],\n 'acos': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.acos(n.evaluate(ctx))\n ],\n 'atan': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.atan(n.evaluate(ctx))\n ],\n 'min': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => Math.min(...args.map(arg => arg.evaluate(ctx)))\n ],\n 'max': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => Math.max(...args.map(arg => arg.evaluate(ctx)))\n ],\n 'abs': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.abs(n.evaluate(ctx))\n ],\n 'round': [\n NumberType,\n [NumberType],\n (ctx, [n]) => {\n const v = n.evaluate(ctx);\n // Javascript's Math.round() rounds towards +Infinity for halfway\n // values, even when they're negative. It's more common to round\n // away from 0 (e.g., this is what python and C++ do)\n return v < 0 ? -Math.round(-v) : Math.round(v);\n }\n ],\n 'floor': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.floor(n.evaluate(ctx))\n ],\n 'ceil': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.ceil(n.evaluate(ctx))\n ],\n 'filter-==': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => ctx.properties()[(k: any).value] === (v: any).value\n ],\n 'filter-id-==': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => ctx.id() === (v: any).value\n ],\n 'filter-type-==': [\n BooleanType,\n [StringType],\n (ctx, [v]) => ctx.geometryType() === (v: any).value\n ],\n 'filter-<': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a < b;\n }\n ],\n 'filter-id-<': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a < b;\n }\n ],\n 'filter->': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a > b;\n }\n ],\n 'filter-id->': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a > b;\n }\n ],\n 'filter-<=': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a <= b;\n }\n ],\n 'filter-id-<=': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a <= b;\n }\n ],\n 'filter->=': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a >= b;\n }\n ],\n 'filter-id->=': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a >= b;\n }\n ],\n 'filter-has': [\n BooleanType,\n [ValueType],\n (ctx, [k]) => (k: any).value in ctx.properties()\n ],\n 'filter-has-id': [\n BooleanType,\n [],\n (ctx) => (ctx.id() !== null && ctx.id() !== undefined)\n ],\n 'filter-type-in': [\n BooleanType,\n [array(StringType)],\n (ctx, [v]) => (v: any).value.indexOf(ctx.geometryType()) >= 0\n ],\n 'filter-id-in': [\n BooleanType,\n [array(ValueType)],\n (ctx, [v]) => (v: any).value.indexOf(ctx.id()) >= 0\n ],\n 'filter-in-small': [\n BooleanType,\n [StringType, array(ValueType)],\n // assumes v is an array literal\n (ctx, [k, v]) => (v: any).value.indexOf(ctx.properties()[(k: any).value]) >= 0\n ],\n 'filter-in-large': [\n BooleanType,\n [StringType, array(ValueType)],\n // assumes v is a array literal with values sorted in ascending order and of a single type\n (ctx, [k, v]) => binarySearch(ctx.properties()[(k: any).value], (v: any).value, 0, (v: any).value.length - 1)\n ],\n 'all': {\n type: BooleanType,\n overloads: [\n [\n [BooleanType, BooleanType],\n (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx)\n ],\n [\n varargs(BooleanType),\n (ctx, args) => {\n for (const arg of args) {\n if (!arg.evaluate(ctx))\n return false;\n }\n return true;\n }\n ]\n ]\n },\n 'any': {\n type: BooleanType,\n overloads: [\n [\n [BooleanType, BooleanType],\n (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx)\n ],\n [\n varargs(BooleanType),\n (ctx, args) => {\n for (const arg of args) {\n if (arg.evaluate(ctx))\n return true;\n }\n return false;\n }\n ]\n ]\n },\n '!': [\n BooleanType,\n [BooleanType],\n (ctx, [b]) => !b.evaluate(ctx)\n ],\n 'is-supported-script': [\n BooleanType,\n [StringType],\n // At parse time this will always return true, so we need to exclude this expression with isGlobalPropertyConstant\n (ctx, [s]) => {\n const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript;\n if (isSupportedScript) {\n return isSupportedScript(s.evaluate(ctx));\n }\n return true;\n }\n ],\n 'upcase': [\n StringType,\n [StringType],\n (ctx, [s]) => s.evaluate(ctx).toUpperCase()\n ],\n 'downcase': [\n StringType,\n [StringType],\n (ctx, [s]) => s.evaluate(ctx).toLowerCase()\n ],\n 'concat': [\n StringType,\n varargs(ValueType),\n (ctx, args) => args.map(arg => valueToString(arg.evaluate(ctx))).join('')\n ],\n 'resolved-locale': [\n StringType,\n [CollatorType],\n (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale()\n ]\n});\n\nexport default expressions;\n","// @flow\n\n/**\n * A type used for returning and propagating errors. The first element of the union\n * represents success and contains a value, and the second represents an error and\n * contains an error value.\n * @private\n */\nexport type Result =\n | {| result: 'success', value: T |}\n | {| result: 'error', value: E |};\n\nexport function success(value: T): Result {\n return {result: 'success', value};\n}\n\nexport function error(value: E): Result {\n return {result: 'error', value};\n}\n","// @flow\n\nimport type {StylePropertySpecification} from '../style-spec';\n\nexport function supportsPropertyExpression(spec: StylePropertySpecification): boolean {\n return spec['property-type'] === 'data-driven' || spec['property-type'] === 'cross-faded-data-driven';\n}\n\nexport function supportsZoomExpression(spec: StylePropertySpecification): boolean {\n return !!spec.expression && spec.expression.parameters.indexOf('zoom') > -1;\n}\n\nexport function supportsInterpolation(spec: StylePropertySpecification): boolean {\n return !!spec.expression && spec.expression.interpolated;\n}\n","// @flow\n\nexport default function getType(val: mixed): string {\n if (val instanceof Number) {\n return 'number';\n } else if (val instanceof String) {\n return 'string';\n } else if (val instanceof Boolean) {\n return 'boolean';\n } else if (Array.isArray(val)) {\n return 'array';\n } else if (val === null) {\n return 'null';\n } else {\n return typeof val;\n }\n}\n","\nimport * as colorSpaces from '../util/color_spaces';\nimport Color from '../util/color';\nimport extend from '../util/extend';\nimport getType from '../util/get_type';\nimport * as interpolate from '../util/interpolate';\nimport Interpolate from '../expression/definitions/interpolate';\nimport Formatted from '../expression/types/formatted';\nimport ResolvedImage from '../expression/types/resolved_image';\nimport {supportsInterpolation} from '../util/properties';\nimport {findStopLessThanOrEqualTo} from '../expression/stops';\n\nexport function isFunction(value) {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction identityFunction(x) {\n return x;\n}\n\nexport function createFunction(parameters, propertySpec) {\n const isColor = propertySpec.type === 'color';\n const zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === 'object';\n const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined;\n const zoomDependent = zoomAndFeatureDependent || !featureDependent;\n const type = parameters.type || (supportsInterpolation(propertySpec) ? 'exponential' : 'interval');\n\n if (isColor) {\n parameters = extend({}, parameters);\n\n if (parameters.stops) {\n parameters.stops = parameters.stops.map((stop) => {\n return [stop[0], Color.parse(stop[1])];\n });\n }\n\n if (parameters.default) {\n parameters.default = Color.parse(parameters.default);\n } else {\n parameters.default = Color.parse(propertySpec.default);\n }\n }\n\n if (parameters.colorSpace && parameters.colorSpace !== 'rgb' && !colorSpaces[parameters.colorSpace]) { // eslint-disable-line import/namespace\n throw new Error(`Unknown color space: ${parameters.colorSpace}`);\n }\n\n let innerFun;\n let hashedStops;\n let categoricalKeyType;\n if (type === 'exponential') {\n innerFun = evaluateExponentialFunction;\n } else if (type === 'interval') {\n innerFun = evaluateIntervalFunction;\n } else if (type === 'categorical') {\n innerFun = evaluateCategoricalFunction;\n\n // For categorical functions, generate an Object as a hashmap of the stops for fast searching\n hashedStops = Object.create(null);\n for (const stop of parameters.stops) {\n hashedStops[stop[0]] = stop[1];\n }\n\n // Infer key type based on first stop key-- used to encforce strict type checking later\n categoricalKeyType = typeof parameters.stops[0][0];\n\n } else if (type === 'identity') {\n innerFun = evaluateIdentityFunction;\n } else {\n throw new Error(`Unknown function type \"${type}\"`);\n }\n\n if (zoomAndFeatureDependent) {\n const featureFunctions = {};\n const zoomStops = [];\n for (let s = 0; s < parameters.stops.length; s++) {\n const stop = parameters.stops[s];\n const zoom = stop[0].zoom;\n if (featureFunctions[zoom] === undefined) {\n featureFunctions[zoom] = {\n zoom,\n type: parameters.type,\n property: parameters.property,\n default: parameters.default,\n stops: []\n };\n zoomStops.push(zoom);\n }\n featureFunctions[zoom].stops.push([stop[0].value, stop[1]]);\n }\n\n const featureFunctionStops = [];\n for (const z of zoomStops) {\n featureFunctionStops.push([featureFunctions[z].zoom, createFunction(featureFunctions[z], propertySpec)]);\n }\n\n const interpolationType = {name: 'linear'};\n return {\n kind: 'composite',\n interpolationType,\n interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType),\n zoomStops: featureFunctionStops.map(s => s[0]),\n evaluate({zoom}, properties) {\n return evaluateExponentialFunction({\n stops: featureFunctionStops,\n base: parameters.base\n }, propertySpec, zoom).evaluate(zoom, properties);\n }\n };\n } else if (zoomDependent) {\n const interpolationType = type === 'exponential' ?\n {name: 'exponential', base: parameters.base !== undefined ? parameters.base : 1} : null;\n return {\n kind: 'camera',\n interpolationType,\n interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType),\n zoomStops: parameters.stops.map(s => s[0]),\n evaluate: ({zoom}) => innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType)\n };\n } else {\n return {\n kind: 'source',\n evaluate(_, feature) {\n const value = feature && feature.properties ? feature.properties[parameters.property] : undefined;\n if (value === undefined) {\n return coalesce(parameters.default, propertySpec.default);\n }\n return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType);\n }\n };\n }\n}\n\nfunction coalesce(a, b, c) {\n if (a !== undefined) return a;\n if (b !== undefined) return b;\n if (c !== undefined) return c;\n}\n\nfunction evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) {\n const evaluated = typeof input === keyType ? hashedStops[input] : undefined; // Enforce strict typing on input\n return coalesce(evaluated, parameters.default, propertySpec.default);\n}\n\nfunction evaluateIntervalFunction(parameters, propertySpec, input) {\n // Edge cases\n if (getType(input) !== 'number') return coalesce(parameters.default, propertySpec.default);\n const n = parameters.stops.length;\n if (n === 1) return parameters.stops[0][1];\n if (input <= parameters.stops[0][0]) return parameters.stops[0][1];\n if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1];\n\n const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input);\n\n return parameters.stops[index][1];\n}\n\nfunction evaluateExponentialFunction(parameters, propertySpec, input) {\n const base = parameters.base !== undefined ? parameters.base : 1;\n\n // Edge cases\n if (getType(input) !== 'number') return coalesce(parameters.default, propertySpec.default);\n const n = parameters.stops.length;\n if (n === 1) return parameters.stops[0][1];\n if (input <= parameters.stops[0][0]) return parameters.stops[0][1];\n if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1];\n\n const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input);\n const t = interpolationFactor(\n input, base,\n parameters.stops[index][0],\n parameters.stops[index + 1][0]);\n\n const outputLower = parameters.stops[index][1];\n const outputUpper = parameters.stops[index + 1][1];\n let interp = interpolate[propertySpec.type] || identityFunction; // eslint-disable-line import/namespace\n\n if (parameters.colorSpace && parameters.colorSpace !== 'rgb') {\n const colorspace = colorSpaces[parameters.colorSpace]; // eslint-disable-line import/namespace\n interp = (a, b) => colorspace.reverse(colorspace.interpolate(colorspace.forward(a), colorspace.forward(b), t));\n }\n\n if (typeof outputLower.evaluate === 'function') {\n return {\n evaluate(...args) {\n const evaluatedLower = outputLower.evaluate.apply(undefined, args);\n const evaluatedUpper = outputUpper.evaluate.apply(undefined, args);\n // Special case for fill-outline-color, which has no spec default.\n if (evaluatedLower === undefined || evaluatedUpper === undefined) {\n return undefined;\n }\n return interp(evaluatedLower, evaluatedUpper, t);\n }\n };\n }\n\n return interp(outputLower, outputUpper, t);\n}\n\nfunction evaluateIdentityFunction(parameters, propertySpec, input) {\n if (propertySpec.type === 'color') {\n input = Color.parse(input);\n } else if (propertySpec.type === 'formatted') {\n input = Formatted.fromString(input.toString());\n } else if (propertySpec.type === 'resolvedImage') {\n input = ResolvedImage.fromString(input.toString());\n } else if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) {\n input = undefined;\n }\n return coalesce(input, parameters.default, propertySpec.default);\n}\n\n/**\n * Returns a ratio that can be used to interpolate between exponential function\n * stops.\n *\n * How it works:\n * Two consecutive stop values define a (scaled and shifted) exponential\n * function `f(x) = a * base^x + b`, where `base` is the user-specified base,\n * and `a` and `b` are constants affording sufficient degrees of freedom to fit\n * the function to the given stops.\n *\n * Here's a bit of algebra that lets us compute `f(x)` directly from the stop\n * values without explicitly solving for `a` and `b`:\n *\n * First stop value: `f(x0) = y0 = a * base^x0 + b`\n * Second stop value: `f(x1) = y1 = a * base^x1 + b`\n * => `y1 - y0 = a(base^x1 - base^x0)`\n * => `a = (y1 - y0)/(base^x1 - base^x0)`\n *\n * Desired value: `f(x) = y = a * base^x + b`\n * => `f(x) = y0 + a * (base^x - base^x0)`\n *\n * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a\n * little algebra:\n * ```\n * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0)\n * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0)\n * ```\n *\n * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have\n * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as\n * an interpolation factor between the two stops' output values.\n *\n * (Note: a slightly different form for `ratio`,\n * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer\n * expensive `Math.pow()` operations.)\n *\n * @private\n */\nfunction interpolationFactor(input, base, lowerValue, upperValue) {\n const difference = upperValue - lowerValue;\n const progress = input - lowerValue;\n\n if (difference === 0) {\n return 0;\n } else if (base === 1) {\n return progress / difference;\n } else {\n return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport extend from '../util/extend';\nimport ParsingError from './parsing_error';\nimport ParsingContext from './parsing_context';\nimport EvaluationContext from './evaluation_context';\nimport CompoundExpression from './compound_expression';\nimport Step from './definitions/step';\nimport Interpolate from './definitions/interpolate';\nimport Coalesce from './definitions/coalesce';\nimport Let from './definitions/let';\nimport definitions from './definitions';\nimport * as isConstant from './is_constant';\nimport RuntimeError from './runtime_error';\nimport {success, error} from '../util/result';\nimport {supportsPropertyExpression, supportsZoomExpression, supportsInterpolation} from '../util/properties';\n\nimport type {Type, EvaluationKind} from './types';\nimport type {Value} from './values';\nimport type {Expression} from './expression';\nimport type {StylePropertySpecification} from '../style-spec';\nimport type {Result} from '../util/result';\nimport type {InterpolationType} from './definitions/interpolate';\nimport type {PropertyValueSpecification} from '../types';\nimport type {FormattedSection} from './types/formatted';\nimport type Point from '@mapbox/point-geometry';\nimport type {CanonicalTileID} from '../../source/tile_id';\n\nexport type Feature = {\n +type: 1 | 2 | 3 | 'Unknown' | 'Point' | 'MultiPoint' | 'LineString' | 'MultiLineString' | 'Polygon' | 'MultiPolygon',\n +id?: any,\n +properties: {[_: string]: any},\n +patterns?: {[_: string]: {\"min\": string, \"mid\": string, \"max\": string}},\n +geometry?: Array>\n};\n\nexport type FeatureState = {[_: string]: any};\n\nexport type GlobalProperties = $ReadOnly<{\n zoom: number,\n heatmapDensity?: number,\n lineProgress?: number,\n isSupportedScript?: (_: string) => boolean,\n accumulated?: Value\n}>;\n\nexport class StyleExpression {\n expression: Expression;\n\n _evaluator: EvaluationContext;\n _defaultValue: Value;\n _warningHistory: {[key: string]: boolean};\n _enumValues: ?{[_: string]: any};\n\n constructor(expression: Expression, propertySpec: ?StylePropertySpecification) {\n this.expression = expression;\n this._warningHistory = {};\n this._evaluator = new EvaluationContext();\n this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null;\n this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null;\n }\n\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any {\n this._evaluator.globals = globals;\n this._evaluator.feature = feature;\n this._evaluator.featureState = featureState;\n this._evaluator.canonical = canonical;\n this._evaluator.availableImages = availableImages || null;\n this._evaluator.formattedSection = formattedSection;\n\n return this.expression.evaluate(this._evaluator);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any {\n this._evaluator.globals = globals;\n this._evaluator.feature = feature || null;\n this._evaluator.featureState = featureState || null;\n this._evaluator.canonical = canonical;\n this._evaluator.availableImages = availableImages || null;\n this._evaluator.formattedSection = formattedSection || null;\n\n try {\n const val = this.expression.evaluate(this._evaluator);\n // eslint-disable-next-line no-self-compare\n if (val === null || val === undefined || (typeof val === 'number' && val !== val)) {\n return this._defaultValue;\n }\n if (this._enumValues && !(val in this._enumValues)) {\n throw new RuntimeError(`Expected value to be one of ${Object.keys(this._enumValues).map(v => JSON.stringify(v)).join(', ')}, but found ${JSON.stringify(val)} instead.`);\n }\n return val;\n } catch (e) {\n if (!this._warningHistory[e.message]) {\n this._warningHistory[e.message] = true;\n if (typeof console !== 'undefined') {\n console.warn(e.message);\n }\n }\n return this._defaultValue;\n }\n }\n}\n\nexport function isExpression(expression: mixed) {\n return Array.isArray(expression) && expression.length > 0 &&\n typeof expression[0] === 'string' && expression[0] in definitions;\n}\n\n/**\n * Parse and typecheck the given style spec JSON expression. If\n * options.defaultValue is provided, then the resulting StyleExpression's\n * `evaluate()` method will handle errors by logging a warning (once per\n * message) and returning the default value. Otherwise, it will throw\n * evaluation errors.\n *\n * @private\n */\nexport function createExpression(expression: mixed, propertySpec: ?StylePropertySpecification): Result> {\n const parser = new ParsingContext(definitions, [], propertySpec ? getExpectedType(propertySpec) : undefined);\n\n // For string-valued properties, coerce to string at the top level rather than asserting.\n const parsed = parser.parse(expression, undefined, undefined, undefined,\n propertySpec && propertySpec.type === 'string' ? {typeAnnotation: 'coerce'} : undefined);\n\n if (!parsed) {\n assert(parser.errors.length > 0);\n return error(parser.errors);\n }\n\n return success(new StyleExpression(parsed, propertySpec));\n}\n\nexport class ZoomConstantExpression {\n kind: Kind;\n isStateDependent: boolean;\n _styleExpression: StyleExpression;\n\n constructor(kind: Kind, expression: StyleExpression) {\n this.kind = kind;\n this._styleExpression = expression;\n this.isStateDependent = kind !== ('constant': EvaluationKind) && !isConstant.isStateConstant(expression.expression);\n }\n\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n}\n\nexport class ZoomDependentExpression {\n kind: Kind;\n zoomStops: Array;\n isStateDependent: boolean;\n\n _styleExpression: StyleExpression;\n interpolationType: ?InterpolationType;\n\n constructor(kind: Kind, expression: StyleExpression, zoomStops: Array, interpolationType?: InterpolationType) {\n this.kind = kind;\n this.zoomStops = zoomStops;\n this._styleExpression = expression;\n this.isStateDependent = kind !== ('camera': EvaluationKind) && !isConstant.isStateConstant(expression.expression);\n this.interpolationType = interpolationType;\n }\n\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n\n interpolationFactor(input: number, lower: number, upper: number): number {\n if (this.interpolationType) {\n return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper);\n } else {\n return 0;\n }\n }\n}\n\nexport type ConstantExpression = {\n kind: 'constant',\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array) => any,\n}\n\nexport type SourceExpression = {\n kind: 'source',\n isStateDependent: boolean,\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection) => any,\n};\n\nexport type CameraExpression = {\n kind: 'camera',\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array) => any,\n +interpolationFactor: (input: number, lower: number, upper: number) => number,\n zoomStops: Array,\n interpolationType: ?InterpolationType\n};\n\nexport type CompositeExpression = {\n kind: 'composite',\n isStateDependent: boolean,\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection) => any,\n +interpolationFactor: (input: number, lower: number, upper: number) => number,\n zoomStops: Array,\n interpolationType: ?InterpolationType\n};\n\nexport type StylePropertyExpression =\n | ConstantExpression\n | SourceExpression\n | CameraExpression\n | CompositeExpression;\n\nexport function createPropertyExpression(expression: mixed, propertySpec: StylePropertySpecification): Result> {\n expression = createExpression(expression, propertySpec);\n if (expression.result === 'error') {\n return expression;\n }\n\n const parsed = expression.value.expression;\n\n const isFeatureConstant = isConstant.isFeatureConstant(parsed);\n if (!isFeatureConstant && !supportsPropertyExpression(propertySpec)) {\n return error([new ParsingError('', 'data expressions not supported')]);\n }\n\n const isZoomConstant = isConstant.isGlobalPropertyConstant(parsed, ['zoom']);\n if (!isZoomConstant && !supportsZoomExpression(propertySpec)) {\n return error([new ParsingError('', 'zoom expressions not supported')]);\n }\n\n const zoomCurve = findZoomCurve(parsed);\n if (!zoomCurve && !isZoomConstant) {\n return error([new ParsingError('', '\"zoom\" expression may only be used as input to a top-level \"step\" or \"interpolate\" expression.')]);\n } else if (zoomCurve instanceof ParsingError) {\n return error([zoomCurve]);\n } else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) {\n return error([new ParsingError('', '\"interpolate\" expressions cannot be used with this property')]);\n }\n\n if (!zoomCurve) {\n return success(isFeatureConstant ?\n (new ZoomConstantExpression('constant', expression.value): ConstantExpression) :\n (new ZoomConstantExpression('source', expression.value): SourceExpression));\n }\n\n const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined;\n\n return success(isFeatureConstant ?\n (new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType): CameraExpression) :\n (new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType): CompositeExpression));\n}\n\nimport {isFunction, createFunction} from '../function';\nimport {Color} from './values';\n\n// serialization wrapper for old-style stop functions normalized to the\n// expression interface\nexport class StylePropertyFunction {\n _parameters: PropertyValueSpecification;\n _specification: StylePropertySpecification;\n\n kind: EvaluationKind;\n evaluate: (globals: GlobalProperties, feature?: Feature) => any;\n interpolationFactor: ?(input: number, lower: number, upper: number) => number;\n zoomStops: ?Array;\n\n constructor(parameters: PropertyValueSpecification, specification: StylePropertySpecification) {\n this._parameters = parameters;\n this._specification = specification;\n extend(this, createFunction(this._parameters, this._specification));\n }\n\n static deserialize(serialized: {_parameters: PropertyValueSpecification, _specification: StylePropertySpecification}) {\n return ((new StylePropertyFunction(serialized._parameters, serialized._specification)): StylePropertyFunction);\n }\n\n static serialize(input: StylePropertyFunction) {\n return {\n _parameters: input._parameters,\n _specification: input._specification\n };\n }\n}\n\nexport function normalizePropertyExpression(value: PropertyValueSpecification, specification: StylePropertySpecification): StylePropertyExpression {\n if (isFunction(value)) {\n return (new StylePropertyFunction(value, specification): any);\n\n } else if (isExpression(value)) {\n const expression = createPropertyExpression(value, specification);\n if (expression.result === 'error') {\n // this should have been caught in validation\n throw new Error(expression.value.map(err => `${err.key}: ${err.message}`).join(', '));\n }\n return expression.value;\n\n } else {\n let constant: any = value;\n if (typeof value === 'string' && specification.type === 'color') {\n constant = Color.parse(value);\n }\n return {\n kind: 'constant',\n evaluate: () => constant\n };\n }\n}\n\n// Zoom-dependent expressions may only use [\"zoom\"] as the input to a top-level \"step\" or \"interpolate\"\n// expression (collectively referred to as a \"curve\"). The curve may be wrapped in one or more \"let\" or\n// \"coalesce\" expressions.\nfunction findZoomCurve(expression: Expression): Step | Interpolate | ParsingError | null {\n let result = null;\n if (expression instanceof Let) {\n result = findZoomCurve(expression.result);\n\n } else if (expression instanceof Coalesce) {\n for (const arg of expression.args) {\n result = findZoomCurve(arg);\n if (result) {\n break;\n }\n }\n\n } else if ((expression instanceof Step || expression instanceof Interpolate) &&\n expression.input instanceof CompoundExpression &&\n expression.input.name === 'zoom') {\n\n result = expression;\n }\n\n if (result instanceof ParsingError) {\n return result;\n }\n\n expression.eachChild((child) => {\n const childResult = findZoomCurve(child);\n if (childResult instanceof ParsingError) {\n result = childResult;\n } else if (!result && childResult) {\n result = new ParsingError('', '\"zoom\" expression may only be used as input to a top-level \"step\" or \"interpolate\" expression.');\n } else if (result && childResult && result !== childResult) {\n result = new ParsingError('', 'Only one zoom-based \"step\" or \"interpolate\" subexpression may be used in an expression.');\n }\n });\n\n return result;\n}\n\nimport {ColorType, StringType, NumberType, BooleanType, ValueType, FormattedType, ResolvedImageType, array} from './types';\n\nfunction getExpectedType(spec: StylePropertySpecification): Type {\n const types = {\n color: ColorType,\n string: StringType,\n number: NumberType,\n enum: StringType,\n boolean: BooleanType,\n formatted: FormattedType,\n resolvedImage: ResolvedImageType\n };\n\n if (spec.type === 'array') {\n return array(types[spec.value] || ValueType, spec.length);\n }\n\n return types[spec.type];\n}\n\nfunction getDefaultValue(spec: StylePropertySpecification): Value {\n if (spec.type === 'color' && isFunction(spec.default)) {\n // Special case for heatmap-color: it uses the 'default:' to define a\n // default color ramp, but createExpression expects a simple value to fall\n // back to in case of runtime errors\n return new Color(0, 0, 0, 0);\n } else if (spec.type === 'color') {\n return Color.parse(spec.default) || null;\n } else if (spec.default === undefined) {\n return null;\n } else {\n return spec.default;\n }\n}\n","// @flow\n\nimport assert from 'assert';\nimport type {StylePropertySpecification} from '../style-spec';\n\nexport default convertFunction;\n\nfunction convertLiteral(value) {\n return typeof value === 'object' ? ['literal', value] : value;\n}\n\nfunction convertFunction(parameters: any, propertySpec: StylePropertySpecification) {\n let stops = parameters.stops;\n if (!stops) {\n // identity function\n return convertIdentityFunction(parameters, propertySpec);\n }\n\n const zoomAndFeatureDependent = stops && typeof stops[0][0] === 'object';\n const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined;\n const zoomDependent = zoomAndFeatureDependent || !featureDependent;\n\n stops = stops.map((stop) => {\n if (!featureDependent && propertySpec.tokens && typeof stop[1] === 'string') {\n return [stop[0], convertTokenString(stop[1])];\n }\n return [stop[0], convertLiteral(stop[1])];\n });\n\n if (zoomAndFeatureDependent) {\n return convertZoomAndPropertyFunction(parameters, propertySpec, stops);\n } else if (zoomDependent) {\n return convertZoomFunction(parameters, propertySpec, stops);\n } else {\n return convertPropertyFunction(parameters, propertySpec, stops);\n }\n}\n\nfunction convertIdentityFunction(parameters, propertySpec): Array {\n const get = ['get', parameters.property];\n\n if (parameters.default === undefined) {\n // By default, expressions for string-valued properties get coerced. To preserve\n // legacy function semantics, insert an explicit assertion instead.\n return propertySpec.type === 'string' ? ['string', get] : get;\n } else if (propertySpec.type === 'enum') {\n return [\n 'match',\n get,\n Object.keys(propertySpec.values),\n get,\n parameters.default\n ];\n } else {\n const expression = [propertySpec.type === 'color' ? 'to-color' : propertySpec.type, get, convertLiteral(parameters.default)];\n if (propertySpec.type === 'array') {\n expression.splice(1, 0, propertySpec.value, propertySpec.length || null);\n }\n return expression;\n }\n}\n\nfunction getInterpolateOperator(parameters) {\n switch (parameters.colorSpace) {\n case 'hcl': return 'interpolate-hcl';\n case 'lab': return 'interpolate-lab';\n default: return 'interpolate';\n }\n}\n\nfunction convertZoomAndPropertyFunction(parameters, propertySpec, stops) {\n const featureFunctionParameters = {};\n const featureFunctionStops = {};\n const zoomStops = [];\n for (let s = 0; s < stops.length; s++) {\n const stop = stops[s];\n const zoom = stop[0].zoom;\n if (featureFunctionParameters[zoom] === undefined) {\n featureFunctionParameters[zoom] = {\n zoom,\n type: parameters.type,\n property: parameters.property,\n default: parameters.default,\n };\n featureFunctionStops[zoom] = [];\n zoomStops.push(zoom);\n }\n featureFunctionStops[zoom].push([stop[0].value, stop[1]]);\n }\n\n // the interpolation type for the zoom dimension of a zoom-and-property\n // function is determined directly from the style property specification\n // for which it's being used: linear for interpolatable properties, step\n // otherwise.\n const functionType = getFunctionType({}, propertySpec);\n if (functionType === 'exponential') {\n const expression = [getInterpolateOperator(parameters), ['linear'], ['zoom']];\n\n for (const z of zoomStops) {\n const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]);\n appendStopPair(expression, z, output, false);\n }\n\n return expression;\n } else {\n const expression = ['step', ['zoom']];\n\n for (const z of zoomStops) {\n const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]);\n appendStopPair(expression, z, output, true);\n }\n\n fixupDegenerateStepCurve(expression);\n\n return expression;\n }\n}\n\nfunction coalesce(a, b) {\n if (a !== undefined) return a;\n if (b !== undefined) return b;\n}\n\nfunction getFallback(parameters, propertySpec) {\n const defaultValue = convertLiteral(coalesce(parameters.default, propertySpec.default));\n\n /*\n * Some fields with type: resolvedImage have an undefined default.\n * Because undefined is an invalid value for resolvedImage, set fallback to\n * an empty string instead of undefined to ensure output\n * passes validation.\n */\n if (defaultValue === undefined && propertySpec.type === 'resolvedImage') {\n return '';\n }\n return defaultValue;\n}\n\nfunction convertPropertyFunction(parameters, propertySpec, stops) {\n const type = getFunctionType(parameters, propertySpec);\n const get = ['get', parameters.property];\n if (type === 'categorical' && typeof stops[0][0] === 'boolean') {\n assert(parameters.stops.length > 0 && parameters.stops.length <= 2);\n const expression = ['case'];\n for (const stop of stops) {\n expression.push(['==', get, stop[0]], stop[1]);\n }\n\n expression.push(getFallback(parameters, propertySpec));\n return expression;\n } else if (type === 'categorical') {\n const expression = ['match', get];\n for (const stop of stops) {\n appendStopPair(expression, stop[0], stop[1], false);\n }\n expression.push(getFallback(parameters, propertySpec));\n return expression;\n } else if (type === 'interval') {\n const expression = ['step', ['number', get]];\n for (const stop of stops) {\n appendStopPair(expression, stop[0], stop[1], true);\n }\n fixupDegenerateStepCurve(expression);\n return parameters.default === undefined ? expression : [\n 'case',\n ['==', ['typeof', get], 'number'],\n expression,\n convertLiteral(parameters.default)\n ];\n } else if (type === 'exponential') {\n const base = parameters.base !== undefined ? parameters.base : 1;\n const expression = [\n getInterpolateOperator(parameters),\n base === 1 ? [\"linear\"] : [\"exponential\", base],\n [\"number\", get]\n ];\n\n for (const stop of stops) {\n appendStopPair(expression, stop[0], stop[1], false);\n }\n return parameters.default === undefined ? expression : [\n 'case',\n ['==', ['typeof', get], 'number'],\n expression,\n convertLiteral(parameters.default)\n ];\n } else {\n throw new Error(`Unknown property function type ${type}`);\n }\n}\n\nfunction convertZoomFunction(parameters, propertySpec, stops, input = ['zoom']) {\n const type = getFunctionType(parameters, propertySpec);\n let expression;\n let isStep = false;\n if (type === 'interval') {\n expression = ['step', input];\n isStep = true;\n } else if (type === 'exponential') {\n const base = parameters.base !== undefined ? parameters.base : 1;\n expression = [getInterpolateOperator(parameters), base === 1 ? [\"linear\"] : [\"exponential\", base], input];\n\n } else {\n throw new Error(`Unknown zoom function type \"${type}\"`);\n }\n\n for (const stop of stops) {\n appendStopPair(expression, stop[0], stop[1], isStep);\n }\n\n fixupDegenerateStepCurve(expression);\n\n return expression;\n}\n\nfunction fixupDegenerateStepCurve(expression) {\n // degenerate step curve (i.e. a constant function): add a noop stop\n if (expression[0] === 'step' && expression.length === 3) {\n expression.push(0);\n expression.push(expression[3]);\n }\n}\n\nfunction appendStopPair(curve, input, output, isStep) {\n // Skip duplicate stop values. They were not validated for functions, but they are for expressions.\n // https://github.com/mapbox/mapbox-gl-js/issues/4107\n if (curve.length > 3 && input === curve[curve.length - 2]) {\n return;\n }\n // step curves don't get the first input value, as it is redundant.\n if (!(isStep && curve.length === 2)) {\n curve.push(input);\n }\n curve.push(output);\n}\n\nfunction getFunctionType(parameters, propertySpec) {\n if (parameters.type) {\n return parameters.type;\n } else {\n assert(propertySpec.expression);\n return (propertySpec.expression: any).interpolated ? 'exponential' : 'interval';\n }\n}\n\n// \"String with {name} token\" => [\"concat\", \"String with \", [\"get\", \"name\"], \" token\"]\nexport function convertTokenString(s: string) {\n const result = ['concat'];\n const re = /{([^{}]+)}/g;\n let pos = 0;\n for (let match = re.exec(s); match !== null; match = re.exec(s)) {\n const literal = s.slice(pos, re.lastIndex - match[0].length);\n pos = re.lastIndex;\n if (literal.length > 0) result.push(literal);\n result.push(['get', match[1]]);\n }\n\n if (result.length === 1) {\n return s;\n }\n\n if (pos < s.length) {\n result.push(s.slice(pos));\n } else if (result.length === 2) {\n return ['to-string', result[1]];\n }\n\n return result;\n}\n\n","// @flow\n\nimport {createExpression} from '../expression';\nimport type {GlobalProperties, Feature} from '../expression';\nimport type {CanonicalTileID} from '../../source/tile_id';\n\ntype FilterExpression = (globalProperties: GlobalProperties, feature: Feature, canonical?: CanonicalTileID) => boolean;\nexport type FeatureFilter ={filter: FilterExpression, needGeometry: boolean};\n\nexport default createFilter;\nexport {isExpressionFilter};\n\nfunction isExpressionFilter(filter: any) {\n if (filter === true || filter === false) {\n return true;\n }\n\n if (!Array.isArray(filter) || filter.length === 0) {\n return false;\n }\n switch (filter[0]) {\n case 'has':\n return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type';\n\n case 'in':\n return filter.length >= 3 && (typeof filter[1] !== 'string' || Array.isArray(filter[2]));\n\n case '!in':\n case '!has':\n case 'none':\n return false;\n\n case '==':\n case '!=':\n case '>':\n case '>=':\n case '<':\n case '<=':\n return filter.length !== 3 || (Array.isArray(filter[1]) || Array.isArray(filter[2]));\n\n case 'any':\n case 'all':\n for (const f of filter.slice(1)) {\n if (!isExpressionFilter(f) && typeof f !== 'boolean') {\n return false;\n }\n }\n return true;\n\n default:\n return true;\n }\n}\n\nconst filterSpec = {\n 'type': 'boolean',\n 'default': false,\n 'transition': false,\n 'property-type': 'data-driven',\n 'expression': {\n 'interpolated': false,\n 'parameters': ['zoom', 'feature']\n }\n};\n\n/**\n * Given a filter expressed as nested arrays, return a new function\n * that evaluates whether a given feature (with a .properties or .tags property)\n * passes its test.\n *\n * @private\n * @param {Array} filter mapbox gl filter\n * @returns {Function} filter-evaluating function\n */\nfunction createFilter(filter: any): FeatureFilter {\n if (filter === null || filter === undefined) {\n return {filter: () => true, needGeometry: false};\n }\n\n if (!isExpressionFilter(filter)) {\n filter = convertFilter(filter);\n }\n\n const compiled = createExpression(filter, filterSpec);\n if (compiled.result === 'error') {\n throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', '));\n } else {\n const needGeometry = geometryNeeded(filter);\n return {filter: (globalProperties: GlobalProperties, feature: Feature, canonical?: CanonicalTileID) => compiled.value.evaluate(globalProperties, feature, {}, canonical),\n needGeometry};\n }\n}\n\n// Comparison function to sort numbers and strings\nfunction compare(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction geometryNeeded(filter) {\n if (!Array.isArray(filter)) return false;\n if (filter[0] === 'within') return true;\n for (let index = 1; index < filter.length; index++) {\n if (geometryNeeded(filter[index])) return true;\n }\n return false;\n}\n\nfunction convertFilter(filter: ?Array): mixed {\n if (!filter) return true;\n const op = filter[0];\n if (filter.length <= 1) return (op !== 'any');\n const converted =\n op === '==' ? convertComparisonOp(filter[1], filter[2], '==') :\n op === '!=' ? convertNegation(convertComparisonOp(filter[1], filter[2], '==')) :\n op === '<' ||\n op === '>' ||\n op === '<=' ||\n op === '>=' ? convertComparisonOp(filter[1], filter[2], op) :\n op === 'any' ? convertDisjunctionOp(filter.slice(1)) :\n op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter)) :\n op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter).map(convertNegation)) :\n op === 'in' ? convertInOp(filter[1], filter.slice(2)) :\n op === '!in' ? convertNegation(convertInOp(filter[1], filter.slice(2))) :\n op === 'has' ? convertHasOp(filter[1]) :\n op === '!has' ? convertNegation(convertHasOp(filter[1])) :\n op === 'within' ? filter :\n true;\n return converted;\n}\n\nfunction convertComparisonOp(property: string, value: any, op: string) {\n switch (property) {\n case '$type':\n return [`filter-type-${op}`, value];\n case '$id':\n return [`filter-id-${op}`, value];\n default:\n return [`filter-${op}`, property, value];\n }\n}\n\nfunction convertDisjunctionOp(filters: Array>) {\n return ['any'].concat(filters.map(convertFilter));\n}\n\nfunction convertInOp(property: string, values: Array) {\n if (values.length === 0) { return false; }\n switch (property) {\n case '$type':\n return [`filter-type-in`, ['literal', values]];\n case '$id':\n return [`filter-id-in`, ['literal', values]];\n default:\n if (values.length > 200 && !values.some(v => typeof v !== typeof values[0])) {\n return ['filter-in-large', property, ['literal', values.sort(compare)]];\n } else {\n return ['filter-in-small', property, ['literal', values]];\n }\n }\n}\n\nfunction convertHasOp(property: string) {\n switch (property) {\n case '$type':\n return true;\n case '$id':\n return [`filter-has-id`];\n default:\n return [`filter-has`, property];\n }\n}\n\nfunction convertNegation(filter: mixed) {\n return ['!', filter];\n}\n","// @flow\n\nimport {isExpressionFilter} from './index';\n\nimport type {FilterSpecification} from '../types';\n\ntype ExpectedTypes = {[_: string]: 'string' | 'number' | 'boolean'};\n\n/**\n * Convert the given legacy filter to (the JSON representation of) an\n * equivalent expression\n * @private\n */\nexport default function convertFilter(filter: FilterSpecification): mixed {\n return _convertFilter(filter, {});\n}\n\n/*\n * Convert the given filter to an expression, storing the expected types for\n * any feature properties referenced in expectedTypes.\n *\n * These expected types are needed in order to construct preflight type checks\n * needed for handling 'any' filters. A preflight type check is necessary in\n * order to mimic legacy filters' semantics around expected type mismatches.\n * For example, consider the legacy filter:\n *\n * [\"any\", [\"all\", [\">\", \"y\", 0], [\">\", \"y\", 0]], [\">\", \"x\", 0]]\n *\n * Naively, we might convert this to the expression:\n *\n * [\"any\", [\"all\", [\">\", [\"get\", \"y\"], 0], [\">\", [\"get\", \"z\"], 0]], [\">\", [\"get\", \"x\"], 0]]\n *\n * But if we tried to evaluate this against, say `{x: 1, y: null, z: 0}`, the\n * [\">\", [\"get\", \"y\"], 0] would cause an evaluation error, leading to the\n * entire filter returning false. Legacy filter semantics, though, ask for\n * [\">\", \"y\", 0] to simply return `false` when `y` is of the wrong type,\n * allowing the subsequent terms of the outer \"any\" expression to be evaluated\n * (resulting, in this case, in a `true` value, because x > 0).\n *\n * We account for this by inserting a preflight type-checking expression before\n * each \"any\" term, allowing us to avoid evaluating the actual converted filter\n * if any type mismatches would cause it to produce an evalaution error:\n *\n * [\"any\",\n * [\"case\",\n * [\"all\", [\"==\", [\"typeof\", [\"get\", \"y\"]], \"number\"], [\"==\", [\"typeof\", [\"get\", \"z\"], \"number]],\n * [\"all\", [\">\", [\"get\", \"y\"], 0], [\">\", [\"get\", \"z\"], 0]],\n * false\n * ],\n * [\"case\",\n * [\"==\", [\"typeof\", [\"get\", \"x\"], \"number\"]],\n * [\">\", [\"get\", \"x\"], 0],\n * false\n * ]\n * ]\n *\n * An alternative, possibly more direct approach would be to use type checks\n * in the conversion of each comparison operator, so that the converted version\n * of each individual ==, >=, etc. would mimic the legacy filter semantics. The\n * downside of this approach is that it can lead to many more type checks than\n * would otherwise be necessary: outside the context of an \"any\" expression,\n * bailing out due to a runtime type error (expression semantics) and returning\n * false (legacy filter semantics) are equivalent: they cause the filter to\n * produce a `false` result.\n */\nfunction _convertFilter(filter: FilterSpecification, expectedTypes: ExpectedTypes): mixed {\n if (isExpressionFilter(filter)) { return filter; }\n\n if (!filter) return true;\n const op = filter[0];\n if (filter.length <= 1) return (op !== 'any');\n\n let converted;\n\n if (\n op === '==' ||\n op === '!=' ||\n op === '<' ||\n op === '>' ||\n op === '<=' ||\n op === '>='\n ) {\n const [, property, value] = (filter: any);\n converted = convertComparisonOp(property, value, op, expectedTypes);\n } else if (op === 'any') {\n const children = (filter: any).slice(1).map(f => {\n const types = {};\n const child = _convertFilter(f, types);\n const typechecks = runtimeTypeChecks(types);\n return typechecks === true ? child : ['case', typechecks, child, false];\n });\n return ['any'].concat(children);\n } else if (op === 'all') {\n const children = (filter: any).slice(1).map(f => _convertFilter(f, expectedTypes));\n return children.length > 1 ? ['all'].concat(children) : [].concat(...children);\n } else if (op === 'none') {\n return ['!', _convertFilter(['any'].concat(filter.slice(1)), {})];\n } else if (op === 'in') {\n converted = convertInOp((filter[1]: any), filter.slice(2));\n } else if (op === '!in') {\n converted = convertInOp((filter[1]: any), filter.slice(2), true);\n } else if (op === 'has') {\n converted = convertHasOp((filter[1]: any));\n } else if (op === '!has') {\n converted = ['!', convertHasOp((filter[1]: any))];\n } else {\n converted = true;\n }\n\n return converted;\n}\n\n// Given a set of feature properties and an expected type for each one,\n// construct an boolean expression that tests whether each property has the\n// right type.\n// E.g.: for {name: 'string', population: 'number'}, return\n// [ 'all',\n// ['==', ['typeof', ['get', 'name'], 'string']],\n// ['==', ['typeof', ['get', 'population'], 'number]]\n// ]\nfunction runtimeTypeChecks(expectedTypes: ExpectedTypes) {\n const conditions = [];\n for (const property in expectedTypes) {\n const get = property === '$id' ? ['id'] : ['get', property];\n conditions.push(['==', ['typeof', get], expectedTypes[property]]);\n }\n if (conditions.length === 0) return true;\n if (conditions.length === 1) return conditions[0];\n return ['all'].concat(conditions);\n}\n\nfunction convertComparisonOp(property: string, value: any, op: string, expectedTypes: ?ExpectedTypes) {\n let get;\n if (property === '$type') {\n return [op, ['geometry-type'], value];\n } else if (property === '$id') {\n get = ['id'];\n } else {\n get = ['get', property];\n }\n\n if (expectedTypes && value !== null) {\n const type = ((typeof value): any);\n expectedTypes[property] = type;\n }\n\n if (op === '==' && property !== '$id' && value === null) {\n return [\n 'all',\n ['has', property], // missing property != null for legacy filters\n ['==', get, null]\n ];\n } else if (op === '!=' && property !== '$id' && value === null) {\n return [\n 'any',\n ['!', ['has', property]], // missing property != null for legacy filters\n ['!=', get, null]\n ];\n }\n\n return [op, get, value];\n}\n\nfunction convertInOp(property: string, values: Array, negate = false) {\n if (values.length === 0) return negate;\n\n let get;\n if (property === '$type') {\n get = ['geometry-type'];\n } else if (property === '$id') {\n get = ['id'];\n } else {\n get = ['get', property];\n }\n\n // Determine if the list of values to be searched is homogenously typed.\n // If so (and if the type is string or number), then we can use a\n // [match, input, [...values], true, false] construction rather than a\n // bunch of `==` tests.\n let uniformTypes = true;\n const type = typeof values[0];\n for (const value of values) {\n if (typeof value !== type) {\n uniformTypes = false;\n break;\n }\n }\n\n if (uniformTypes && (type === 'string' || type === 'number')) {\n // Match expressions must have unique values.\n const uniqueValues = values.sort().filter((v, i) => i === 0 || values[i - 1] !== v);\n return ['match', get, uniqueValues, !negate, negate];\n }\n\n return [ negate ? 'all' : 'any' ].concat(\n values.map(v => [negate ? '!=' : '==', get, v])\n );\n}\n\nfunction convertHasOp(property: string) {\n if (property === '$type') {\n return true;\n } else if (property === '$id') {\n return ['!=', ['id'], null];\n } else {\n return ['has', property];\n }\n}\n","// @flow\n\nimport {\n eachLayer,\n eachProperty\n} from '../visit';\nimport {isExpression} from '../expression';\nimport convertFunction, {convertTokenString} from '../function/convert';\nimport convertFilter from '../feature_filter/convert';\n\nimport type {StyleSpecification} from '../types';\n\n/**\n * Migrate the given style object in place to use expressions. Specifically,\n * this will convert (a) \"stop\" functions, and (b) legacy filters to their\n * expression equivalents.\n */\nexport default function(style: StyleSpecification) {\n const converted = [];\n\n eachLayer(style, (layer) => {\n if (layer.filter) {\n layer.filter = (convertFilter(layer.filter): any);\n }\n });\n\n eachProperty(style, {paint: true, layout: true}, ({path, value, reference, set}) => {\n if (isExpression(value)) return;\n if (typeof value === 'object' && !Array.isArray(value)) {\n set(convertFunction(value, reference));\n converted.push(path.join('.'));\n } else if (reference.tokens && typeof value === 'string') {\n set(convertTokenString(value));\n }\n });\n\n return style;\n}\n\n","\nimport migrateToV8 from './migrate/v8';\nimport migrateToExpressions from './migrate/expressions';\n\n/**\n * Migrate a Mapbox GL Style to the latest version.\n *\n * @private\n * @alias migrate\n * @param {object} style a Mapbox GL Style\n * @returns {Object} a migrated style\n * @example\n * var fs = require('fs');\n * var migrate = require('mapbox-gl-style-spec').migrate;\n * var style = fs.readFileSync('./style.json', 'utf8');\n * fs.writeFileSync('./style.json', JSON.stringify(migrate(style)));\n */\nexport default function(style) {\n let migrated = false;\n\n if (style.version === 7) {\n style = migrateToV8(style);\n migrated = true;\n }\n\n if (style.version === 8) {\n migrated = migrateToExpressions(style);\n migrated = true;\n }\n\n if (!migrated) {\n throw new Error('cannot migrate from', style.version);\n }\n\n return style;\n}\n","\nexport default function (style) {\n const styleIDs = [];\n const sourceIDs = [];\n const compositedSourceLayers = [];\n\n for (const id in style.sources) {\n const source = style.sources[id];\n\n if (source.type !== \"vector\")\n continue;\n\n const match = /^mapbox:\\/\\/(.*)/.exec(source.url);\n if (!match)\n continue;\n\n styleIDs.push(id);\n sourceIDs.push(match[1]);\n }\n\n if (styleIDs.length < 2)\n return style;\n\n styleIDs.forEach((id) => {\n delete style.sources[id];\n });\n\n const compositeID = sourceIDs.join(\",\");\n\n style.sources[compositeID] = {\n \"type\": \"vector\",\n \"url\": `mapbox://${compositeID}`\n };\n\n style.layers.forEach((layer) => {\n if (styleIDs.indexOf(layer.source) >= 0) {\n layer.source = compositeID;\n\n if ('source-layer' in layer) {\n if (compositedSourceLayers.indexOf(layer['source-layer']) >= 0) {\n throw new Error('Conflicting source layer names');\n } else {\n compositedSourceLayers.push(layer['source-layer']);\n }\n }\n }\n });\n\n return style;\n}\n","\nexport default ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout'];\n","\nimport refProperties from './util/ref_properties';\n\nfunction deref(layer, parent) {\n const result = {};\n\n for (const k in layer) {\n if (k !== 'ref') {\n result[k] = layer[k];\n }\n }\n\n refProperties.forEach((k) => {\n if (k in parent) {\n result[k] = parent[k];\n }\n });\n\n return result;\n}\n\nexport default derefLayers;\n\n/**\n * Given an array of layers, some of which may contain `ref` properties\n * whose value is the `id` of another property, return a new array where\n * such layers have been augmented with the 'type', 'source', etc. properties\n * from the parent layer, and the `ref` property has been removed.\n *\n * The input is not modified. The output may contain references to portions\n * of the input.\n *\n * @private\n * @param {Array} layers\n * @returns {Array}\n */\nfunction derefLayers(layers) {\n layers = layers.slice();\n\n const map = Object.create(null);\n for (let i = 0; i < layers.length; i++) {\n map[layers[i].id] = layers[i];\n }\n\n for (let i = 0; i < layers.length; i++) {\n if ('ref' in layers[i]) {\n layers[i] = deref(layers[i], map[layers[i].ref]);\n }\n }\n\n return layers;\n}\n","// @flow\n\n/**\n * Deeply compares two object literals.\n *\n * @private\n */\nfunction deepEqual(a: ?mixed, b: ?mixed): boolean {\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) return false;\n }\n return true;\n }\n if (typeof a === 'object' && a !== null && b !== null) {\n if (!(typeof b === 'object')) return false;\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n for (const key in a) {\n if (!deepEqual(a[key], b[key])) return false;\n }\n return true;\n }\n return a === b;\n}\n\nexport default deepEqual;\n","\nimport isEqual from './util/deep_equal';\n\nconst operations = {\n\n /*\n * { command: 'setStyle', args: [stylesheet] }\n */\n setStyle: 'setStyle',\n\n /*\n * { command: 'addLayer', args: [layer, 'beforeLayerId'] }\n */\n addLayer: 'addLayer',\n\n /*\n * { command: 'removeLayer', args: ['layerId'] }\n */\n removeLayer: 'removeLayer',\n\n /*\n * { command: 'setPaintProperty', args: ['layerId', 'prop', value] }\n */\n setPaintProperty: 'setPaintProperty',\n\n /*\n * { command: 'setLayoutProperty', args: ['layerId', 'prop', value] }\n */\n setLayoutProperty: 'setLayoutProperty',\n\n /*\n * { command: 'setFilter', args: ['layerId', filter] }\n */\n setFilter: 'setFilter',\n\n /*\n * { command: 'addSource', args: ['sourceId', source] }\n */\n addSource: 'addSource',\n\n /*\n * { command: 'removeSource', args: ['sourceId'] }\n */\n removeSource: 'removeSource',\n\n /*\n * { command: 'setGeoJSONSourceData', args: ['sourceId', data] }\n */\n setGeoJSONSourceData: 'setGeoJSONSourceData',\n\n /*\n * { command: 'setLayerZoomRange', args: ['layerId', 0, 22] }\n */\n setLayerZoomRange: 'setLayerZoomRange',\n\n /*\n * { command: 'setLayerProperty', args: ['layerId', 'prop', value] }\n */\n setLayerProperty: 'setLayerProperty',\n\n /*\n * { command: 'setCenter', args: [[lon, lat]] }\n */\n setCenter: 'setCenter',\n\n /*\n * { command: 'setZoom', args: [zoom] }\n */\n setZoom: 'setZoom',\n\n /*\n * { command: 'setBearing', args: [bearing] }\n */\n setBearing: 'setBearing',\n\n /*\n * { command: 'setPitch', args: [pitch] }\n */\n setPitch: 'setPitch',\n\n /*\n * { command: 'setSprite', args: ['spriteUrl'] }\n */\n setSprite: 'setSprite',\n\n /*\n * { command: 'setGlyphs', args: ['glyphsUrl'] }\n */\n setGlyphs: 'setGlyphs',\n\n /*\n * { command: 'setTransition', args: [transition] }\n */\n setTransition: 'setTransition',\n\n /*\n * { command: 'setLighting', args: [lightProperties] }\n */\n setLight: 'setLight'\n\n};\n\nfunction addSource(sourceId, after, commands) {\n commands.push({command: operations.addSource, args: [sourceId, after[sourceId]]});\n}\n\nfunction removeSource(sourceId, commands, sourcesRemoved) {\n commands.push({command: operations.removeSource, args: [sourceId]});\n sourcesRemoved[sourceId] = true;\n}\n\nfunction updateSource(sourceId, after, commands, sourcesRemoved) {\n removeSource(sourceId, commands, sourcesRemoved);\n addSource(sourceId, after, commands);\n}\n\nfunction canUpdateGeoJSON(before, after, sourceId) {\n let prop;\n for (prop in before[sourceId]) {\n if (!before[sourceId].hasOwnProperty(prop)) continue;\n if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) {\n return false;\n }\n }\n for (prop in after[sourceId]) {\n if (!after[sourceId].hasOwnProperty(prop)) continue;\n if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) {\n return false;\n }\n }\n return true;\n}\n\nfunction diffSources(before, after, commands, sourcesRemoved) {\n before = before || {};\n after = after || {};\n\n let sourceId;\n\n // look for sources to remove\n for (sourceId in before) {\n if (!before.hasOwnProperty(sourceId)) continue;\n if (!after.hasOwnProperty(sourceId)) {\n removeSource(sourceId, commands, sourcesRemoved);\n }\n }\n\n // look for sources to add/update\n for (sourceId in after) {\n if (!after.hasOwnProperty(sourceId)) continue;\n if (!before.hasOwnProperty(sourceId)) {\n addSource(sourceId, after, commands);\n } else if (!isEqual(before[sourceId], after[sourceId])) {\n if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) {\n commands.push({command: operations.setGeoJSONSourceData, args: [sourceId, after[sourceId].data]});\n } else {\n // no update command, must remove then add\n updateSource(sourceId, after, commands, sourcesRemoved);\n }\n }\n }\n}\n\nfunction diffLayerPropertyChanges(before, after, commands, layerId, klass, command) {\n before = before || {};\n after = after || {};\n\n let prop;\n\n for (prop in before) {\n if (!before.hasOwnProperty(prop)) continue;\n if (!isEqual(before[prop], after[prop])) {\n commands.push({command, args: [layerId, prop, after[prop], klass]});\n }\n }\n for (prop in after) {\n if (!after.hasOwnProperty(prop) || before.hasOwnProperty(prop)) continue;\n if (!isEqual(before[prop], after[prop])) {\n commands.push({command, args: [layerId, prop, after[prop], klass]});\n }\n }\n}\n\nfunction pluckId(layer) {\n return layer.id;\n}\nfunction indexById(group, layer) {\n group[layer.id] = layer;\n return group;\n}\n\nfunction diffLayers(before, after, commands) {\n before = before || [];\n after = after || [];\n\n // order of layers by id\n const beforeOrder = before.map(pluckId);\n const afterOrder = after.map(pluckId);\n\n // index of layer by id\n const beforeIndex = before.reduce(indexById, {});\n const afterIndex = after.reduce(indexById, {});\n\n // track order of layers as if they have been mutated\n const tracker = beforeOrder.slice();\n\n // layers that have been added do not need to be diffed\n const clean = Object.create(null);\n\n let i, d, layerId, beforeLayer, afterLayer, insertBeforeLayerId, prop;\n\n // remove layers\n for (i = 0, d = 0; i < beforeOrder.length; i++) {\n layerId = beforeOrder[i];\n if (!afterIndex.hasOwnProperty(layerId)) {\n commands.push({command: operations.removeLayer, args: [layerId]});\n tracker.splice(tracker.indexOf(layerId, d), 1);\n } else {\n // limit where in tracker we need to look for a match\n d++;\n }\n }\n\n // add/reorder layers\n for (i = 0, d = 0; i < afterOrder.length; i++) {\n // work backwards as insert is before an existing layer\n layerId = afterOrder[afterOrder.length - 1 - i];\n\n if (tracker[tracker.length - 1 - i] === layerId) continue;\n\n if (beforeIndex.hasOwnProperty(layerId)) {\n // remove the layer before we insert at the correct position\n commands.push({command: operations.removeLayer, args: [layerId]});\n tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1);\n } else {\n // limit where in tracker we need to look for a match\n d++;\n }\n\n // add layer at correct position\n insertBeforeLayerId = tracker[tracker.length - i];\n commands.push({command: operations.addLayer, args: [afterIndex[layerId], insertBeforeLayerId]});\n tracker.splice(tracker.length - i, 0, layerId);\n clean[layerId] = true;\n }\n\n // update layers\n for (i = 0; i < afterOrder.length; i++) {\n layerId = afterOrder[i];\n beforeLayer = beforeIndex[layerId];\n afterLayer = afterIndex[layerId];\n\n // no need to update if previously added (new or moved)\n if (clean[layerId] || isEqual(beforeLayer, afterLayer)) continue;\n\n // If source, source-layer, or type have changes, then remove the layer\n // and add it back 'from scratch'.\n if (!isEqual(beforeLayer.source, afterLayer.source) || !isEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !isEqual(beforeLayer.type, afterLayer.type)) {\n commands.push({command: operations.removeLayer, args: [layerId]});\n // we add the layer back at the same position it was already in, so\n // there's no need to update the `tracker`\n insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1];\n commands.push({command: operations.addLayer, args: [afterLayer, insertBeforeLayerId]});\n continue;\n }\n\n // layout, paint, filter, minzoom, maxzoom\n diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, operations.setLayoutProperty);\n diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, operations.setPaintProperty);\n if (!isEqual(beforeLayer.filter, afterLayer.filter)) {\n commands.push({command: operations.setFilter, args: [layerId, afterLayer.filter]});\n }\n if (!isEqual(beforeLayer.minzoom, afterLayer.minzoom) || !isEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) {\n commands.push({command: operations.setLayerZoomRange, args: [layerId, afterLayer.minzoom, afterLayer.maxzoom]});\n }\n\n // handle all other layer props, including paint.*\n for (prop in beforeLayer) {\n if (!beforeLayer.hasOwnProperty(prop)) continue;\n if (prop === 'layout' || prop === 'paint' || prop === 'filter' ||\n prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue;\n if (prop.indexOf('paint.') === 0) {\n diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);\n } else if (!isEqual(beforeLayer[prop], afterLayer[prop])) {\n commands.push({command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]]});\n }\n }\n for (prop in afterLayer) {\n if (!afterLayer.hasOwnProperty(prop) || beforeLayer.hasOwnProperty(prop)) continue;\n if (prop === 'layout' || prop === 'paint' || prop === 'filter' ||\n prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue;\n if (prop.indexOf('paint.') === 0) {\n diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);\n } else if (!isEqual(beforeLayer[prop], afterLayer[prop])) {\n commands.push({command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]]});\n }\n }\n }\n}\n\n/**\n * Diff two stylesheet\n *\n * Creates semanticly aware diffs that can easily be applied at runtime.\n * Operations produced by the diff closely resemble the mapbox-gl-js API. Any\n * error creating the diff will fall back to the 'setStyle' operation.\n *\n * Example diff:\n * [\n * { command: 'setConstant', args: ['@water', '#0000FF'] },\n * { command: 'setPaintProperty', args: ['background', 'background-color', 'black'] }\n * ]\n *\n * @private\n * @param {*} [before] stylesheet to compare from\n * @param {*} after stylesheet to compare to\n * @returns Array list of changes\n */\nfunction diffStyles(before, after) {\n if (!before) return [{command: operations.setStyle, args: [after]}];\n\n let commands = [];\n\n try {\n // Handle changes to top-level properties\n if (!isEqual(before.version, after.version)) {\n return [{command: operations.setStyle, args: [after]}];\n }\n if (!isEqual(before.center, after.center)) {\n commands.push({command: operations.setCenter, args: [after.center]});\n }\n if (!isEqual(before.zoom, after.zoom)) {\n commands.push({command: operations.setZoom, args: [after.zoom]});\n }\n if (!isEqual(before.bearing, after.bearing)) {\n commands.push({command: operations.setBearing, args: [after.bearing]});\n }\n if (!isEqual(before.pitch, after.pitch)) {\n commands.push({command: operations.setPitch, args: [after.pitch]});\n }\n if (!isEqual(before.sprite, after.sprite)) {\n commands.push({command: operations.setSprite, args: [after.sprite]});\n }\n if (!isEqual(before.glyphs, after.glyphs)) {\n commands.push({command: operations.setGlyphs, args: [after.glyphs]});\n }\n if (!isEqual(before.transition, after.transition)) {\n commands.push({command: operations.setTransition, args: [after.transition]});\n }\n if (!isEqual(before.light, after.light)) {\n commands.push({command: operations.setLight, args: [after.light]});\n }\n\n // Handle changes to `sources`\n // If a source is to be removed, we also--before the removeSource\n // command--need to remove all the style layers that depend on it.\n const sourcesRemoved = {};\n\n // First collect the {add,remove}Source commands\n const removeOrAddSourceCommands = [];\n diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved);\n\n // Push a removeLayer command for each style layer that depends on a\n // source that's being removed.\n // Also, exclude any such layers them from the input to `diffLayers`\n // below, so that diffLayers produces the appropriate `addLayers`\n // command\n const beforeLayers = [];\n if (before.layers) {\n before.layers.forEach((layer) => {\n if (sourcesRemoved[layer.source]) {\n commands.push({command: operations.removeLayer, args: [layer.id]});\n } else {\n beforeLayers.push(layer);\n }\n });\n }\n commands = commands.concat(removeOrAddSourceCommands);\n\n // Handle changes to `layers`\n diffLayers(beforeLayers, after.layers, commands);\n\n } catch (e) {\n // fall back to setStyle\n console.warn('Unable to compute style diff:', e);\n commands = [{command: operations.setStyle, args: [after]}];\n }\n\n return commands;\n}\n\nexport default diffStyles;\nexport {operations};\n","// @flow\n\n// Note: Do not inherit from Error. It breaks when transpiling to ES5.\n\nexport default class ValidationError {\n message: string;\n identifier: ?string;\n line: ?number;\n\n constructor(key: ?string, value: ?{ __line__: number }, message: string, identifier: ?string) {\n this.message = (key ? `${key}: ` : '') + message;\n if (identifier) this.identifier = identifier;\n\n if (value !== null && value !== undefined && value.__line__) {\n this.line = value.__line__;\n }\n }\n}\n","// @flow\n\n// Note: Do not inherit from Error. It breaks when transpiling to ES5.\n\nexport default class ParsingError {\n message: string;\n error: Error;\n line: number;\n\n constructor(error: Error) {\n this.error = error;\n this.message = error.message;\n const match = error.message.match(/line (\\d+)/);\n this.line = match ? parseInt(match[1], 10) : 0;\n }\n}\n","\nimport ValidationError from '../error/validation_error';\n\nexport default function validateConstants(options) {\n const key = options.key;\n const constants = options.value;\n\n if (constants) {\n return [new ValidationError(key, constants, 'constants have been deprecated as of v8')];\n } else {\n return [];\n }\n}\n","// @flow\n\n// Turn jsonlint-lines-primitives objects into primitive objects\nexport function unbundle(value: mixed) {\n if (value instanceof Number || value instanceof String || value instanceof Boolean) {\n return value.valueOf();\n } else {\n return value;\n }\n}\n\nexport function deepUnbundle(value: mixed): mixed {\n if (Array.isArray(value)) {\n return value.map(deepUnbundle);\n } else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) {\n const unbundledValue: { [key: string]: mixed } = {};\n for (const key in value) {\n unbundledValue[key] = deepUnbundle(value[key]);\n }\n return unbundledValue;\n }\n\n return unbundle(value);\n}\n","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport validateSpec from './validate';\n\nexport default function validateObject(options) {\n const key = options.key;\n const object = options.value;\n const elementSpecs = options.valueSpec || {};\n const elementValidators = options.objectElementValidators || {};\n const style = options.style;\n const styleSpec = options.styleSpec;\n let errors = [];\n\n const type = getType(object);\n if (type !== 'object') {\n return [new ValidationError(key, object, `object expected, ${type} found`)];\n }\n\n for (const objectKey in object) {\n const elementSpecKey = objectKey.split('.')[0]; // treat 'paint.*' as 'paint'\n const elementSpec = elementSpecs[elementSpecKey] || elementSpecs['*'];\n\n let validateElement;\n if (elementValidators[elementSpecKey]) {\n validateElement = elementValidators[elementSpecKey];\n } else if (elementSpecs[elementSpecKey]) {\n validateElement = validateSpec;\n } else if (elementValidators['*']) {\n validateElement = elementValidators['*'];\n } else if (elementSpecs['*']) {\n validateElement = validateSpec;\n } else {\n errors.push(new ValidationError(key, object[objectKey], `unknown property \"${objectKey}\"`));\n continue;\n }\n\n errors = errors.concat(validateElement({\n key: (key ? `${key}.` : key) + objectKey,\n value: object[objectKey],\n valueSpec: elementSpec,\n style,\n styleSpec,\n object,\n objectKey\n }, object));\n }\n\n for (const elementSpecKey in elementSpecs) {\n // Don't check `required` when there's a custom validator for that property.\n if (elementValidators[elementSpecKey]) {\n continue;\n }\n\n if (elementSpecs[elementSpecKey].required && elementSpecs[elementSpecKey]['default'] === undefined && object[elementSpecKey] === undefined) {\n errors.push(new ValidationError(key, object, `missing required property \"${elementSpecKey}\"`));\n }\n }\n\n return errors;\n}\n","\nimport getType from '../util/get_type';\nimport validate from './validate';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateArray(options) {\n const array = options.value;\n const arraySpec = options.valueSpec;\n const style = options.style;\n const styleSpec = options.styleSpec;\n const key = options.key;\n const validateArrayElement = options.arrayElementValidator || validate;\n\n if (getType(array) !== 'array') {\n return [new ValidationError(key, array, `array expected, ${getType(array)} found`)];\n }\n\n if (arraySpec.length && array.length !== arraySpec.length) {\n return [new ValidationError(key, array, `array length ${arraySpec.length} expected, length ${array.length} found`)];\n }\n\n if (arraySpec['min-length'] && array.length < arraySpec['min-length']) {\n return [new ValidationError(key, array, `array length at least ${arraySpec['min-length']} expected, length ${array.length} found`)];\n }\n\n let arrayElementSpec = {\n \"type\": arraySpec.value,\n \"values\": arraySpec.values\n };\n\n if (styleSpec.$version < 7) {\n arrayElementSpec.function = arraySpec.function;\n }\n\n if (getType(arraySpec.value) === 'object') {\n arrayElementSpec = arraySpec.value;\n }\n\n let errors = [];\n for (let i = 0; i < array.length; i++) {\n errors = errors.concat(validateArrayElement({\n array,\n arrayIndex: i,\n value: array[i],\n valueSpec: arrayElementSpec,\n style,\n styleSpec,\n key: `${key}[${i}]`\n }));\n }\n return errors;\n}\n","\nimport getType from '../util/get_type';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateNumber(options) {\n const key = options.key;\n const value = options.value;\n const valueSpec = options.valueSpec;\n let type = getType(value);\n\n // eslint-disable-next-line no-self-compare\n if (type === 'number' && value !== value) {\n type = 'NaN';\n }\n\n if (type !== 'number') {\n return [new ValidationError(key, value, `number expected, ${type} found`)];\n }\n\n if ('minimum' in valueSpec && value < valueSpec.minimum) {\n return [new ValidationError(key, value, `${value} is less than the minimum value ${valueSpec.minimum}`)];\n }\n\n if ('maximum' in valueSpec && value > valueSpec.maximum) {\n return [new ValidationError(key, value, `${value} is greater than the maximum value ${valueSpec.maximum}`)];\n }\n\n return [];\n}\n","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport validate from './validate';\nimport validateObject from './validate_object';\nimport validateArray from './validate_array';\nimport validateNumber from './validate_number';\nimport {isExpression} from '../expression';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint';\nimport {\n supportsPropertyExpression,\n supportsZoomExpression,\n supportsInterpolation\n} from '../util/properties';\n\nexport default function validateFunction(options) {\n const functionValueSpec = options.valueSpec;\n const functionType = unbundle(options.value.type);\n let stopKeyType;\n let stopDomainValues = {};\n let previousStopDomainValue;\n let previousStopDomainZoom;\n\n const isZoomFunction = functionType !== 'categorical' && options.value.property === undefined;\n const isPropertyFunction = !isZoomFunction;\n const isZoomAndPropertyFunction =\n getType(options.value.stops) === 'array' &&\n getType(options.value.stops[0]) === 'array' &&\n getType(options.value.stops[0][0]) === 'object';\n\n const errors = validateObject({\n key: options.key,\n value: options.value,\n valueSpec: options.styleSpec.function,\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {\n stops: validateFunctionStops,\n default: validateFunctionDefault\n }\n });\n\n if (functionType === 'identity' && isZoomFunction) {\n errors.push(new ValidationError(options.key, options.value, 'missing required property \"property\"'));\n }\n\n if (functionType !== 'identity' && !options.value.stops) {\n errors.push(new ValidationError(options.key, options.value, 'missing required property \"stops\"'));\n }\n\n if (functionType === 'exponential' && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) {\n errors.push(new ValidationError(options.key, options.value, 'exponential functions not supported'));\n }\n\n if (options.styleSpec.$version >= 8) {\n if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) {\n errors.push(new ValidationError(options.key, options.value, 'property functions not supported'));\n } else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) {\n errors.push(new ValidationError(options.key, options.value, 'zoom functions not supported'));\n }\n }\n\n if ((functionType === 'categorical' || isZoomAndPropertyFunction) && options.value.property === undefined) {\n errors.push(new ValidationError(options.key, options.value, '\"property\" property is required'));\n }\n\n return errors;\n\n function validateFunctionStops(options) {\n if (functionType === 'identity') {\n return [new ValidationError(options.key, options.value, 'identity function may not have a \"stops\" property')];\n }\n\n let errors = [];\n const value = options.value;\n\n errors = errors.concat(validateArray({\n key: options.key,\n value,\n valueSpec: options.valueSpec,\n style: options.style,\n styleSpec: options.styleSpec,\n arrayElementValidator: validateFunctionStop\n }));\n\n if (getType(value) === 'array' && value.length === 0) {\n errors.push(new ValidationError(options.key, value, 'array must have at least one stop'));\n }\n\n return errors;\n }\n\n function validateFunctionStop(options) {\n let errors = [];\n const value = options.value;\n const key = options.key;\n\n if (getType(value) !== 'array') {\n return [new ValidationError(key, value, `array expected, ${getType(value)} found`)];\n }\n\n if (value.length !== 2) {\n return [new ValidationError(key, value, `array length 2 expected, length ${value.length} found`)];\n }\n\n if (isZoomAndPropertyFunction) {\n if (getType(value[0]) !== 'object') {\n return [new ValidationError(key, value, `object expected, ${getType(value[0])} found`)];\n }\n if (value[0].zoom === undefined) {\n return [new ValidationError(key, value, 'object stop key must have zoom')];\n }\n if (value[0].value === undefined) {\n return [new ValidationError(key, value, 'object stop key must have value')];\n }\n if (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) {\n return [new ValidationError(key, value[0].zoom, 'stop zoom values must appear in ascending order')];\n }\n if (unbundle(value[0].zoom) !== previousStopDomainZoom) {\n previousStopDomainZoom = unbundle(value[0].zoom);\n previousStopDomainValue = undefined;\n stopDomainValues = {};\n }\n errors = errors.concat(validateObject({\n key: `${key}[0]`,\n value: value[0],\n valueSpec: {zoom: {}},\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {zoom: validateNumber, value: validateStopDomainValue}\n }));\n } else {\n errors = errors.concat(validateStopDomainValue({\n key: `${key}[0]`,\n value: value[0],\n valueSpec: {},\n style: options.style,\n styleSpec: options.styleSpec\n }, value));\n }\n\n if (isExpression(deepUnbundle(value[1]))) {\n return errors.concat([new ValidationError(`${key}[1]`, value[1], 'expressions are not allowed in function stops.')]);\n }\n\n return errors.concat(validate({\n key: `${key}[1]`,\n value: value[1],\n valueSpec: functionValueSpec,\n style: options.style,\n styleSpec: options.styleSpec\n }));\n }\n\n function validateStopDomainValue(options, stop) {\n const type = getType(options.value);\n const value = unbundle(options.value);\n\n const reportValue = options.value !== null ? options.value : stop;\n\n if (!stopKeyType) {\n stopKeyType = type;\n } else if (type !== stopKeyType) {\n return [new ValidationError(options.key, reportValue, `${type} stop domain type must match previous stop domain type ${stopKeyType}`)];\n }\n\n if (type !== 'number' && type !== 'string' && type !== 'boolean') {\n return [new ValidationError(options.key, reportValue, 'stop domain value must be a number, string, or boolean')];\n }\n\n if (type !== 'number' && functionType !== 'categorical') {\n let message = `number expected, ${type} found`;\n if (supportsPropertyExpression(functionValueSpec) && functionType === undefined) {\n message += '\\nIf you intended to use a categorical function, specify `\"type\": \"categorical\"`.';\n }\n return [new ValidationError(options.key, reportValue, message)];\n }\n\n if (functionType === 'categorical' && type === 'number' && (!isFinite(value) || Math.floor(value) !== value)) {\n return [new ValidationError(options.key, reportValue, `integer expected, found ${value}`)];\n }\n\n if (functionType !== 'categorical' && type === 'number' && previousStopDomainValue !== undefined && value < previousStopDomainValue) {\n return [new ValidationError(options.key, reportValue, 'stop domain values must appear in ascending order')];\n } else {\n previousStopDomainValue = value;\n }\n\n if (functionType === 'categorical' && value in stopDomainValues) {\n return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')];\n } else {\n stopDomainValues[value] = true;\n }\n\n return [];\n }\n\n function validateFunctionDefault(options) {\n return validate({\n key: options.key,\n value: options.value,\n valueSpec: functionValueSpec,\n style: options.style,\n styleSpec: options.styleSpec\n });\n }\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error';\n\nimport {createExpression, createPropertyExpression} from '../expression';\nimport {deepUnbundle} from '../util/unbundle_jsonlint';\nimport {isStateConstant, isGlobalPropertyConstant, isFeatureConstant} from '../expression/is_constant';\n\nexport default function validateExpression(options: any): Array {\n const expression = (options.expressionContext === 'property' ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec);\n if (expression.result === 'error') {\n return expression.value.map((error) => {\n return new ValidationError(`${options.key}${error.key}`, options.value, error.message);\n });\n }\n\n const expressionObj = (expression.value: any).expression || (expression.value: any)._styleExpression.expression;\n\n if (options.expressionContext === 'property' && (options.propertyKey === 'text-font') &&\n !expressionObj.outputDefined()) {\n return [new ValidationError(options.key, options.value, `Invalid data expression for \"${options.propertyKey}\". Output values must be contained as literals within the expression.`)];\n }\n\n if (options.expressionContext === 'property' && options.propertyType === 'layout' &&\n (!isStateConstant(expressionObj))) {\n return [new ValidationError(options.key, options.value, '\"feature-state\" data expressions are not supported with layout properties.')];\n }\n\n if (options.expressionContext === 'filter' && !isStateConstant(expressionObj)) {\n return [new ValidationError(options.key, options.value, '\"feature-state\" data expressions are not supported with filters.')];\n }\n\n if (options.expressionContext && options.expressionContext.indexOf('cluster') === 0) {\n if (!isGlobalPropertyConstant(expressionObj, ['zoom', 'feature-state'])) {\n return [new ValidationError(options.key, options.value, '\"zoom\" and \"feature-state\" expressions are not supported with cluster properties.')];\n }\n if (options.expressionContext === 'cluster-initial' && !isFeatureConstant(expressionObj)) {\n return [new ValidationError(options.key, options.value, 'Feature data expressions are not supported with initial expression part of cluster properties.')];\n }\n }\n\n return [];\n}\n","\nimport getType from '../util/get_type';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateBoolean(options) {\n const value = options.value;\n const key = options.key;\n const type = getType(value);\n\n if (type !== 'boolean') {\n return [new ValidationError(key, value, `boolean expected, ${type} found`)];\n }\n\n return [];\n}\n","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport {parseCSSColor} from 'csscolorparser';\n\nexport default function validateColor(options) {\n const key = options.key;\n const value = options.value;\n const type = getType(value);\n\n if (type !== 'string') {\n return [new ValidationError(key, value, `color expected, ${type} found`)];\n }\n\n if (parseCSSColor(value) === null) {\n return [new ValidationError(key, value, `color expected, \"${value}\" found`)];\n }\n\n return [];\n}\n","\nimport ValidationError from '../error/validation_error';\nimport {unbundle} from '../util/unbundle_jsonlint';\n\nexport default function validateEnum(options) {\n const key = options.key;\n const value = options.value;\n const valueSpec = options.valueSpec;\n const errors = [];\n\n if (Array.isArray(valueSpec.values)) { // <=v7\n if (valueSpec.values.indexOf(unbundle(value)) === -1) {\n errors.push(new ValidationError(key, value, `expected one of [${valueSpec.values.join(', ')}], ${JSON.stringify(value)} found`));\n }\n } else { // >=v8\n if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) {\n errors.push(new ValidationError(key, value, `expected one of [${Object.keys(valueSpec.values).join(', ')}], ${JSON.stringify(value)} found`));\n }\n }\n return errors;\n}\n","\nimport ValidationError from '../error/validation_error';\nimport validateExpression from './validate_expression';\nimport validateEnum from './validate_enum';\nimport getType from '../util/get_type';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint';\nimport extend from '../util/extend';\nimport {isExpressionFilter} from '../feature_filter';\n\nexport default function validateFilter(options) {\n if (isExpressionFilter(deepUnbundle(options.value))) {\n return validateExpression(extend({}, options, {\n expressionContext: 'filter',\n valueSpec: {value: 'boolean'}\n }));\n } else {\n return validateNonExpressionFilter(options);\n }\n}\n\nfunction validateNonExpressionFilter(options) {\n const value = options.value;\n const key = options.key;\n\n if (getType(value) !== 'array') {\n return [new ValidationError(key, value, `array expected, ${getType(value)} found`)];\n }\n\n const styleSpec = options.styleSpec;\n let type;\n\n let errors = [];\n\n if (value.length < 1) {\n return [new ValidationError(key, value, 'filter array must have at least 1 element')];\n }\n\n errors = errors.concat(validateEnum({\n key: `${key}[0]`,\n value: value[0],\n valueSpec: styleSpec.filter_operator,\n style: options.style,\n styleSpec: options.styleSpec\n }));\n\n switch (unbundle(value[0])) {\n case '<':\n case '<=':\n case '>':\n case '>=':\n if (value.length >= 2 && unbundle(value[1]) === '$type') {\n errors.push(new ValidationError(key, value, `\"$type\" cannot be use with operator \"${value[0]}\"`));\n }\n /* falls through */\n case '==':\n case '!=':\n if (value.length !== 3) {\n errors.push(new ValidationError(key, value, `filter array for operator \"${value[0]}\" must have 3 elements`));\n }\n /* falls through */\n case 'in':\n case '!in':\n if (value.length >= 2) {\n type = getType(value[1]);\n if (type !== 'string') {\n errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`));\n }\n }\n for (let i = 2; i < value.length; i++) {\n type = getType(value[i]);\n if (unbundle(value[1]) === '$type') {\n errors = errors.concat(validateEnum({\n key: `${key}[${i}]`,\n value: value[i],\n valueSpec: styleSpec.geometry_type,\n style: options.style,\n styleSpec: options.styleSpec\n }));\n } else if (type !== 'string' && type !== 'number' && type !== 'boolean') {\n errors.push(new ValidationError(`${key}[${i}]`, value[i], `string, number, or boolean expected, ${type} found`));\n }\n }\n break;\n\n case 'any':\n case 'all':\n case 'none':\n for (let i = 1; i < value.length; i++) {\n errors = errors.concat(validateNonExpressionFilter({\n key: `${key}[${i}]`,\n value: value[i],\n style: options.style,\n styleSpec: options.styleSpec\n }));\n }\n break;\n\n case 'has':\n case '!has':\n type = getType(value[1]);\n if (value.length !== 2) {\n errors.push(new ValidationError(key, value, `filter array for \"${value[0]}\" operator must have 2 elements`));\n } else if (type !== 'string') {\n errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`));\n }\n break;\n case 'within':\n type = getType(value[1]);\n if (value.length !== 2) {\n errors.push(new ValidationError(key, value, `filter array for \"${value[0]}\" operator must have 2 elements`));\n } else if (type !== 'object') {\n errors.push(new ValidationError(`${key}[1]`, value[1], `object expected, ${type} found`));\n }\n break;\n }\n return errors;\n}\n","\nimport validate from './validate';\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport {isFunction} from '../function';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint';\nimport {supportsPropertyExpression} from '../util/properties';\n\nexport default function validateProperty(options, propertyType) {\n const key = options.key;\n const style = options.style;\n const styleSpec = options.styleSpec;\n const value = options.value;\n const propertyKey = options.objectKey;\n const layerSpec = styleSpec[`${propertyType}_${options.layerType}`];\n\n if (!layerSpec) return [];\n\n const transitionMatch = propertyKey.match(/^(.*)-transition$/);\n if (propertyType === 'paint' && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) {\n return validate({\n key,\n value,\n valueSpec: styleSpec.transition,\n style,\n styleSpec\n });\n }\n\n const valueSpec = options.valueSpec || layerSpec[propertyKey];\n if (!valueSpec) {\n return [new ValidationError(key, value, `unknown property \"${propertyKey}\"`)];\n }\n\n let tokenMatch;\n if (getType(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) {\n return [new ValidationError(\n key, value,\n `\"${propertyKey}\" does not support interpolation syntax\\n` +\n `Use an identity property function instead: \\`{ \"type\": \"identity\", \"property\": ${JSON.stringify(tokenMatch[1])} }\\`.`)];\n }\n\n const errors = [];\n\n if (options.layerType === 'symbol') {\n if (propertyKey === 'text-field' && style && !style.glyphs) {\n errors.push(new ValidationError(key, value, 'use of \"text-field\" requires a style \"glyphs\" property'));\n }\n if (propertyKey === 'text-font' && isFunction(deepUnbundle(value)) && unbundle(value.type) === 'identity') {\n errors.push(new ValidationError(key, value, '\"text-font\" does not support identity functions'));\n }\n }\n\n return errors.concat(validate({\n key: options.key,\n value,\n valueSpec,\n style,\n styleSpec,\n expressionContext: 'property',\n propertyType,\n propertyKey\n }));\n}\n","\nimport validateProperty from './validate_property';\n\nexport default function validatePaintProperty(options) {\n return validateProperty(options, 'paint');\n}\n","\nimport validateProperty from './validate_property';\n\nexport default function validateLayoutProperty(options) {\n return validateProperty(options, 'layout');\n}\n","\nimport ValidationError from '../error/validation_error';\nimport {unbundle} from '../util/unbundle_jsonlint';\nimport validateObject from './validate_object';\nimport validateFilter from './validate_filter';\nimport validatePaintProperty from './validate_paint_property';\nimport validateLayoutProperty from './validate_layout_property';\nimport validateSpec from './validate';\nimport extend from '../util/extend';\n\nexport default function validateLayer(options) {\n let errors = [];\n\n const layer = options.value;\n const key = options.key;\n const style = options.style;\n const styleSpec = options.styleSpec;\n\n if (!layer.type && !layer.ref) {\n errors.push(new ValidationError(key, layer, 'either \"type\" or \"ref\" is required'));\n }\n let type = unbundle(layer.type);\n const ref = unbundle(layer.ref);\n\n if (layer.id) {\n const layerId = unbundle(layer.id);\n for (let i = 0; i < options.arrayIndex; i++) {\n const otherLayer = style.layers[i];\n if (unbundle(otherLayer.id) === layerId) {\n errors.push(new ValidationError(key, layer.id, `duplicate layer id \"${layer.id}\", previously used at line ${otherLayer.id.__line__}`));\n }\n }\n }\n\n if ('ref' in layer) {\n ['type', 'source', 'source-layer', 'filter', 'layout'].forEach((p) => {\n if (p in layer) {\n errors.push(new ValidationError(key, layer[p], `\"${p}\" is prohibited for ref layers`));\n }\n });\n\n let parent;\n\n style.layers.forEach((layer) => {\n if (unbundle(layer.id) === ref) parent = layer;\n });\n\n if (!parent) {\n errors.push(new ValidationError(key, layer.ref, `ref layer \"${ref}\" not found`));\n } else if (parent.ref) {\n errors.push(new ValidationError(key, layer.ref, 'ref cannot reference another ref layer'));\n } else {\n type = unbundle(parent.type);\n }\n } else if (type !== 'background') {\n if (!layer.source) {\n errors.push(new ValidationError(key, layer, 'missing required property \"source\"'));\n } else {\n const source = style.sources && style.sources[layer.source];\n const sourceType = source && unbundle(source.type);\n if (!source) {\n errors.push(new ValidationError(key, layer.source, `source \"${layer.source}\" not found`));\n } else if (sourceType === 'vector' && type === 'raster') {\n errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a raster source`));\n } else if (sourceType === 'raster' && type !== 'raster') {\n errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a vector source`));\n } else if (sourceType === 'vector' && !layer['source-layer']) {\n errors.push(new ValidationError(key, layer, `layer \"${layer.id}\" must specify a \"source-layer\"`));\n } else if (sourceType === 'raster-dem' && type !== 'hillshade') {\n errors.push(new ValidationError(key, layer.source, 'raster-dem source can only be used with layer type \\'hillshade\\'.'));\n } else if (type === 'line' && layer.paint && layer.paint['line-gradient'] &&\n (sourceType !== 'geojson' || !source.lineMetrics)) {\n errors.push(new ValidationError(key, layer, `layer \"${layer.id}\" specifies a line-gradient, which requires a GeoJSON source with \\`lineMetrics\\` enabled.`));\n }\n }\n }\n\n errors = errors.concat(validateObject({\n key,\n value: layer,\n valueSpec: styleSpec.layer,\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {\n '*'() {\n return [];\n },\n // We don't want to enforce the spec's `\"requires\": true` for backward compatibility with refs;\n // the actual requirement is validated above. See https://github.com/mapbox/mapbox-gl-js/issues/5772.\n type() {\n return validateSpec({\n key: `${key}.type`,\n value: layer.type,\n valueSpec: styleSpec.layer.type,\n style: options.style,\n styleSpec: options.styleSpec,\n object: layer,\n objectKey: 'type'\n });\n },\n filter: validateFilter,\n layout(options) {\n return validateObject({\n layer,\n key: options.key,\n value: options.value,\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {\n '*'(options) {\n return validateLayoutProperty(extend({layerType: type}, options));\n }\n }\n });\n },\n paint(options) {\n return validateObject({\n layer,\n key: options.key,\n value: options.value,\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {\n '*'(options) {\n return validatePaintProperty(extend({layerType: type}, options));\n }\n }\n });\n }\n }\n }));\n\n return errors;\n}\n","\nimport getType from '../util/get_type';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateString(options) {\n const value = options.value;\n const key = options.key;\n const type = getType(value);\n\n if (type !== 'string') {\n return [new ValidationError(key, value, `string expected, ${type} found`)];\n }\n\n return [];\n}\n","\nimport ValidationError from '../error/validation_error';\nimport {unbundle} from '../util/unbundle_jsonlint';\nimport validateObject from './validate_object';\nimport validateEnum from './validate_enum';\nimport validateExpression from './validate_expression';\nimport validateString from './validate_string';\nimport getType from '../util/get_type';\n\nconst objectElementValidators = {\n promoteId: validatePromoteId\n};\n\nexport default function validateSource(options) {\n const value = options.value;\n const key = options.key;\n const styleSpec = options.styleSpec;\n const style = options.style;\n\n if (!value.type) {\n return [new ValidationError(key, value, '\"type\" is required')];\n }\n\n const type = unbundle(value.type);\n let errors;\n\n switch (type) {\n case 'vector':\n case 'raster':\n case 'raster-dem':\n errors = validateObject({\n key,\n value,\n valueSpec: styleSpec[`source_${type.replace('-', '_')}`],\n style: options.style,\n styleSpec,\n objectElementValidators\n });\n return errors;\n\n case 'geojson':\n errors = validateObject({\n key,\n value,\n valueSpec: styleSpec.source_geojson,\n style,\n styleSpec,\n objectElementValidators\n });\n if (value.cluster) {\n for (const prop in value.clusterProperties) {\n const [operator, mapExpr] = value.clusterProperties[prop];\n const reduceExpr = typeof operator === 'string' ? [operator, ['accumulated'], ['get', prop]] : operator;\n\n errors.push(...validateExpression({\n key: `${key}.${prop}.map`,\n value: mapExpr,\n expressionContext: 'cluster-map'\n }));\n errors.push(...validateExpression({\n key: `${key}.${prop}.reduce`,\n value: reduceExpr,\n expressionContext: 'cluster-reduce'\n }));\n }\n }\n return errors;\n\n case 'video':\n return validateObject({\n key,\n value,\n valueSpec: styleSpec.source_video,\n style,\n styleSpec\n });\n\n case 'image':\n return validateObject({\n key,\n value,\n valueSpec: styleSpec.source_image,\n style,\n styleSpec\n });\n\n case 'canvas':\n return [new ValidationError(key, null, `Please use runtime APIs to add canvas sources, rather than including them in stylesheets.`, 'source.canvas')];\n\n default:\n return validateEnum({\n key: `${key}.type`,\n value: value.type,\n valueSpec: {values: ['vector', 'raster', 'raster-dem', 'geojson', 'video', 'image']},\n style,\n styleSpec\n });\n }\n}\n\nfunction validatePromoteId({key, value}) {\n if (getType(value) === 'string') {\n return validateString({key, value});\n } else {\n const errors = [];\n for (const prop in value) {\n errors.push(...validateString({key: `${key}.${prop}`, value: value[prop]}));\n }\n return errors;\n }\n}\n","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport validate from './validate';\n\nexport default function validateLight(options) {\n const light = options.value;\n const styleSpec = options.styleSpec;\n const lightSpec = styleSpec.light;\n const style = options.style;\n\n let errors = [];\n\n const rootType = getType(light);\n if (light === undefined) {\n return errors;\n } else if (rootType !== 'object') {\n errors = errors.concat([new ValidationError('light', light, `object expected, ${rootType} found`)]);\n return errors;\n }\n\n for (const key in light) {\n const transitionMatch = key.match(/^(.*)-transition$/);\n\n if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) {\n errors = errors.concat(validate({\n key,\n value: light[key],\n valueSpec: styleSpec.transition,\n style,\n styleSpec\n }));\n } else if (lightSpec[key]) {\n errors = errors.concat(validate({\n key,\n value: light[key],\n valueSpec: lightSpec[key],\n style,\n styleSpec\n }));\n } else {\n errors = errors.concat([new ValidationError(key, light[key], `unknown property \"${key}\"`)]);\n }\n }\n\n return errors;\n}\n","// @flow\nimport validateExpression from './validate_expression';\nimport validateString from './validate_string';\n\nexport default function validateFormatted(options: any) {\n if (validateString(options).length === 0) {\n return [];\n }\n\n return validateExpression(options);\n}\n","// @flow\nimport validateExpression from './validate_expression';\nimport validateString from './validate_string';\n\nexport default function validateImage(options: any) {\n if (validateString(options).length === 0) {\n return [];\n }\n\n return validateExpression(options);\n}\n","\nimport extend from '../util/extend';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint';\nimport {isExpression} from '../expression';\nimport {isFunction} from '../function';\n\nimport validateFunction from './validate_function';\nimport validateExpression from './validate_expression';\nimport validateObject from './validate_object';\nimport validateArray from './validate_array';\nimport validateBoolean from './validate_boolean';\nimport validateNumber from './validate_number';\nimport validateColor from './validate_color';\nimport validateConstants from './validate_constants';\nimport validateEnum from './validate_enum';\nimport validateFilter from './validate_filter';\nimport validateLayer from './validate_layer';\nimport validateSource from './validate_source';\nimport validateLight from './validate_light';\nimport validateString from './validate_string';\nimport validateFormatted from './validate_formatted';\nimport validateImage from './validate_image';\n\nconst VALIDATORS = {\n '*'() {\n return [];\n },\n 'array': validateArray,\n 'boolean': validateBoolean,\n 'number': validateNumber,\n 'color': validateColor,\n 'constants': validateConstants,\n 'enum': validateEnum,\n 'filter': validateFilter,\n 'function': validateFunction,\n 'layer': validateLayer,\n 'object': validateObject,\n 'source': validateSource,\n 'light': validateLight,\n 'string': validateString,\n 'formatted': validateFormatted,\n 'resolvedImage': validateImage\n};\n\n// Main recursive validation function. Tracks:\n//\n// - key: string representing location of validation in style tree. Used only\n// for more informative error reporting.\n// - value: current value from style being evaluated. May be anything from a\n// high level object that needs to be descended into deeper or a simple\n// scalar value.\n// - valueSpec: current spec being evaluated. Tracks value.\n// - styleSpec: current full spec being evaluated.\n\nexport default function validate(options) {\n const value = options.value;\n const valueSpec = options.valueSpec;\n const styleSpec = options.styleSpec;\n\n if (valueSpec.expression && isFunction(unbundle(value))) {\n return validateFunction(options);\n\n } else if (valueSpec.expression && isExpression(deepUnbundle(value))) {\n return validateExpression(options);\n\n } else if (valueSpec.type && VALIDATORS[valueSpec.type]) {\n return VALIDATORS[valueSpec.type](options);\n\n } else {\n const valid = validateObject(extend({}, options, {\n valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec\n }));\n return valid;\n }\n}\n","\nimport ValidationError from '../error/validation_error';\nimport validateString from './validate_string';\n\nexport default function(options) {\n const value = options.value;\n const key = options.key;\n\n const errors = validateString(options);\n if (errors.length) return errors;\n\n if (value.indexOf('{fontstack}') === -1) {\n errors.push(new ValidationError(key, value, '\"glyphs\" url must include a \"{fontstack}\" token'));\n }\n\n if (value.indexOf('{range}') === -1) {\n errors.push(new ValidationError(key, value, '\"glyphs\" url must include a \"{range}\" token'));\n }\n\n return errors;\n}\n","\nimport validateConstants from './validate/validate_constants';\nimport validate from './validate/validate';\nimport latestStyleSpec from './reference/latest';\nimport validateGlyphsURL from './validate/validate_glyphs_url';\n\nimport validateSource from './validate/validate_source';\nimport validateLight from './validate/validate_light';\nimport validateLayer from './validate/validate_layer';\nimport validateFilter from './validate/validate_filter';\nimport validatePaintProperty from './validate/validate_paint_property';\nimport validateLayoutProperty from './validate/validate_layout_property';\n\n/**\n * Validate a Mapbox GL style against the style specification. This entrypoint,\n * `mapbox-gl-style-spec/lib/validate_style.min`, is designed to produce as\n * small a browserify bundle as possible by omitting unnecessary functionality\n * and legacy style specifications.\n *\n * @private\n * @param {Object} style The style to be validated.\n * @param {Object} [styleSpec] The style specification to validate against.\n * If omitted, the latest style spec is used.\n * @returns {Array}\n * @example\n * var validate = require('mapbox-gl-style-spec/lib/validate_style.min');\n * var errors = validate(style);\n */\nfunction validateStyleMin(style, styleSpec = latestStyleSpec) {\n\n let errors = [];\n\n errors = errors.concat(validate({\n key: '',\n value: style,\n valueSpec: styleSpec.$root,\n styleSpec,\n style,\n objectElementValidators: {\n glyphs: validateGlyphsURL,\n '*'() {\n return [];\n }\n }\n }));\n\n if (style.constants) {\n errors = errors.concat(validateConstants({\n key: 'constants',\n value: style.constants,\n style,\n styleSpec\n }));\n }\n\n return sortErrors(errors);\n}\n\nvalidateStyleMin.source = wrapCleanErrors(validateSource);\nvalidateStyleMin.light = wrapCleanErrors(validateLight);\nvalidateStyleMin.layer = wrapCleanErrors(validateLayer);\nvalidateStyleMin.filter = wrapCleanErrors(validateFilter);\nvalidateStyleMin.paintProperty = wrapCleanErrors(validatePaintProperty);\nvalidateStyleMin.layoutProperty = wrapCleanErrors(validateLayoutProperty);\n\nfunction sortErrors(errors) {\n return [].concat(errors).sort((a, b) => {\n return a.line - b.line;\n });\n}\n\nfunction wrapCleanErrors(inner) {\n return function(...args) {\n return sortErrors(inner.apply(this, args));\n };\n}\n\nexport default validateStyleMin;\n","/* parser generated by jison 0.4.15 */\n/*\n Returns a Parser object of the following structure:\n\n Parser: {\n yy: {}\n }\n\n Parser.prototype: {\n yy: {},\n trace: function(),\n symbols_: {associative list: name ==> number},\n terminals_: {associative list: number ==> name},\n productions_: [...],\n performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$),\n table: [...],\n defaultActions: {...},\n parseError: function(str, hash),\n parse: function(input),\n\n lexer: {\n EOF: 1,\n parseError: function(str, hash),\n setInput: function(input),\n input: function(),\n unput: function(str),\n more: function(),\n less: function(n),\n pastInput: function(),\n upcomingInput: function(),\n showPosition: function(),\n test_match: function(regex_match_array, rule_index),\n next: function(),\n lex: function(),\n begin: function(condition),\n popState: function(),\n _currentRules: function(),\n topState: function(),\n pushState: function(condition),\n\n options: {\n ranges: boolean (optional: true ==> token location info will include a .range[] member)\n flex: boolean (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match)\n backtrack_lexer: boolean (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code)\n },\n\n performAction: function(yy, yy_, $avoiding_name_collisions, YY_START),\n rules: [...],\n conditions: {associative list: name ==> set},\n }\n }\n\n\n token location info (@$, _$, etc.): {\n first_line: n,\n last_line: n,\n first_column: n,\n last_column: n,\n range: [start_number, end_number] (where the numbers are indexes into the input string, regular zero-based)\n }\n\n\n the parseError function receives a 'hash' object with these members for lexer and parser errors: {\n text: (matched text)\n token: (the produced terminal token, if any)\n line: (yylineno)\n }\n while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: {\n loc: (yylloc)\n expected: (string describing the set of expected tokens)\n recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error)\n }\n*/\nvar parser = (function(){\nvar o=function(k,v,o,l){for(o=o||{},l=k.length;l--;o[k[l]]=v);return o},$V0=[1,12],$V1=[1,13],$V2=[1,9],$V3=[1,10],$V4=[1,11],$V5=[1,14],$V6=[1,15],$V7=[14,18,22,24],$V8=[18,22],$V9=[22,24];\nvar parser = {trace: function trace() { },\nyy: {},\nsymbols_: {\"error\":2,\"JSONString\":3,\"STRING\":4,\"JSONNumber\":5,\"NUMBER\":6,\"JSONNullLiteral\":7,\"NULL\":8,\"JSONBooleanLiteral\":9,\"TRUE\":10,\"FALSE\":11,\"JSONText\":12,\"JSONValue\":13,\"EOF\":14,\"JSONObject\":15,\"JSONArray\":16,\"{\":17,\"}\":18,\"JSONMemberList\":19,\"JSONMember\":20,\":\":21,\",\":22,\"[\":23,\"]\":24,\"JSONElementList\":25,\"$accept\":0,\"$end\":1},\nterminals_: {2:\"error\",4:\"STRING\",6:\"NUMBER\",8:\"NULL\",10:\"TRUE\",11:\"FALSE\",14:\"EOF\",17:\"{\",18:\"}\",21:\":\",22:\",\",23:\"[\",24:\"]\"},\nproductions_: [0,[3,1],[5,1],[7,1],[9,1],[9,1],[12,2],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[15,2],[15,3],[20,3],[19,1],[19,3],[16,2],[16,3],[25,1],[25,3]],\nperformAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */) {\n/* this == yyval */\n\nvar $0 = $$.length - 1;\nswitch (yystate) {\ncase 1:\n // replace escaped characters with actual character\n this.$ = new String(yytext.replace(/\\\\(\\\\|\")/g, \"$\"+\"1\")\n .replace(/\\\\n/g,'\\n')\n .replace(/\\\\r/g,'\\r')\n .replace(/\\\\t/g,'\\t')\n .replace(/\\\\v/g,'\\v')\n .replace(/\\\\f/g,'\\f')\n .replace(/\\\\b/g,'\\b'));\n this.$.__line__ = this._$.first_line;\n \nbreak;\ncase 2:\n\n this.$ = new Number(yytext);\n this.$.__line__ = this._$.first_line;\n \nbreak;\ncase 3:\n\n this.$ = null;\n \nbreak;\ncase 4:\n\n this.$ = new Boolean(true);\n this.$.__line__ = this._$.first_line;\n \nbreak;\ncase 5:\n\n this.$ = new Boolean(false);\n this.$.__line__ = this._$.first_line;\n \nbreak;\ncase 6:\nreturn this.$ = $$[$0-1];\nbreak;\ncase 13:\nthis.$ = {}; Object.defineProperty(this.$, '__line__', {\n value: this._$.first_line,\n enumerable: false\n })\nbreak;\ncase 14: case 19:\nthis.$ = $$[$0-1]; Object.defineProperty(this.$, '__line__', {\n value: this._$.first_line,\n enumerable: false\n })\nbreak;\ncase 15:\nthis.$ = [$$[$0-2], $$[$0]];\nbreak;\ncase 16:\nthis.$ = {}; this.$[$$[$0][0]] = $$[$0][1];\nbreak;\ncase 17:\nthis.$ = $$[$0-2]; $$[$0-2][$$[$0][0]] = $$[$0][1];\nbreak;\ncase 18:\nthis.$ = []; Object.defineProperty(this.$, '__line__', {\n value: this._$.first_line,\n enumerable: false\n })\nbreak;\ncase 20:\nthis.$ = [$$[$0]];\nbreak;\ncase 21:\nthis.$ = $$[$0-2]; $$[$0-2].push($$[$0]);\nbreak;\n}\n},\ntable: [{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,12:1,13:2,15:7,16:8,17:$V5,23:$V6},{1:[3]},{14:[1,16]},o($V7,[2,7]),o($V7,[2,8]),o($V7,[2,9]),o($V7,[2,10]),o($V7,[2,11]),o($V7,[2,12]),o($V7,[2,3]),o($V7,[2,4]),o($V7,[2,5]),o([14,18,21,22,24],[2,1]),o($V7,[2,2]),{3:20,4:$V0,18:[1,17],19:18,20:19},{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,13:23,15:7,16:8,17:$V5,23:$V6,24:[1,21],25:22},{1:[2,6]},o($V7,[2,13]),{18:[1,24],22:[1,25]},o($V8,[2,16]),{21:[1,26]},o($V7,[2,18]),{22:[1,28],24:[1,27]},o($V9,[2,20]),o($V7,[2,14]),{3:20,4:$V0,20:29},{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,13:30,15:7,16:8,17:$V5,23:$V6},o($V7,[2,19]),{3:5,4:$V0,5:6,6:$V1,7:3,8:$V2,9:4,10:$V3,11:$V4,13:31,15:7,16:8,17:$V5,23:$V6},o($V8,[2,17]),o($V8,[2,15]),o($V9,[2,21])],\ndefaultActions: {16:[2,6]},\nparseError: function parseError(str, hash) {\n if (hash.recoverable) {\n this.trace(str);\n } else {\n throw new Error(str);\n }\n},\nparse: function parse(input) {\n var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = '', yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;\n var args = lstack.slice.call(arguments, 1);\n var lexer = Object.create(this.lexer);\n var sharedState = { yy: {} };\n for (var k in this.yy) {\n if (Object.prototype.hasOwnProperty.call(this.yy, k)) {\n sharedState.yy[k] = this.yy[k];\n }\n }\n lexer.setInput(input, sharedState.yy);\n sharedState.yy.lexer = lexer;\n sharedState.yy.parser = this;\n if (typeof lexer.yylloc == 'undefined') {\n lexer.yylloc = {};\n }\n var yyloc = lexer.yylloc;\n lstack.push(yyloc);\n var ranges = lexer.options && lexer.options.ranges;\n if (typeof sharedState.yy.parseError === 'function') {\n this.parseError = sharedState.yy.parseError;\n } else {\n this.parseError = Object.getPrototypeOf(this).parseError;\n }\n function popStack(n) {\n stack.length = stack.length - 2 * n;\n vstack.length = vstack.length - n;\n lstack.length = lstack.length - n;\n }\n _token_stack:\n function lex() {\n var token;\n token = lexer.lex() || EOF;\n if (typeof token !== 'number') {\n token = self.symbols_[token] || token;\n }\n return token;\n }\n var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;\n while (true) {\n state = stack[stack.length - 1];\n if (this.defaultActions[state]) {\n action = this.defaultActions[state];\n } else {\n if (symbol === null || typeof symbol == 'undefined') {\n symbol = lex();\n }\n action = table[state] && table[state][symbol];\n }\n if (typeof action === 'undefined' || !action.length || !action[0]) {\n var errStr = '';\n expected = [];\n for (p in table[state]) {\n if (this.terminals_[p] && p > TERROR) {\n expected.push('\\'' + this.terminals_[p] + '\\'');\n }\n }\n if (lexer.showPosition) {\n errStr = 'Parse error on line ' + (yylineno + 1) + ':\\n' + lexer.showPosition() + '\\nExpecting ' + expected.join(', ') + ', got \\'' + (this.terminals_[symbol] || symbol) + '\\'';\n } else {\n errStr = 'Parse error on line ' + (yylineno + 1) + ': Unexpected ' + (symbol == EOF ? 'end of input' : '\\'' + (this.terminals_[symbol] || symbol) + '\\'');\n }\n this.parseError(errStr, {\n text: lexer.match,\n token: this.terminals_[symbol] || symbol,\n line: lexer.yylineno,\n loc: yyloc,\n expected: expected\n });\n }\n if (action[0] instanceof Array && action.length > 1) {\n throw new Error('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol);\n }\n switch (action[0]) {\n case 1:\n stack.push(symbol);\n vstack.push(lexer.yytext);\n lstack.push(lexer.yylloc);\n stack.push(action[1]);\n symbol = null;\n if (!preErrorSymbol) {\n yyleng = lexer.yyleng;\n yytext = lexer.yytext;\n yylineno = lexer.yylineno;\n yyloc = lexer.yylloc;\n if (recovering > 0) {\n recovering--;\n }\n } else {\n symbol = preErrorSymbol;\n preErrorSymbol = null;\n }\n break;\n case 2:\n len = this.productions_[action[1]][1];\n yyval.$ = vstack[vstack.length - len];\n yyval._$ = {\n first_line: lstack[lstack.length - (len || 1)].first_line,\n last_line: lstack[lstack.length - 1].last_line,\n first_column: lstack[lstack.length - (len || 1)].first_column,\n last_column: lstack[lstack.length - 1].last_column\n };\n if (ranges) {\n yyval._$.range = [\n lstack[lstack.length - (len || 1)].range[0],\n lstack[lstack.length - 1].range[1]\n ];\n }\n r = this.performAction.apply(yyval, [\n yytext,\n yyleng,\n yylineno,\n sharedState.yy,\n action[1],\n vstack,\n lstack\n ].concat(args));\n if (typeof r !== 'undefined') {\n return r;\n }\n if (len) {\n stack = stack.slice(0, -1 * len * 2);\n vstack = vstack.slice(0, -1 * len);\n lstack = lstack.slice(0, -1 * len);\n }\n stack.push(this.productions_[action[1]][0]);\n vstack.push(yyval.$);\n lstack.push(yyval._$);\n newState = table[stack[stack.length - 2]][stack[stack.length - 1]];\n stack.push(newState);\n break;\n case 3:\n return true;\n }\n }\n return true;\n}};\n/* generated by jison-lex 0.3.4 */\nvar lexer = (function(){\nvar lexer = ({\n\nEOF:1,\n\nparseError:function parseError(str, hash) {\n if (this.yy.parser) {\n this.yy.parser.parseError(str, hash);\n } else {\n throw new Error(str);\n }\n },\n\n// resets the lexer, sets new input\nsetInput:function (input, yy) {\n this.yy = yy || this.yy || {};\n this._input = input;\n this._more = this._backtrack = this.done = false;\n this.yylineno = this.yyleng = 0;\n this.yytext = this.matched = this.match = '';\n this.conditionStack = ['INITIAL'];\n this.yylloc = {\n first_line: 1,\n first_column: 0,\n last_line: 1,\n last_column: 0\n };\n if (this.options.ranges) {\n this.yylloc.range = [0,0];\n }\n this.offset = 0;\n return this;\n },\n\n// consumes and returns one char from the input\ninput:function () {\n var ch = this._input[0];\n this.yytext += ch;\n this.yyleng++;\n this.offset++;\n this.match += ch;\n this.matched += ch;\n var lines = ch.match(/(?:\\r\\n?|\\n).*/g);\n if (lines) {\n this.yylineno++;\n this.yylloc.last_line++;\n } else {\n this.yylloc.last_column++;\n }\n if (this.options.ranges) {\n this.yylloc.range[1]++;\n }\n\n this._input = this._input.slice(1);\n return ch;\n },\n\n// unshifts one char (or a string) into the input\nunput:function (ch) {\n var len = ch.length;\n var lines = ch.split(/(?:\\r\\n?|\\n)/g);\n\n this._input = ch + this._input;\n this.yytext = this.yytext.substr(0, this.yytext.length - len);\n //this.yyleng -= len;\n this.offset -= len;\n var oldLines = this.match.split(/(?:\\r\\n?|\\n)/g);\n this.match = this.match.substr(0, this.match.length - 1);\n this.matched = this.matched.substr(0, this.matched.length - 1);\n\n if (lines.length - 1) {\n this.yylineno -= lines.length - 1;\n }\n var r = this.yylloc.range;\n\n this.yylloc = {\n first_line: this.yylloc.first_line,\n last_line: this.yylineno + 1,\n first_column: this.yylloc.first_column,\n last_column: lines ?\n (lines.length === oldLines.length ? this.yylloc.first_column : 0)\n + oldLines[oldLines.length - lines.length].length - lines[0].length :\n this.yylloc.first_column - len\n };\n\n if (this.options.ranges) {\n this.yylloc.range = [r[0], r[0] + this.yyleng - len];\n }\n this.yyleng = this.yytext.length;\n return this;\n },\n\n// When called from action, caches matched text and appends it on next action\nmore:function () {\n this._more = true;\n return this;\n },\n\n// When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead.\nreject:function () {\n if (this.options.backtrack_lexer) {\n this._backtrack = true;\n } else {\n return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\\n' + this.showPosition(), {\n text: \"\",\n token: null,\n line: this.yylineno\n });\n\n }\n return this;\n },\n\n// retain first n characters of the match\nless:function (n) {\n this.unput(this.match.slice(n));\n },\n\n// displays already matched input, i.e. for error messages\npastInput:function () {\n var past = this.matched.substr(0, this.matched.length - this.match.length);\n return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\\n/g, \"\");\n },\n\n// displays upcoming input, i.e. for error messages\nupcomingInput:function () {\n var next = this.match;\n if (next.length < 20) {\n next += this._input.substr(0, 20-next.length);\n }\n return (next.substr(0,20) + (next.length > 20 ? '...' : '')).replace(/\\n/g, \"\");\n },\n\n// displays the character position where the lexing error occurred, i.e. for error messages\nshowPosition:function () {\n var pre = this.pastInput();\n var c = new Array(pre.length + 1).join(\"-\");\n return pre + this.upcomingInput() + \"\\n\" + c + \"^\";\n },\n\n// test the lexed token: return FALSE when not a match, otherwise return token\ntest_match:function (match, indexed_rule) {\n var token,\n lines,\n backup;\n\n if (this.options.backtrack_lexer) {\n // save context\n backup = {\n yylineno: this.yylineno,\n yylloc: {\n first_line: this.yylloc.first_line,\n last_line: this.last_line,\n first_column: this.yylloc.first_column,\n last_column: this.yylloc.last_column\n },\n yytext: this.yytext,\n match: this.match,\n matches: this.matches,\n matched: this.matched,\n yyleng: this.yyleng,\n offset: this.offset,\n _more: this._more,\n _input: this._input,\n yy: this.yy,\n conditionStack: this.conditionStack.slice(0),\n done: this.done\n };\n if (this.options.ranges) {\n backup.yylloc.range = this.yylloc.range.slice(0);\n }\n }\n\n lines = match[0].match(/(?:\\r\\n?|\\n).*/g);\n if (lines) {\n this.yylineno += lines.length;\n }\n this.yylloc = {\n first_line: this.yylloc.last_line,\n last_line: this.yylineno + 1,\n first_column: this.yylloc.last_column,\n last_column: lines ?\n lines[lines.length - 1].length - lines[lines.length - 1].match(/\\r?\\n?/)[0].length :\n this.yylloc.last_column + match[0].length\n };\n this.yytext += match[0];\n this.match += match[0];\n this.matches = match;\n this.yyleng = this.yytext.length;\n if (this.options.ranges) {\n this.yylloc.range = [this.offset, this.offset += this.yyleng];\n }\n this._more = false;\n this._backtrack = false;\n this._input = this._input.slice(match[0].length);\n this.matched += match[0];\n token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]);\n if (this.done && this._input) {\n this.done = false;\n }\n if (token) {\n return token;\n } else if (this._backtrack) {\n // recover context\n for (var k in backup) {\n this[k] = backup[k];\n }\n return false; // rule action called reject() implying the next rule should be tested instead.\n }\n return false;\n },\n\n// return next match in input\nnext:function () {\n if (this.done) {\n return this.EOF;\n }\n if (!this._input) {\n this.done = true;\n }\n\n var token,\n match,\n tempMatch,\n index;\n if (!this._more) {\n this.yytext = '';\n this.match = '';\n }\n var rules = this._currentRules();\n for (var i = 0; i < rules.length; i++) {\n tempMatch = this._input.match(this.rules[rules[i]]);\n if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {\n match = tempMatch;\n index = i;\n if (this.options.backtrack_lexer) {\n token = this.test_match(tempMatch, rules[i]);\n if (token !== false) {\n return token;\n } else if (this._backtrack) {\n match = false;\n continue; // rule action called reject() implying a rule MISmatch.\n } else {\n // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)\n return false;\n }\n } else if (!this.options.flex) {\n break;\n }\n }\n }\n if (match) {\n token = this.test_match(match, rules[index]);\n if (token !== false) {\n return token;\n }\n // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)\n return false;\n }\n if (this._input === \"\") {\n return this.EOF;\n } else {\n return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\\n' + this.showPosition(), {\n text: \"\",\n token: null,\n line: this.yylineno\n });\n }\n },\n\n// return next match that has a token\nlex:function lex() {\n var r = this.next();\n if (r) {\n return r;\n } else {\n return this.lex();\n }\n },\n\n// activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)\nbegin:function begin(condition) {\n this.conditionStack.push(condition);\n },\n\n// pop the previously active lexer condition state off the condition stack\npopState:function popState() {\n var n = this.conditionStack.length - 1;\n if (n > 0) {\n return this.conditionStack.pop();\n } else {\n return this.conditionStack[0];\n }\n },\n\n// produce the lexer rule set which is active for the currently active lexer condition state\n_currentRules:function _currentRules() {\n if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) {\n return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;\n } else {\n return this.conditions[\"INITIAL\"].rules;\n }\n },\n\n// return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available\ntopState:function topState(n) {\n n = this.conditionStack.length - 1 - Math.abs(n || 0);\n if (n >= 0) {\n return this.conditionStack[n];\n } else {\n return \"INITIAL\";\n }\n },\n\n// alias for begin(condition)\npushState:function pushState(condition) {\n this.begin(condition);\n },\n\n// return the number of states currently on the stack\nstateStackSize:function stateStackSize() {\n return this.conditionStack.length;\n },\noptions: {},\nperformAction: function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) {\nvar YYSTATE=YY_START;\nswitch($avoiding_name_collisions) {\ncase 0:/* skip whitespace */\nbreak;\ncase 1:return 6\nbreak;\ncase 2:yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2); return 4\nbreak;\ncase 3:return 17\nbreak;\ncase 4:return 18\nbreak;\ncase 5:return 23\nbreak;\ncase 6:return 24\nbreak;\ncase 7:return 22\nbreak;\ncase 8:return 21\nbreak;\ncase 9:return 10\nbreak;\ncase 10:return 11\nbreak;\ncase 11:return 8\nbreak;\ncase 12:return 14\nbreak;\ncase 13:return 'INVALID'\nbreak;\n}\n},\nrules: [/^(?:\\s+)/,/^(?:(-?([0-9]|[1-9][0-9]+))(\\.[0-9]+)?([eE][-+]?[0-9]+)?\\b)/,/^(?:\"(?:\\\\[\\\\\"bfnrt/]|\\\\u[a-fA-F0-9]{4}|[^\\\\\\0-\\x09\\x0a-\\x1f\"])*\")/,/^(?:\\{)/,/^(?:\\})/,/^(?:\\[)/,/^(?:\\])/,/^(?:,)/,/^(?::)/,/^(?:true\\b)/,/^(?:false\\b)/,/^(?:null\\b)/,/^(?:$)/,/^(?:.)/],\nconditions: {\"INITIAL\":{\"rules\":[0,1,2,3,4,5,6,7,8,9,10,11,12,13],\"inclusive\":true}}\n});\nreturn lexer;\n})();\nparser.lexer = lexer;\nfunction Parser () {\n this.yy = {};\n}\nParser.prototype = parser;parser.Parser = Parser;\nreturn new Parser;\n})();\n\n\nif (typeof require !== 'undefined' && typeof exports !== 'undefined') {\nexports.parser = parser;\nexports.Parser = parser.Parser;\nexports.parse = function () { return parser.parse.apply(parser, arguments); };\n}\n","import ParsingError from './error/parsing_error';\nimport jsonlint from '@mapbox/jsonlint-lines-primitives';\n\nexport default function readStyle(style) {\n if (style instanceof String || typeof style === 'string' || style instanceof Buffer) {\n try {\n return jsonlint.parse(style.toString());\n } catch (e) {\n throw new ParsingError(e);\n }\n }\n\n return style;\n}\n","\nimport validateStyleMin from './validate_style.min';\nimport {v8} from './style-spec';\nimport readStyle from './read_style';\n\n/**\n * Validate a Mapbox GL style against the style specification.\n *\n * @private\n * @alias validate\n * @param {Object|String|Buffer} style The style to be validated. If a `String`\n * or `Buffer` is provided, the returned errors will contain line numbers.\n * @param {Object} [styleSpec] The style specification to validate against.\n * If omitted, the spec version is inferred from the stylesheet.\n * @returns {Array}\n * @example\n * var validate = require('mapbox-gl-style-spec').validate;\n * var style = fs.readFileSync('./style.json', 'utf8');\n * var errors = validate(style);\n */\n\nexport default function validateStyle(style, styleSpec = v8) {\n let s = style;\n\n try {\n s = readStyle(s);\n } catch (e) {\n return [e];\n }\n\n return validateStyleMin(s, styleSpec);\n}\n\nexport const source = validateStyleMin.source;\nexport const light = validateStyleMin.light;\nexport const layer = validateStyleMin.layer;\nexport const filter = validateStyleMin.filter;\nexport const paintProperty = validateStyleMin.paintProperty;\nexport const layoutProperty = validateStyleMin.layoutProperty;\n","// @flow\n\nimport validateStyle from './validate_style.min';\nimport {v8} from './style-spec';\nimport readStyle from './read_style';\nimport ValidationError from './error/validation_error';\nimport getType from './util/get_type';\n\nconst SUPPORTED_SPEC_VERSION = 8;\nconst MAX_SOURCES_IN_STYLE = 15;\n\nfunction isValid(value: ?string, regex: RegExp): boolean {\n if (!value || getType(value) !== 'string') return true;\n return !!value.match(regex);\n}\n\nfunction getSourceCount(source: Object): number {\n if (source.url) {\n return source.url.split(',').length;\n } else {\n return 0;\n }\n}\n\nfunction getAllowedKeyErrors(obj: Object, keys: Array<*>, path: ?string): Array {\n const allowed = new Set(keys);\n const errors = [];\n Object.keys(obj).forEach(k => {\n if (!allowed.has(k)) {\n const prop = path ? `${path}.${k}` : null;\n errors.push(new ValidationError(prop, obj[k], `Unsupported property \"${k}\"`));\n }\n });\n return errors;\n}\n\nfunction getSourceErrors(source: Object, i: number): Array {\n const errors = [];\n\n /*\n * Inlined sources are not supported by the Mapbox Styles API, so only\n * \"type\", \"url\", and \"tileSize\" properties are valid\n */\n const sourceKeys = ['type', 'url', 'tileSize'];\n errors.push(...getAllowedKeyErrors(source, sourceKeys, 'source'));\n\n /*\n * \"source\" is required. Valid examples:\n * mapbox://mapbox.abcd1234\n * mapbox://penny.abcd1234\n * mapbox://mapbox.abcd1234,penny.abcd1234\n */\n const sourceUrlPattern = /^mapbox:\\/\\/([^/]*)$/;\n if (!isValid(source.url, sourceUrlPattern)) {\n errors.push(new ValidationError(`sources[${i}]`, source.url, 'Source url must be a valid Mapbox tileset url'));\n }\n\n return errors;\n}\n\nfunction getSourcesErrors(sources: Object): Array {\n const errors = [];\n let count = 0;\n\n Object.keys(sources).forEach((s: string, i: number) => {\n const sourceErrors = getSourceErrors(sources[s], i);\n\n // If source has errors, skip counting\n if (!sourceErrors.length) {\n count = count + getSourceCount(sources[s]);\n }\n\n errors.push(...sourceErrors);\n });\n\n if (count > MAX_SOURCES_IN_STYLE) {\n errors.push(new ValidationError('sources', null, `Styles must contain ${MAX_SOURCES_IN_STYLE} or fewer sources`));\n }\n\n return errors;\n}\n\nfunction getRootErrors(style: Object, specKeys: Array): Array {\n const errors = [];\n\n /*\n * The following keys are optional but fully managed by the Mapbox Styles\n * API. Values on stylesheet on POST or PATCH will be ignored: \"owner\",\n * \"id\", \"cacheControl\", \"draft\", \"created\", \"modified\"\n *\n * The following keys are optional. The Mapbox Styles API respects value on\n * stylesheet on PATCH, but ignores the value on POST: \"visibility\"\n */\n const optionalRootProperties = [\n 'owner',\n 'id',\n 'cacheControl',\n 'draft',\n 'created',\n 'modified',\n 'visibility'\n ];\n\n const allowedKeyErrors = getAllowedKeyErrors(style, [...specKeys, ...optionalRootProperties]);\n errors.push(...allowedKeyErrors);\n\n if (style.version > SUPPORTED_SPEC_VERSION || style.version < SUPPORTED_SPEC_VERSION) {\n errors.push(new ValidationError('version', style.version, `Style version must be ${SUPPORTED_SPEC_VERSION}`));\n }\n\n /*\n * \"glyphs\" is optional. If present, valid examples:\n * mapbox://fonts/penny/{fontstack}/{range}.pbf\n * mapbox://fonts/mapbox/{fontstack}/{range}.pbf\n */\n const glyphUrlPattern = /^mapbox:\\/\\/fonts\\/([^/]*)\\/{fontstack}\\/{range}.pbf$/;\n if (!isValid(style.glyphs, glyphUrlPattern)) {\n errors.push(new ValidationError('glyphs', style.glyphs, 'Styles must reference glyphs hosted by Mapbox'));\n }\n\n /*\n * \"sprite\" is optional. If present, valid examples:\n * mapbox://sprites/penny/abcd1234\n * mapbox://sprites/mapbox/abcd1234/draft\n * mapbox://sprites/cyrus/abcd1234/abcd1234\n */\n const spriteUrlPattern = /^mapbox:\\/\\/sprites\\/([^/]*)\\/([^/]*)\\/?([^/]*)?$/;\n if (!isValid(style.sprite, spriteUrlPattern)) {\n errors.push(new ValidationError('sprite', style.sprite, 'Styles must reference sprites hosted by Mapbox'));\n }\n\n /*\n * \"visibility\" is optional. If present, valid examples:\n * \"private\"\n * \"public\"\n */\n const visibilityPattern = /^(public|private)$/;\n if (!isValid(style.visibility, visibilityPattern)) {\n errors.push(new ValidationError('visibility', style.visibility, 'Style visibility must be public or private'));\n }\n\n return errors;\n}\n\n/**\n * Validate a Mapbox GL style against the style specification and check for\n * compatibility with the Mapbox Styles API.\n *\n * @param {Object} style The style to be validated.\n * @returns {Array}\n * @example\n * var validateMapboxApiSupported = require('mapbox-gl-style-spec/lib/validate_style_mapbox_api_supported.js');\n * var errors = validateMapboxApiSupported(style);\n */\nexport default function validateMapboxApiSupported(style: Object): Array {\n let s = style;\n try {\n s = readStyle(s);\n } catch (e) {\n return [e];\n }\n\n let errors = validateStyle(s, v8)\n .concat(getRootErrors(s, Object.keys(v8.$root)));\n\n if (s.sources) {\n errors = errors.concat(getSourcesErrors(s.sources));\n }\n\n return errors;\n}\n","// @flow\n\ntype ExpressionType = 'data-driven' | 'cross-faded' | 'cross-faded-data-driven' | 'color-ramp' | 'data-constant' | 'constant';\ntype ExpressionParameters = Array<'zoom' | 'feature' | 'feature-state' | 'heatmap-density' | 'line-progress'>;\n\ntype ExpressionSpecification = {\n interpolated: boolean,\n parameters: ExpressionParameters\n}\n\nexport type StylePropertySpecification = {\n type: 'number',\n 'property-type': ExpressionType,\n expression?: ExpressionSpecification,\n transition: boolean,\n default?: number\n} | {\n type: 'string',\n 'property-type': ExpressionType,\n expression?: ExpressionSpecification,\n transition: boolean,\n default?: string,\n tokens?: boolean\n} | {\n type: 'boolean',\n 'property-type': ExpressionType,\n expression?: ExpressionSpecification,\n transition: boolean,\n default?: boolean\n} | {\n type: 'enum',\n 'property-type': ExpressionType,\n expression?: ExpressionSpecification,\n values: {[_: string]: {}},\n transition: boolean,\n default?: string\n} | {\n type: 'color',\n 'property-type': ExpressionType,\n expression?: ExpressionSpecification,\n transition: boolean,\n default?: string,\n overridable: boolean\n} | {\n type: 'array',\n value: 'number',\n 'property-type': ExpressionType,\n expression?: ExpressionSpecification,\n length?: number,\n transition: boolean,\n default?: Array\n} | {\n type: 'array',\n value: 'string',\n 'property-type': ExpressionType,\n expression?: ExpressionSpecification,\n length?: number,\n transition: boolean,\n default?: Array\n};\n\nimport v8 from './reference/v8.json';\nimport latest from './reference/latest';\nimport format from './format';\nimport migrate from './migrate';\nimport composite from './composite';\nimport derefLayers from './deref';\nimport diff from './diff';\nimport ValidationError from './error/validation_error';\nimport ParsingError from './error/parsing_error';\nimport {StyleExpression, isExpression, createExpression, createPropertyExpression, normalizePropertyExpression, ZoomConstantExpression, ZoomDependentExpression, StylePropertyFunction} from './expression';\nimport featureFilter, {isExpressionFilter} from './feature_filter';\n\nimport convertFilter from './feature_filter/convert';\nimport Color from './util/color';\nimport {createFunction, isFunction} from './function';\nimport convertFunction from './function/convert';\nimport {eachSource, eachLayer, eachProperty} from './visit';\n\nimport validate from './validate_style';\nimport validateMapboxApiSupported from './validate_mapbox_api_supported';\n\nconst expression = {\n StyleExpression,\n isExpression,\n isExpressionFilter,\n createExpression,\n createPropertyExpression,\n normalizePropertyExpression,\n ZoomConstantExpression,\n ZoomDependentExpression,\n StylePropertyFunction\n};\n\nconst styleFunction = {\n convertFunction,\n createFunction,\n isFunction\n};\n\nconst visit = {eachSource, eachLayer, eachProperty};\n\nexport {\n v8,\n latest,\n format,\n migrate,\n composite,\n derefLayers,\n diff,\n ValidationError,\n ParsingError,\n expression,\n featureFilter,\n convertFilter,\n Color,\n styleFunction as function,\n validate,\n validateMapboxApiSupported,\n visit\n};\n\nvalidate.parsed = validate;\nvalidate.latest = validate;\n"],"names":["sortKeysBy","obj","reference","const","result","key","undefined","format","style","space","$root","layers","map","layer","stringifyPretty","indent","global","this","require$$0","require$$1","getPropertyReference","propertyName","let","i","Reference","layout","length","paint","eachSource","callback","k","sources","eachLayer","eachProperty","options","inner","propertyType","properties","Object","keys","forEach","path","id","value","set","x","eachLayout","indexOf","eachPaint","resolveConstant","constants","isFunction","Array","isArray","stops","renameProperty","from","to","version","source","type","url","coordinates","coord","reverse","property","stop","migrateFontstackURL","input","inputParsed","URL","parse","inputPathnameParts","pathname","split","protocol","hostname","glyphs","migrateFontStack","font","splitAndTrim","string","s","trim","Error","firstSymbolLayer","symbolLayers","splice","concat","output","inputs","ParsingError","message","super","Scope","parent","bindings","name","expression","get","has","NullType","kind","NumberType","StringType","BooleanType","ColorType","ObjectType","ValueType","ErrorType","CollatorType","FormattedType","ResolvedImageType","array","itemType","N","toString","valueMemberTypes","checkSubtype","expected","t","memberType","isValidType","provided","allowedTypes","some","isValidNativeType","Color","r","g","b","a","rgba","parseCSSColor","toArray","Math","round","black","white","transparent","red","Collator","caseSensitive","diacriticSensitive","locale","sensitivity","collator","Intl","usage","compare","lhs","rhs","resolvedLocale","resolvedOptions","FormattedSection","text","image","scale","fontStack","textColor","Formatted","sections","fromString","unformatted","isEmpty","section","factory","join","serialize","serialized","push","ResolvedImage","available","validateRGBA","isValue","mixed","item","typeOf","String","JSON","stringify","Literal","args","context","error","expectedType","evaluate","eachChild","outputDefined","RuntimeError","toJSON","types","number","boolean","object","Assertion","floor","parsed","ctx","fn","every","arg","FormatExpression","firstArg","nextTokenMayBeObject","lastExpression","content","evaluateSection","evaluatedContent","ImageExpression","evaluatedImageName","availableImages","Coercion","Boolean","c","parseColor","num","Number","isNaN","valueToString","child","geometryTypes","EvaluationContext","globals","feature","featureState","formattedSection","_parseColorCache","canonical","geometryType","geometry","canonicalID","cached","CompoundExpression","_evaluate","op","definition","definitions","availableOverloads","overloads","filter","signature","signatureContext","ParsingContext","registry","scope","parsedArgs","argParseFailed","params","errors","signatures","stringifySignature","actualTypes","register","CollatorExpression","EXTENT","updateBBox","bbox","min","max","mercatorXfromLng","lng","mercatorYfromLat","lat","PI","log","tan","boxWithinBox","bbox1","bbox2","getTileCoordinates","p","y","tilesAtZoom","pow","z","onBoundary","p1","p2","x1","y1","x2","y2","rayIntersect","pointWithinPolygon","point","rings","inside","len","ring","j","len2","pointWithinPolygons","polygons","perp","v1","v2","twoSided","q1","q2","x3","y3","det1","det2","lineIntersectLine","d","vectorP","vectorQ","lineIntersectPolygon","polygon","lineStringWithinPolygon","line","lineStringWithinPolygons","getTilePolygon","getTilePolygons","updatePoint","polyBBox","worldSize","halfWorldSize","shift","resetBBox","Infinity","getTilePoints","pointBBox","shifts","tilePoints","points","getTileLines","lineBBox","tileLines","tileLine","pointsWithinPolygons","polygonGeometry","tilePolygon","tilePolygons","linesWithinPolygons","Within","geojson","geometries","features","isFeatureConstant","e","test","isStateConstant","isGlobalPropertyConstant","Var","boundExpression","part","expr","index","_parse","annotate","typeAnnotation","Expr","actual","isConstant","ec","isTypeAnnotation","childrenConstant","findStopLessThanOrEqualTo","lastIndex","lowerIndex","upperIndex","currentIndex","currentValue","nextValue","Step","labels","outputs","label","outputType","labelKey","valueKey","stopCount","out","color","Xn","Yn","Zn","t0","t1","t2","t3","deg2rad","rad2deg","xyz2lab","lab2xyz","xyz2rgb","rgb2xyz","rgbToLab","rgbColor","l","alpha","labToRgb","labColor","interpolateLab","interpolateNumber","rgbToHcl","h","atan2","sqrt","hclToRgb","hclColor","cos","sin","interpolateHue","interpolateHcl","lab","forward","interpolate","hcl","Interpolate","operator","interpolation","interpolationFactor","lower","upper","exponentialInterpolation","base","controlPoints","ub","UnitBezier","solve","slice","rest","outputLower","outputUpper","toLowerCase","lowerValue","upperValue","difference","progress","Coalesce","needsAnnotation","argCount","requestedImageName","Let","binding","At","In","needle","haystack","IndexOf","fromIndex","Match","inputType","cases","otherwise","labelContext","abs","MAX_SAFE_INTEGER","sortedLabels","sort","groupedByOutput","outputLookup","outputIndex","coerceLabel","Case","branches","Slice","beginIndex","endIndex","isComparableType","eq","neq","lt","gt","lteq","gteq","eqCollate","neqCollate","ltCollate","gtCollate","lteqCollate","gteqCollate","makeComparison","compareBasic","compareWithCollator","isOrderComparison","hasUntypedArgument","Comparison","rt","Equals","NotEquals","LessThan","GreaterThan","LessThanOrEqual","GreaterThanOrEqual","NumberFormat","currency","minFractionDigits","maxFractionDigits","minimumFractionDigits","maximumFractionDigits","Length","expressions","v","binarySearch","m","varargs","typeToString","zoom","heatmapDensity","lineProgress","accumulated","LN2","E","n","LN10","asin","acos","atan","ceil","isSupportedScript","toUpperCase","success","supportsPropertyExpression","spec","supportsZoomExpression","parameters","supportsInterpolation","interpolated","getType","val","identityFunction","createFunction","propertySpec","isColor","zoomAndFeatureDependent","featureDependent","zoomDependent","extend","default","colorSpace","colorSpaces","innerFun","hashedStops","categoricalKeyType","evaluateExponentialFunction","evaluateIntervalFunction","evaluateCategoricalFunction","create","evaluateIdentityFunction","featureFunctions","zoomStops","featureFunctionStops","interpolationType","bind","_","coalesce","keyType","evaluated","interp","colorspace","evaluatedLower","apply","evaluatedUpper","values","StyleExpression","_warningHistory","_evaluator","_defaultValue","getDefaultValue","_enumValues","evaluateWithoutErrorHandling","console","warn","isExpression","createExpression","parser","getExpectedType","ZoomConstantExpression","_styleExpression","isStateDependent","ZoomDependentExpression","createPropertyExpression","isZoomConstant","zoomCurve","findZoomCurve","StylePropertyFunction","specification","_parameters","_specification","deserialize","normalizePropertyExpression","err","constant","childResult","enum","formatted","resolvedImage","convertLiteral","convertFunction","convertIdentityFunction","tokens","convertTokenString","convertZoomAndPropertyFunction","convertZoomFunction","convertPropertyFunction","getInterpolateOperator","featureFunctionParameters","functionType","getFunctionType","appendStopPair","fixupDegenerateStepCurve","getFallback","defaultValue","isStep","curve","re","pos","match","exec","literal","isExpressionFilter","f","filterSpec","createFilter","needGeometry","convertFilter","compiled","geometryNeeded","globalProperties","converted","convertComparisonOp","convertNegation","convertDisjunctionOp","convertInOp","convertHasOp","filters","_convertFilter","expectedTypes","children","typechecks","runtimeTypeChecks","conditions","negate","uniformTypes","uniqueValues","migrated","migrateToV8","migrateToExpressions","styleIDs","sourceIDs","compositedSourceLayers","compositeID","deref","refProperties","derefLayers","ref","deepEqual","operations","setStyle","addLayer","removeLayer","setPaintProperty","setLayoutProperty","setFilter","addSource","removeSource","setGeoJSONSourceData","setLayerZoomRange","setLayerProperty","setCenter","setZoom","setBearing","setPitch","setSprite","setGlyphs","setTransition","setLight","sourceId","after","commands","command","sourcesRemoved","updateSource","canUpdateGeoJSON","before","prop","hasOwnProperty","isEqual","diffSources","data","diffLayerPropertyChanges","layerId","klass","pluckId","indexById","group","diffLayers","beforeOrder","afterOrder","beforeIndex","reduce","afterIndex","tracker","clean","beforeLayer","afterLayer","insertBeforeLayerId","lastIndexOf","minzoom","maxzoom","diffStyles","center","bearing","pitch","sprite","transition","light","removeOrAddSourceCommands","beforeLayers","ValidationError","identifier","__line__","parseInt","validateConstants","unbundle","valueOf","deepUnbundle","unbundledValue","validateObject","elementSpecs","valueSpec","elementValidators","objectElementValidators","styleSpec","objectKey","elementSpecKey","elementSpec","validateElement","validateSpec","required","validateArray","arraySpec","validateArrayElement","arrayElementValidator","validate","arrayElementSpec","$version","function","arrayIndex","validateNumber","minimum","maximum","validateFunction","functionValueSpec","stopKeyType","stopDomainValues","previousStopDomainValue","previousStopDomainZoom","isZoomFunction","isPropertyFunction","isZoomAndPropertyFunction","validateFunctionStops","validateFunctionDefault","validateFunctionStop","validateStopDomainValue","reportValue","isFinite","validateExpression","expressionContext","expressionObj","propertyKey","validateBoolean","validateColor","validateEnum","validateFilter","validateNonExpressionFilter","filter_operator","geometry_type","validateProperty","layerSpec","layerType","transitionMatch","tokenMatch","validatePaintProperty","validateLayoutProperty","validateLayer","otherLayer","sourceType","lineMetrics","validateString","promoteId","validatePromoteId","validateSource","replace","source_geojson","cluster","clusterProperties","reduceExpr","mapExpr","source_video","source_image","validateLight","lightSpec","rootType","validateFormatted","validateImage","VALIDATORS","valid","validateStyleMin","latestStyleSpec","validateGlyphsURL","sortErrors","wrapCleanErrors","paintProperty","layoutProperty","require","readStyle","Buffer","jsonlint","validateStyle","v8","SUPPORTED_SPEC_VERSION","MAX_SOURCES_IN_STYLE","isValid","regex","getSourceCount","getAllowedKeyErrors","allowed","Set","getSourceErrors","sourceKeys","sourceUrlPattern","getSourcesErrors","count","sourceErrors","getRootErrors","specKeys","optionalRootProperties","allowedKeyErrors","glyphUrlPattern","spriteUrlPattern","visibilityPattern","visibility","validateMapboxApiSupported","styleFunction","visit","latest"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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e;EAAA,6BAQfG,uBARe;EAAA,2BASfK,qBATe;EAAA,CAAnBhkB,CAlFA;AA8FAA,MAAMm0B,aAAA,GAAgB;EAAA,qBAClBtP,eADkB;EAAA,oBAElBnE,cAFkB;EAAA,gBAGlB1d,YAHkB;EAAA,CAAtBhD,CA9FA;AAoGAA,MAAMo0B,KAAA,GAAQ;EAAA,gBAAC3yB,UAAD;EAAA,eAAaI,SAAb;EAAA,kBAAwBC,YAAxB;EAAA,CAAd9B,CApGA;AAsGA,AAoBA+tB,eAAA,CAAS7hB,MAAT,GAAkB6hB,aAAlB,CA1HA;AA2HAA,eAAA,CAASsG,MAAT,GAAkBtG,aAAlB;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/mapbox-gl/src/style-spec/empty.js b/node_modules/mapbox-gl/src/style-spec/empty.js new file mode 100644 index 0000000000000000000000000000000000000000..e3db069f92d9b7670bae7428fb6ad72c698bbc39 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/empty.js @@ -0,0 +1,29 @@ +import latest from './reference/latest'; + +export default function emptyStyle() { + const style = {}; + + const version = latest['$version']; + for (const styleKey in latest['$root']) { + const spec = latest['$root'][styleKey]; + + if (spec.required) { + let value = null; + if (styleKey === 'version') { + value = version; + } else { + if (spec.type === 'array') { + value = []; + } else { + value = {}; + } + } + + if (value != null) { + style[styleKey] = value; + } + } + } + + return style; +} diff --git a/node_modules/mapbox-gl/src/style-spec/error/parsing_error.js b/node_modules/mapbox-gl/src/style-spec/error/parsing_error.js new file mode 100644 index 0000000000000000000000000000000000000000..8ddb923e2b3dbbc5f2e42e137e384eb568327ac1 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/error/parsing_error.js @@ -0,0 +1,16 @@ +// @flow + +// Note: Do not inherit from Error. It breaks when transpiling to ES5. + +export default class ParsingError { + message: string; + error: Error; + line: number; + + constructor(error: Error) { + this.error = error; + this.message = error.message; + const match = error.message.match(/line (\d+)/); + this.line = match ? parseInt(match[1], 10) : 0; + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/error/validation_error.js b/node_modules/mapbox-gl/src/style-spec/error/validation_error.js new file mode 100644 index 0000000000000000000000000000000000000000..9b90c2f98003a149d36149ca94f4d3944cb28387 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/error/validation_error.js @@ -0,0 +1,18 @@ +// @flow + +// Note: Do not inherit from Error. It breaks when transpiling to ES5. + +export default class ValidationError { + message: string; + identifier: ?string; + line: ?number; + + constructor(key: ?string, value: ?{ __line__: number }, message: string, identifier: ?string) { + this.message = (key ? `${key}: ` : '') + message; + if (identifier) this.identifier = identifier; + + if (value !== null && value !== undefined && value.__line__) { + this.line = value.__line__; + } + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/expression/compound_expression.js b/node_modules/mapbox-gl/src/style-spec/expression/compound_expression.js new file mode 100644 index 0000000000000000000000000000000000000000..e948b0b7689e6c6c3587b1d91a025626106ee6c7 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/compound_expression.js @@ -0,0 +1,162 @@ +// @flow + +import {toString} from './types'; + +import ParsingContext from './parsing_context'; +import EvaluationContext from './evaluation_context'; +import assert from 'assert'; + +import type {Expression, ExpressionRegistry} from './expression'; +import type {Type} from './types'; +import type {Value} from './values'; + +export type Varargs = {| type: Type |}; +type Signature = Array | Varargs; +type Evaluate = (EvaluationContext, Array) => Value; +type Definition = [Type, Signature, Evaluate] | + {|type: Type, overloads: Array<[Signature, Evaluate]>|}; + +class CompoundExpression implements Expression { + name: string; + type: Type; + _evaluate: Evaluate; + args: Array; + + static definitions: {[_: string]: Definition }; + + constructor(name: string, type: Type, evaluate: Evaluate, args: Array) { + this.name = name; + this.type = type; + this._evaluate = evaluate; + this.args = args; + } + + evaluate(ctx: EvaluationContext) { + return this._evaluate(ctx, this.args); + } + + eachChild(fn: (_: Expression) => void) { + this.args.forEach(fn); + } + + outputDefined() { + return false; + } + + serialize(): Array { + return [this.name].concat(this.args.map(arg => arg.serialize())); + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + const op: string = (args[0]: any); + const definition = CompoundExpression.definitions[op]; + if (!definition) { + return context.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0); + } + + // Now check argument types against each signature + const type = Array.isArray(definition) ? + definition[0] : definition.type; + + const availableOverloads = Array.isArray(definition) ? + [[definition[1], definition[2]]] : + definition.overloads; + + const overloads = availableOverloads.filter(([signature]) => ( + !Array.isArray(signature) || // varags + signature.length === args.length - 1 // correct param count + )); + + let signatureContext: ParsingContext = (null: any); + + for (const [params, evaluate] of overloads) { + // Use a fresh context for each attempted signature so that, if + // we eventually succeed, we haven't polluted `context.errors`. + signatureContext = new ParsingContext(context.registry, context.path, null, context.scope); + + // First parse all the args, potentially coercing to the + // types expected by this overload. + const parsedArgs: Array = []; + let argParseFailed = false; + for (let i = 1; i < args.length; i++) { + const arg = args[i]; + const expectedType = Array.isArray(params) ? + params[i - 1] : + params.type; + + const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType); + if (!parsed) { + argParseFailed = true; + break; + } + parsedArgs.push(parsed); + } + if (argParseFailed) { + // Couldn't coerce args of this overload to expected type, move + // on to next one. + continue; + } + + if (Array.isArray(params)) { + if (params.length !== parsedArgs.length) { + signatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`); + continue; + } + } + + for (let i = 0; i < parsedArgs.length; i++) { + const expected = Array.isArray(params) ? params[i] : params.type; + const arg = parsedArgs[i]; + signatureContext.concat(i + 1).checkSubtype(expected, arg.type); + } + + if (signatureContext.errors.length === 0) { + return new CompoundExpression(op, type, evaluate, parsedArgs); + } + } + + assert(!signatureContext || signatureContext.errors.length > 0); + + if (overloads.length === 1) { + context.errors.push(...signatureContext.errors); + } else { + const expected = overloads.length ? overloads : availableOverloads; + const signatures = expected + .map(([params]) => stringifySignature(params)) + .join(' | '); + + const actualTypes = []; + // For error message, re-parse arguments without trying to + // apply any coercions + for (let i = 1; i < args.length; i++) { + const parsed = context.parse(args[i], 1 + actualTypes.length); + if (!parsed) return null; + actualTypes.push(toString(parsed.type)); + } + context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(', ')}) instead.`); + } + + return null; + } + + static register( + registry: ExpressionRegistry, + definitions: {[_: string]: Definition } + ) { + assert(!CompoundExpression.definitions); + CompoundExpression.definitions = definitions; + for (const name in definitions) { + registry[name] = CompoundExpression; + } + } +} + +function stringifySignature(signature: Signature): string { + if (Array.isArray(signature)) { + return `(${signature.map(toString).join(', ')})`; + } else { + return `(${toString(signature.type)}...)`; + } +} + +export default CompoundExpression; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/assertion.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/assertion.js new file mode 100644 index 0000000000000000000000000000000000000000..cfadac6d5d5eadca43c7318a6da310acd27da5a2 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/assertion.js @@ -0,0 +1,130 @@ +// @flow + +import assert from 'assert'; + +import { + ObjectType, + ValueType, + StringType, + NumberType, + BooleanType, + checkSubtype, + toString, + array +} from '../types'; +import RuntimeError from '../runtime_error'; +import {typeOf} from '../values'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +const types = { + string: StringType, + number: NumberType, + boolean: BooleanType, + object: ObjectType +}; + +class Assertion implements Expression { + type: Type; + args: Array; + + constructor(type: Type, args: Array) { + this.type = type; + this.args = args; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + if (args.length < 2) + return context.error(`Expected at least one argument.`); + + let i = 1; + let type; + + const name: string = (args[0]: any); + if (name === 'array') { + let itemType; + if (args.length > 2) { + const type = args[1]; + if (typeof type !== 'string' || !(type in types) || type === 'object') + return context.error('The item type argument of "array" must be one of string, number, boolean', 1); + itemType = types[type]; + i++; + } else { + itemType = ValueType; + } + + let N; + if (args.length > 3) { + if (args[2] !== null && + (typeof args[2] !== 'number' || + args[2] < 0 || + args[2] !== Math.floor(args[2])) + ) { + return context.error('The length argument to "array" must be a positive integer literal', 2); + } + N = args[2]; + i++; + } + + type = array(itemType, N); + } else { + assert(types[name], name); + type = types[name]; + } + + const parsed = []; + for (; i < args.length; i++) { + const input = context.parse(args[i], i, ValueType); + if (!input) return null; + parsed.push(input); + } + + return new Assertion(type, parsed); + } + + evaluate(ctx: EvaluationContext) { + for (let i = 0; i < this.args.length; i++) { + const value = this.args[i].evaluate(ctx); + const error = checkSubtype(this.type, typeOf(value)); + if (!error) { + return value; + } else if (i === this.args.length - 1) { + throw new RuntimeError(`Expected value to be of type ${toString(this.type)}, but found ${toString(typeOf(value))} instead.`); + } + } + + assert(false); + return null; + } + + eachChild(fn: (_: Expression) => void) { + this.args.forEach(fn); + } + + outputDefined(): boolean { + return this.args.every(arg => arg.outputDefined()); + } + + serialize(): Array { + const type = this.type; + const serialized = [type.kind]; + if (type.kind === 'array') { + const itemType = type.itemType; + if (itemType.kind === 'string' || + itemType.kind === 'number' || + itemType.kind === 'boolean') { + serialized.push(itemType.kind); + const N = type.N; + if (typeof N === 'number' || this.args.length > 1) { + serialized.push(N); + } + } + } + return serialized.concat(this.args.map(arg => arg.serialize())); + } +} + +export default Assertion; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/at.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/at.js new file mode 100644 index 0000000000000000000000000000000000000000..e777f43355ed77c4832fc22d9dc3d4069490f230 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/at.js @@ -0,0 +1,70 @@ +// @flow + +import {array, ValueType, NumberType} from '../types'; + +import RuntimeError from '../runtime_error'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type, ArrayType} from '../types'; +import type {Value} from '../values'; + +class At implements Expression { + type: Type; + index: Expression; + input: Expression; + + constructor(type: Type, index: Expression, input: Expression) { + this.type = type; + this.index = index; + this.input = input; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length !== 3) + return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`); + + const index = context.parse(args[1], 1, NumberType); + const input = context.parse(args[2], 2, array(context.expectedType || ValueType)); + + if (!index || !input) return null; + + const t: ArrayType = (input.type: any); + return new At(t.itemType, index, input); + } + + evaluate(ctx: EvaluationContext) { + const index = ((this.index.evaluate(ctx): any): number); + const array = ((this.input.evaluate(ctx): any): Array); + + if (index < 0) { + throw new RuntimeError(`Array index out of bounds: ${index} < 0.`); + } + + if (index >= array.length) { + throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`); + } + + if (index !== Math.floor(index)) { + throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`); + } + + return array[index]; + } + + eachChild(fn: (_: Expression) => void) { + fn(this.index); + fn(this.input); + } + + outputDefined() { + return false; + } + + serialize() { + return ["at", this.index.serialize(), this.input.serialize()]; + } +} + +export default At; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/case.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/case.js new file mode 100644 index 0000000000000000000000000000000000000000..c750aed5ed7d6c59ff18d4bbb9f00298f6099df3 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/case.js @@ -0,0 +1,85 @@ +// @flow + +import assert from 'assert'; + +import {BooleanType} from '../types'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +type Branches = Array<[Expression, Expression]>; + +class Case implements Expression { + type: Type; + + branches: Branches; + otherwise: Expression; + + constructor(type: Type, branches: Branches, otherwise: Expression) { + this.type = type; + this.branches = branches; + this.otherwise = otherwise; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length < 4) + return context.error(`Expected at least 3 arguments, but found only ${args.length - 1}.`); + if (args.length % 2 !== 0) + return context.error(`Expected an odd number of arguments.`); + + let outputType: ?Type; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + + const branches = []; + for (let i = 1; i < args.length - 1; i += 2) { + const test = context.parse(args[i], i, BooleanType); + if (!test) return null; + + const result = context.parse(args[i + 1], i + 1, outputType); + if (!result) return null; + + branches.push([test, result]); + + outputType = outputType || result.type; + } + + const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) return null; + + assert(outputType); + return new Case((outputType: any), branches, otherwise); + } + + evaluate(ctx: EvaluationContext) { + for (const [test, expression] of this.branches) { + if (test.evaluate(ctx)) { + return expression.evaluate(ctx); + } + } + return this.otherwise.evaluate(ctx); + } + + eachChild(fn: (_: Expression) => void) { + for (const [test, expression] of this.branches) { + fn(test); + fn(expression); + } + fn(this.otherwise); + } + + outputDefined(): boolean { + return this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined(); + } + + serialize() { + const serialized = ["case"]; + this.eachChild(child => { serialized.push(child.serialize()); }); + return serialized; + } +} + +export default Case; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/coalesce.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/coalesce.js new file mode 100644 index 0000000000000000000000000000000000000000..9cfce9e987d2cdc3d6bbc2b8a132c0bc84a22120 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/coalesce.js @@ -0,0 +1,93 @@ +// @flow + +import assert from 'assert'; + +import {checkSubtype, ValueType} from '../types'; +import ResolvedImage from '../types/resolved_image'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +class Coalesce implements Expression { + type: Type; + args: Array; + + constructor(type: Type, args: Array) { + this.type = type; + this.args = args; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length < 2) { + return context.error("Expectected at least one argument."); + } + let outputType: Type = (null: any); + const expectedType = context.expectedType; + if (expectedType && expectedType.kind !== 'value') { + outputType = expectedType; + } + const parsedArgs = []; + + for (const arg of args.slice(1)) { + const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, {typeAnnotation: 'omit'}); + if (!parsed) return null; + outputType = outputType || parsed.type; + parsedArgs.push(parsed); + } + assert(outputType); + + // Above, we parse arguments without inferred type annotation so that + // they don't produce a runtime error for `null` input, which would + // preempt the desired null-coalescing behavior. + // Thus, if any of our arguments would have needed an annotation, we + // need to wrap the enclosing coalesce expression with it instead. + const needsAnnotation = expectedType && + parsedArgs.some(arg => checkSubtype(expectedType, arg.type)); + + return needsAnnotation ? + new Coalesce(ValueType, parsedArgs) : + new Coalesce((outputType: any), parsedArgs); + } + + evaluate(ctx: EvaluationContext) { + let result = null; + let argCount = 0; + let requestedImageName; + for (const arg of this.args) { + argCount++; + result = arg.evaluate(ctx); + // we need to keep track of the first requested image in a coalesce statement + // if coalesce can't find a valid image, we return the first image name so styleimagemissing can fire + if (result && result instanceof ResolvedImage && !result.available) { + if (!requestedImageName) { + requestedImageName = result.name; + } + result = null; + if (argCount === this.args.length) { + result = requestedImageName; + } + } + + if (result !== null) break; + } + return result; + } + + eachChild(fn: (_: Expression) => void) { + this.args.forEach(fn); + } + + outputDefined(): boolean { + return this.args.every(arg => arg.outputDefined()); + } + + serialize() { + const serialized = ["coalesce"]; + this.eachChild(child => { serialized.push(child.serialize()); }); + return serialized; + } +} + +export default Coalesce; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/coercion.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/coercion.js new file mode 100644 index 0000000000000000000000000000000000000000..3eb46f776623f5744e052b36281439995106c9d1 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/coercion.js @@ -0,0 +1,133 @@ +// @flow + +import assert from 'assert'; + +import {BooleanType, ColorType, NumberType, StringType, ValueType} from '../types'; +import {Color, toString as valueToString, validateRGBA} from '../values'; +import RuntimeError from '../runtime_error'; +import Formatted from '../types/formatted'; +import FormatExpression from '../definitions/format'; +import ImageExpression from '../definitions/image'; +import ResolvedImage from '../types/resolved_image'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +const types = { + 'to-boolean': BooleanType, + 'to-color': ColorType, + 'to-number': NumberType, + 'to-string': StringType +}; + +/** + * Special form for error-coalescing coercion expressions "to-number", + * "to-color". Since these coercions can fail at runtime, they accept multiple + * arguments, only evaluating one at a time until one succeeds. + * + * @private + */ +class Coercion implements Expression { + type: Type; + args: Array; + + constructor(type: Type, args: Array) { + this.type = type; + this.args = args; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + if (args.length < 2) + return context.error(`Expected at least one argument.`); + + const name: string = (args[0]: any); + assert(types[name], name); + + if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2) + return context.error(`Expected one argument.`); + + const type = types[name]; + + const parsed = []; + for (let i = 1; i < args.length; i++) { + const input = context.parse(args[i], i, ValueType); + if (!input) return null; + parsed.push(input); + } + + return new Coercion(type, parsed); + } + + evaluate(ctx: EvaluationContext) { + if (this.type.kind === 'boolean') { + return Boolean(this.args[0].evaluate(ctx)); + } else if (this.type.kind === 'color') { + let input; + let error; + for (const arg of this.args) { + input = arg.evaluate(ctx); + error = null; + if (input instanceof Color) { + return input; + } else if (typeof input === 'string') { + const c = ctx.parseColor(input); + if (c) return c; + } else if (Array.isArray(input)) { + if (input.length < 3 || input.length > 4) { + error = `Invalid rbga value ${JSON.stringify(input)}: expected an array containing either three or four numeric values.`; + } else { + error = validateRGBA(input[0], input[1], input[2], input[3]); + } + if (!error) { + return new Color((input[0]: any) / 255, (input[1]: any) / 255, (input[2]: any) / 255, (input[3]: any)); + } + } + } + throw new RuntimeError(error || `Could not parse color from value '${typeof input === 'string' ? input : String(JSON.stringify(input))}'`); + } else if (this.type.kind === 'number') { + let value = null; + for (const arg of this.args) { + value = arg.evaluate(ctx); + if (value === null) return 0; + const num = Number(value); + if (isNaN(num)) continue; + return num; + } + throw new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`); + } else if (this.type.kind === 'formatted') { + // There is no explicit 'to-formatted' but this coercion can be implicitly + // created by properties that expect the 'formatted' type. + return Formatted.fromString(valueToString(this.args[0].evaluate(ctx))); + } else if (this.type.kind === 'resolvedImage') { + return ResolvedImage.fromString(valueToString(this.args[0].evaluate(ctx))); + } else { + return valueToString(this.args[0].evaluate(ctx)); + } + } + + eachChild(fn: (_: Expression) => void) { + this.args.forEach(fn); + } + + outputDefined(): boolean { + return this.args.every(arg => arg.outputDefined()); + } + + serialize() { + if (this.type.kind === 'formatted') { + return new FormatExpression([{content: this.args[0], scale: null, font: null, textColor: null}]).serialize(); + } + + if (this.type.kind === 'resolvedImage') { + return new ImageExpression(this.args[0]).serialize(); + } + + const serialized = [`to-${this.type.kind}`]; + this.eachChild(child => { serialized.push(child.serialize()); }); + return serialized; + } +} + +export default Coercion; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/collator.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/collator.js new file mode 100644 index 0000000000000000000000000000000000000000..379d5d6047e5132039036d567108e0867ae7c4b1 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/collator.js @@ -0,0 +1,78 @@ +// @flow + +import {StringType, BooleanType, CollatorType} from '../types'; +import Collator from '../types/collator'; + +import type {Expression} from '../expression'; +import type EvaluationContext from '../evaluation_context'; +import type ParsingContext from '../parsing_context'; +import type {Type} from '../types'; + +export default class CollatorExpression implements Expression { + type: Type; + caseSensitive: Expression; + diacriticSensitive: Expression; + locale: Expression | null; + + constructor(caseSensitive: Expression, diacriticSensitive: Expression, locale: Expression | null) { + this.type = CollatorType; + this.locale = locale; + this.caseSensitive = caseSensitive; + this.diacriticSensitive = diacriticSensitive; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + if (args.length !== 2) + return context.error(`Expected one argument.`); + + const options = (args[1]: any); + if (typeof options !== "object" || Array.isArray(options)) + return context.error(`Collator options argument must be an object.`); + + const caseSensitive = context.parse( + options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType); + if (!caseSensitive) return null; + + const diacriticSensitive = context.parse( + options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType); + if (!diacriticSensitive) return null; + + let locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) return null; + } + + return new CollatorExpression(caseSensitive, diacriticSensitive, locale); + } + + evaluate(ctx: EvaluationContext) { + return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null); + } + + eachChild(fn: (_: Expression) => void) { + fn(this.caseSensitive); + fn(this.diacriticSensitive); + if (this.locale) { + fn(this.locale); + } + } + + outputDefined() { + // Technically the set of possible outputs is the combinatoric set of Collators produced + // by all possible outputs of locale/caseSensitive/diacriticSensitive + // But for the primary use of Collators in comparison operators, we ignore the Collator's + // possible outputs anyway, so we can get away with leaving this false for now. + return false; + } + + serialize() { + const options = {}; + options['case-sensitive'] = this.caseSensitive.serialize(); + options['diacritic-sensitive'] = this.diacriticSensitive.serialize(); + if (this.locale) { + options['locale'] = this.locale.serialize(); + } + return ["collator", options]; + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/comparison.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/comparison.js new file mode 100644 index 0000000000000000000000000000000000000000..210df55ac7ae9ee7663158967e44b7f8ca02b256 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/comparison.js @@ -0,0 +1,184 @@ +// @flow + +import {toString, ValueType, BooleanType, CollatorType} from '../types'; +import Assertion from './assertion'; +import {typeOf} from '../values'; +import RuntimeError from '../runtime_error'; + +import type {Expression} from '../expression'; +import type EvaluationContext from '../evaluation_context'; +import type ParsingContext from '../parsing_context'; +import type {Type} from '../types'; + +type ComparisonOperator = '==' | '!=' | '<' | '>' | '<=' | '>=' ; + +function isComparableType(op: ComparisonOperator, type: Type) { + if (op === '==' || op === '!=') { + // equality operator + return type.kind === 'boolean' || + type.kind === 'string' || + type.kind === 'number' || + type.kind === 'null' || + type.kind === 'value'; + } else { + // ordering operator + return type.kind === 'string' || + type.kind === 'number' || + type.kind === 'value'; + } +} + +function eq(ctx, a, b) { return a === b; } +function neq(ctx, a, b) { return a !== b; } +function lt(ctx, a, b) { return a < b; } +function gt(ctx, a, b) { return a > b; } +function lteq(ctx, a, b) { return a <= b; } +function gteq(ctx, a, b) { return a >= b; } + +function eqCollate(ctx, a, b, c) { return c.compare(a, b) === 0; } +function neqCollate(ctx, a, b, c) { return !eqCollate(ctx, a, b, c); } +function ltCollate(ctx, a, b, c) { return c.compare(a, b) < 0; } +function gtCollate(ctx, a, b, c) { return c.compare(a, b) > 0; } +function lteqCollate(ctx, a, b, c) { return c.compare(a, b) <= 0; } +function gteqCollate(ctx, a, b, c) { return c.compare(a, b) >= 0; } + +/** + * Special form for comparison operators, implementing the signatures: + * - (T, T, ?Collator) => boolean + * - (T, value, ?Collator) => boolean + * - (value, T, ?Collator) => boolean + * + * For inequalities, T must be either value, string, or number. For ==/!=, it + * can also be boolean or null. + * + * Equality semantics are equivalent to Javascript's strict equality (===/!==) + * -- i.e., when the arguments' types don't match, == evaluates to false, != to + * true. + * + * When types don't match in an ordering comparison, a runtime error is thrown. + * + * @private + */ +function makeComparison(op: ComparisonOperator, compareBasic, compareWithCollator) { + const isOrderComparison = op !== '==' && op !== '!='; + + return class Comparison implements Expression { + type: Type; + lhs: Expression; + rhs: Expression; + collator: ?Expression; + hasUntypedArgument: boolean; + + constructor(lhs: Expression, rhs: Expression, collator: ?Expression) { + this.type = BooleanType; + this.lhs = lhs; + this.rhs = rhs; + this.collator = collator; + this.hasUntypedArgument = lhs.type.kind === 'value' || rhs.type.kind === 'value'; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + if (args.length !== 3 && args.length !== 4) + return context.error(`Expected two or three arguments.`); + + const op: ComparisonOperator = (args[0]: any); + + let lhs = context.parse(args[1], 1, ValueType); + if (!lhs) return null; + if (!isComparableType(op, lhs.type)) { + return context.concat(1).error(`"${op}" comparisons are not supported for type '${toString(lhs.type)}'.`); + } + let rhs = context.parse(args[2], 2, ValueType); + if (!rhs) return null; + if (!isComparableType(op, rhs.type)) { + return context.concat(2).error(`"${op}" comparisons are not supported for type '${toString(rhs.type)}'.`); + } + + if ( + lhs.type.kind !== rhs.type.kind && + lhs.type.kind !== 'value' && + rhs.type.kind !== 'value' + ) { + return context.error(`Cannot compare types '${toString(lhs.type)}' and '${toString(rhs.type)}'.`); + } + + if (isOrderComparison) { + // typing rules specific to less/greater than operators + if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') { + // (value, T) + lhs = new Assertion(rhs.type, [lhs]); + } else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') { + // (T, value) + rhs = new Assertion(lhs.type, [rhs]); + } + } + + let collator = null; + if (args.length === 4) { + if ( + lhs.type.kind !== 'string' && + rhs.type.kind !== 'string' && + lhs.type.kind !== 'value' && + rhs.type.kind !== 'value' + ) { + return context.error(`Cannot use collator to compare non-string types.`); + } + collator = context.parse(args[3], 3, CollatorType); + if (!collator) return null; + } + + return new Comparison(lhs, rhs, collator); + } + + evaluate(ctx: EvaluationContext) { + const lhs = this.lhs.evaluate(ctx); + const rhs = this.rhs.evaluate(ctx); + + if (isOrderComparison && this.hasUntypedArgument) { + const lt = typeOf(lhs); + const rt = typeOf(rhs); + // check that type is string or number, and equal + if (lt.kind !== rt.kind || !(lt.kind === 'string' || lt.kind === 'number')) { + throw new RuntimeError(`Expected arguments for "${op}" to be (string, string) or (number, number), but found (${lt.kind}, ${rt.kind}) instead.`); + } + } + + if (this.collator && !isOrderComparison && this.hasUntypedArgument) { + const lt = typeOf(lhs); + const rt = typeOf(rhs); + if (lt.kind !== 'string' || rt.kind !== 'string') { + return compareBasic(ctx, lhs, rhs); + } + } + + return this.collator ? + compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) : + compareBasic(ctx, lhs, rhs); + } + + eachChild(fn: (_: Expression) => void) { + fn(this.lhs); + fn(this.rhs); + if (this.collator) { + fn(this.collator); + } + } + + outputDefined(): boolean { + return true; + } + + serialize() { + const serialized = [op]; + this.eachChild(child => { serialized.push(child.serialize()); }); + return serialized; + } + }; +} + +export const Equals = makeComparison('==', eq, eqCollate); +export const NotEquals = makeComparison('!=', neq, neqCollate); +export const LessThan = makeComparison('<', lt, ltCollate); +export const GreaterThan = makeComparison('>', gt, gtCollate); +export const LessThanOrEqual = makeComparison('<=', lteq, lteqCollate); +export const GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate); diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/format.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/format.js new file mode 100644 index 0000000000000000000000000000000000000000..a376cacff02fe195fcd583f341bb0ce027992ff0 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/format.js @@ -0,0 +1,144 @@ +// @flow + +import {NumberType, ValueType, FormattedType, array, StringType, ColorType, ResolvedImageType} from '../types'; +import Formatted, {FormattedSection} from '../types/formatted'; +import {toString, typeOf} from '../values'; + +import type {Expression} from '../expression'; +import type EvaluationContext from '../evaluation_context'; +import type ParsingContext from '../parsing_context'; +import type {Type} from '../types'; + +type FormattedSectionExpression = { + // Content of a section may be Image expression or other + // type of expression that is coercable to 'string'. + content: Expression, + scale: Expression | null; + font: Expression | null; + textColor: Expression | null; +} + +export default class FormatExpression implements Expression { + type: Type; + sections: Array; + + constructor(sections: Array) { + this.type = FormattedType; + this.sections = sections; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + if (args.length < 2) { + return context.error(`Expected at least one argument.`); + } + + const firstArg = args[1]; + if (!Array.isArray(firstArg) && typeof firstArg === 'object') { + return context.error(`First argument must be an image or text section.`); + } + + const sections: Array = []; + let nextTokenMayBeObject = false; + for (let i = 1; i <= args.length - 1; ++i) { + const arg = (args[i]: any); + + if (nextTokenMayBeObject && typeof arg === "object" && !Array.isArray(arg)) { + nextTokenMayBeObject = false; + + let scale = null; + if (arg['font-scale']) { + scale = context.parse(arg['font-scale'], 1, NumberType); + if (!scale) return null; + } + + let font = null; + if (arg['text-font']) { + font = context.parse(arg['text-font'], 1, array(StringType)); + if (!font) return null; + } + + let textColor = null; + if (arg['text-color']) { + textColor = context.parse(arg['text-color'], 1, ColorType); + if (!textColor) return null; + } + + const lastExpression = sections[sections.length - 1]; + lastExpression.scale = scale; + lastExpression.font = font; + lastExpression.textColor = textColor; + } else { + const content = context.parse(args[i], 1, ValueType); + if (!content) return null; + + const kind = content.type.kind; + if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage') + return context.error(`Formatted text type must be 'string', 'value', 'image' or 'null'.`); + + nextTokenMayBeObject = true; + sections.push({content, scale: null, font: null, textColor: null}); + } + } + + return new FormatExpression(sections); + } + + evaluate(ctx: EvaluationContext) { + const evaluateSection = section => { + const evaluatedContent = section.content.evaluate(ctx); + if (typeOf(evaluatedContent) === ResolvedImageType) { + return new FormattedSection('', evaluatedContent, null, null, null); + } + + return new FormattedSection( + toString(evaluatedContent), + null, + section.scale ? section.scale.evaluate(ctx) : null, + section.font ? section.font.evaluate(ctx).join(',') : null, + section.textColor ? section.textColor.evaluate(ctx) : null + ); + }; + + return new Formatted(this.sections.map(evaluateSection)); + } + + eachChild(fn: (_: Expression) => void) { + for (const section of this.sections) { + fn(section.content); + if (section.scale) { + fn(section.scale); + } + if (section.font) { + fn(section.font); + } + if (section.textColor) { + fn(section.textColor); + } + } + } + + outputDefined() { + // Technically the combinatoric set of all children + // Usually, this.text will be undefined anyway + return false; + } + + serialize() { + const serialized = ["format"]; + for (const section of this.sections) { + serialized.push(section.content.serialize()); + const options = {}; + if (section.scale) { + options['font-scale'] = section.scale.serialize(); + } + if (section.font) { + options['text-font'] = section.font.serialize(); + } + if (section.textColor) { + options['text-color'] = section.textColor.serialize(); + } + serialized.push(options); + } + return serialized; + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/image.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/image.js new file mode 100644 index 0000000000000000000000000000000000000000..8b73e1c79dc705135d118210650360b6f7b1b6f2 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/image.js @@ -0,0 +1,52 @@ +// @flow + +import {ResolvedImageType, StringType} from '../types'; +import ResolvedImage from '../types/resolved_image'; + +import type {Expression} from '../expression'; +import type EvaluationContext from '../evaluation_context'; +import type ParsingContext from '../parsing_context'; +import type {Type} from '../types'; + +export default class ImageExpression implements Expression { + type: Type; + input: Expression; + + constructor(input: Expression) { + this.type = ResolvedImageType; + this.input = input; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + if (args.length !== 2) { + return context.error(`Expected two arguments.`); + } + + const name = context.parse(args[1], 1, StringType); + if (!name) return context.error(`No image name provided.`); + + return new ImageExpression(name); + } + + evaluate(ctx: EvaluationContext) { + const evaluatedImageName = this.input.evaluate(ctx); + + const value = ResolvedImage.fromString(evaluatedImageName); + if (value && ctx.availableImages) value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1; + + return value; + } + + eachChild(fn: (_: Expression) => void) { + fn(this.input); + } + + outputDefined() { + // The output of image is determined by the list of available images in the evaluation context + return false; + } + + serialize() { + return ["image", this.input.serialize()]; + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/in.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/in.js new file mode 100644 index 0000000000000000000000000000000000000000..0e6681a5080e19d045ddb4a5a6d6bffa60d46a7f --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/in.js @@ -0,0 +1,72 @@ +// @flow + +import {BooleanType, StringType, ValueType, NullType, toString, NumberType, isValidType, isValidNativeType} from '../types'; +import RuntimeError from '../runtime_error'; +import {typeOf} from '../values'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +class In implements Expression { + type: Type; + needle: Expression; + haystack: Expression; + + constructor(needle: Expression, haystack: Expression) { + this.type = BooleanType; + this.needle = needle; + this.haystack = haystack; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length !== 3) { + return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`); + } + + const needle = context.parse(args[1], 1, ValueType); + + const haystack = context.parse(args[2], 2, ValueType); + + if (!needle || !haystack) return null; + + if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) { + return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString(needle.type)} instead`); + } + + return new In(needle, haystack); + } + + evaluate(ctx: EvaluationContext) { + const needle = (this.needle.evaluate(ctx): any); + const haystack = (this.haystack.evaluate(ctx): any); + + if (!haystack) return false; + + if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) { + throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString(typeOf(needle))} instead.`); + } + + if (!isValidNativeType(haystack, ['string', 'array'])) { + throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString(typeOf(haystack))} instead.`); + } + + return haystack.indexOf(needle) >= 0; + } + + eachChild(fn: (_: Expression) => void) { + fn(this.needle); + fn(this.haystack); + } + + outputDefined() { + return true; + } + + serialize() { + return ["in", this.needle.serialize(), this.haystack.serialize()]; + } +} + +export default In; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/index.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fcc1535c8bf33f5fe23b406cfa502b7dfc18e18d --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/index.js @@ -0,0 +1,565 @@ +// @flow + +import { + type Type, + NumberType, + StringType, + BooleanType, + ColorType, + ObjectType, + ValueType, + ErrorType, + CollatorType, + array, + toString as typeToString +} from '../types'; + +import {typeOf, Color, validateRGBA, toString as valueToString} from '../values'; +import CompoundExpression from '../compound_expression'; +import RuntimeError from '../runtime_error'; +import Let from './let'; +import Var from './var'; +import Literal from './literal'; +import Assertion from './assertion'; +import Coercion from './coercion'; +import At from './at'; +import In from './in'; +import IndexOf from './index_of'; +import Match from './match'; +import Case from './case'; +import Slice from './slice'; +import Step from './step'; +import Interpolate from './interpolate'; +import Coalesce from './coalesce'; +import { + Equals, + NotEquals, + LessThan, + GreaterThan, + LessThanOrEqual, + GreaterThanOrEqual +} from './comparison'; +import CollatorExpression from './collator'; +import NumberFormat from './number_format'; +import FormatExpression from './format'; +import ImageExpression from './image'; +import Length from './length'; +import Within from './within'; + +import type {Varargs} from '../compound_expression'; +import type {ExpressionRegistry} from '../expression'; + +const expressions: ExpressionRegistry = { + // special forms + '==': Equals, + '!=': NotEquals, + '>': GreaterThan, + '<': LessThan, + '>=': GreaterThanOrEqual, + '<=': LessThanOrEqual, + 'array': Assertion, + 'at': At, + 'boolean': Assertion, + 'case': Case, + 'coalesce': Coalesce, + 'collator': CollatorExpression, + 'format': FormatExpression, + 'image': ImageExpression, + 'in': In, + 'index-of': IndexOf, + 'interpolate': Interpolate, + 'interpolate-hcl': Interpolate, + 'interpolate-lab': Interpolate, + 'length': Length, + 'let': Let, + 'literal': Literal, + 'match': Match, + 'number': Assertion, + 'number-format': NumberFormat, + 'object': Assertion, + 'slice': Slice, + 'step': Step, + 'string': Assertion, + 'to-boolean': Coercion, + 'to-color': Coercion, + 'to-number': Coercion, + 'to-string': Coercion, + 'var': Var, + 'within': Within +}; + +function rgba(ctx, [r, g, b, a]) { + r = r.evaluate(ctx); + g = g.evaluate(ctx); + b = b.evaluate(ctx); + const alpha = a ? a.evaluate(ctx) : 1; + const error = validateRGBA(r, g, b, alpha); + if (error) throw new RuntimeError(error); + return new Color(r / 255 * alpha, g / 255 * alpha, b / 255 * alpha, alpha); +} + +function has(key, obj) { + return key in obj; +} + +function get(key, obj) { + const v = obj[key]; + return typeof v === 'undefined' ? null : v; +} + +function binarySearch(v, a, i, j) { + while (i <= j) { + const m = (i + j) >> 1; + if (a[m] === v) + return true; + if (a[m] > v) + j = m - 1; + else + i = m + 1; + } + return false; +} + +function varargs(type: Type): Varargs { + return {type}; +} + +CompoundExpression.register(expressions, { + 'error': [ + ErrorType, + [StringType], + (ctx, [v]) => { throw new RuntimeError(v.evaluate(ctx)); } + ], + 'typeof': [ + StringType, + [ValueType], + (ctx, [v]) => typeToString(typeOf(v.evaluate(ctx))) + ], + 'to-rgba': [ + array(NumberType, 4), + [ColorType], + (ctx, [v]) => { + return v.evaluate(ctx).toArray(); + } + ], + 'rgb': [ + ColorType, + [NumberType, NumberType, NumberType], + rgba + ], + 'rgba': [ + ColorType, + [NumberType, NumberType, NumberType, NumberType], + rgba + ], + 'has': { + type: BooleanType, + overloads: [ + [ + [StringType], + (ctx, [key]) => has(key.evaluate(ctx), ctx.properties()) + ], [ + [StringType, ObjectType], + (ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx)) + ] + ] + }, + 'get': { + type: ValueType, + overloads: [ + [ + [StringType], + (ctx, [key]) => get(key.evaluate(ctx), ctx.properties()) + ], [ + [StringType, ObjectType], + (ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx)) + ] + ] + }, + 'feature-state': [ + ValueType, + [StringType], + (ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {}) + ], + 'properties': [ + ObjectType, + [], + (ctx) => ctx.properties() + ], + 'geometry-type': [ + StringType, + [], + (ctx) => ctx.geometryType() + ], + 'id': [ + ValueType, + [], + (ctx) => ctx.id() + ], + 'zoom': [ + NumberType, + [], + (ctx) => ctx.globals.zoom + ], + 'heatmap-density': [ + NumberType, + [], + (ctx) => ctx.globals.heatmapDensity || 0 + ], + 'line-progress': [ + NumberType, + [], + (ctx) => ctx.globals.lineProgress || 0 + ], + 'accumulated': [ + ValueType, + [], + (ctx) => ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated + ], + '+': [ + NumberType, + varargs(NumberType), + (ctx, args) => { + let result = 0; + for (const arg of args) { + result += arg.evaluate(ctx); + } + return result; + } + ], + '*': [ + NumberType, + varargs(NumberType), + (ctx, args) => { + let result = 1; + for (const arg of args) { + result *= arg.evaluate(ctx); + } + return result; + } + ], + '-': { + type: NumberType, + overloads: [ + [ + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx) + ], [ + [NumberType], + (ctx, [a]) => -a.evaluate(ctx) + ] + ] + }, + '/': [ + NumberType, + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx) + ], + '%': [ + NumberType, + [NumberType, NumberType], + (ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx) + ], + 'ln2': [ + NumberType, + [], + () => Math.LN2 + ], + 'pi': [ + NumberType, + [], + () => Math.PI + ], + 'e': [ + NumberType, + [], + () => Math.E + ], + '^': [ + NumberType, + [NumberType, NumberType], + (ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx)) + ], + 'sqrt': [ + NumberType, + [NumberType], + (ctx, [x]) => Math.sqrt(x.evaluate(ctx)) + ], + 'log10': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10 + ], + 'ln': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) + ], + 'log2': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2 + ], + 'sin': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.sin(n.evaluate(ctx)) + ], + 'cos': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.cos(n.evaluate(ctx)) + ], + 'tan': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.tan(n.evaluate(ctx)) + ], + 'asin': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.asin(n.evaluate(ctx)) + ], + 'acos': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.acos(n.evaluate(ctx)) + ], + 'atan': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.atan(n.evaluate(ctx)) + ], + 'min': [ + NumberType, + varargs(NumberType), + (ctx, args) => Math.min(...args.map(arg => arg.evaluate(ctx))) + ], + 'max': [ + NumberType, + varargs(NumberType), + (ctx, args) => Math.max(...args.map(arg => arg.evaluate(ctx))) + ], + 'abs': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.abs(n.evaluate(ctx)) + ], + 'round': [ + NumberType, + [NumberType], + (ctx, [n]) => { + const v = n.evaluate(ctx); + // Javascript's Math.round() rounds towards +Infinity for halfway + // values, even when they're negative. It's more common to round + // away from 0 (e.g., this is what python and C++ do) + return v < 0 ? -Math.round(-v) : Math.round(v); + } + ], + 'floor': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.floor(n.evaluate(ctx)) + ], + 'ceil': [ + NumberType, + [NumberType], + (ctx, [n]) => Math.ceil(n.evaluate(ctx)) + ], + 'filter-==': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => ctx.properties()[(k: any).value] === (v: any).value + ], + 'filter-id-==': [ + BooleanType, + [ValueType], + (ctx, [v]) => ctx.id() === (v: any).value + ], + 'filter-type-==': [ + BooleanType, + [StringType], + (ctx, [v]) => ctx.geometryType() === (v: any).value + ], + 'filter-<': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[(k: any).value]; + const b = (v: any).value; + return typeof a === typeof b && a < b; + } + ], + 'filter-id-<': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = (v: any).value; + return typeof a === typeof b && a < b; + } + ], + 'filter->': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[(k: any).value]; + const b = (v: any).value; + return typeof a === typeof b && a > b; + } + ], + 'filter-id->': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = (v: any).value; + return typeof a === typeof b && a > b; + } + ], + 'filter-<=': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[(k: any).value]; + const b = (v: any).value; + return typeof a === typeof b && a <= b; + } + ], + 'filter-id-<=': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = (v: any).value; + return typeof a === typeof b && a <= b; + } + ], + 'filter->=': [ + BooleanType, + [StringType, ValueType], + (ctx, [k, v]) => { + const a = ctx.properties()[(k: any).value]; + const b = (v: any).value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-id->=': [ + BooleanType, + [ValueType], + (ctx, [v]) => { + const a = ctx.id(); + const b = (v: any).value; + return typeof a === typeof b && a >= b; + } + ], + 'filter-has': [ + BooleanType, + [ValueType], + (ctx, [k]) => (k: any).value in ctx.properties() + ], + 'filter-has-id': [ + BooleanType, + [], + (ctx) => (ctx.id() !== null && ctx.id() !== undefined) + ], + 'filter-type-in': [ + BooleanType, + [array(StringType)], + (ctx, [v]) => (v: any).value.indexOf(ctx.geometryType()) >= 0 + ], + 'filter-id-in': [ + BooleanType, + [array(ValueType)], + (ctx, [v]) => (v: any).value.indexOf(ctx.id()) >= 0 + ], + 'filter-in-small': [ + BooleanType, + [StringType, array(ValueType)], + // assumes v is an array literal + (ctx, [k, v]) => (v: any).value.indexOf(ctx.properties()[(k: any).value]) >= 0 + ], + 'filter-in-large': [ + BooleanType, + [StringType, array(ValueType)], + // assumes v is a array literal with values sorted in ascending order and of a single type + (ctx, [k, v]) => binarySearch(ctx.properties()[(k: any).value], (v: any).value, 0, (v: any).value.length - 1) + ], + 'all': { + type: BooleanType, + overloads: [ + [ + [BooleanType, BooleanType], + (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx) + ], + [ + varargs(BooleanType), + (ctx, args) => { + for (const arg of args) { + if (!arg.evaluate(ctx)) + return false; + } + return true; + } + ] + ] + }, + 'any': { + type: BooleanType, + overloads: [ + [ + [BooleanType, BooleanType], + (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx) + ], + [ + varargs(BooleanType), + (ctx, args) => { + for (const arg of args) { + if (arg.evaluate(ctx)) + return true; + } + return false; + } + ] + ] + }, + '!': [ + BooleanType, + [BooleanType], + (ctx, [b]) => !b.evaluate(ctx) + ], + 'is-supported-script': [ + BooleanType, + [StringType], + // At parse time this will always return true, so we need to exclude this expression with isGlobalPropertyConstant + (ctx, [s]) => { + const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript; + if (isSupportedScript) { + return isSupportedScript(s.evaluate(ctx)); + } + return true; + } + ], + 'upcase': [ + StringType, + [StringType], + (ctx, [s]) => s.evaluate(ctx).toUpperCase() + ], + 'downcase': [ + StringType, + [StringType], + (ctx, [s]) => s.evaluate(ctx).toLowerCase() + ], + 'concat': [ + StringType, + varargs(ValueType), + (ctx, args) => args.map(arg => valueToString(arg.evaluate(ctx))).join('') + ], + 'resolved-locale': [ + StringType, + [CollatorType], + (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale() + ] +}); + +export default expressions; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/index_of.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/index_of.js new file mode 100644 index 0000000000000000000000000000000000000000..48e629335cfea3fd9fc9b32cc23fab6d2a6f883c --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/index_of.js @@ -0,0 +1,89 @@ +// @flow + +import {BooleanType, StringType, ValueType, NullType, toString, NumberType, isValidType, isValidNativeType} from '../types'; +import RuntimeError from '../runtime_error'; +import {typeOf} from '../values'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +class IndexOf implements Expression { + type: Type; + needle: Expression; + haystack: Expression; + fromIndex: ?Expression; + + constructor(needle: Expression, haystack: Expression, fromIndex?: Expression) { + this.type = NumberType; + this.needle = needle; + this.haystack = haystack; + this.fromIndex = fromIndex; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length <= 2 || args.length >= 5) { + return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`); + } + + const needle = context.parse(args[1], 1, ValueType); + + const haystack = context.parse(args[2], 2, ValueType); + + if (!needle || !haystack) return null; + if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) { + return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString(needle.type)} instead`); + } + + if (args.length === 4) { + const fromIndex = context.parse(args[3], 3, NumberType); + if (!fromIndex) return null; + return new IndexOf(needle, haystack, fromIndex); + } else { + return new IndexOf(needle, haystack); + } + } + + evaluate(ctx: EvaluationContext) { + const needle = (this.needle.evaluate(ctx): any); + const haystack = (this.haystack.evaluate(ctx): any); + + if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) { + throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString(typeOf(needle))} instead.`); + } + + if (!isValidNativeType(haystack, ['string', 'array'])) { + throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString(typeOf(haystack))} instead.`); + } + + if (this.fromIndex) { + const fromIndex = (this.fromIndex.evaluate(ctx): number); + return haystack.indexOf(needle, fromIndex); + } + + return haystack.indexOf(needle); + } + + eachChild(fn: (_: Expression) => void) { + fn(this.needle); + fn(this.haystack); + if (this.fromIndex) { + fn(this.fromIndex); + } + } + + outputDefined() { + return false; + } + + serialize() { + if (this.fromIndex != null && this.fromIndex !== undefined) { + const fromIndex = this.fromIndex.serialize(); + return ["index-of", this.needle.serialize(), this.haystack.serialize(), fromIndex]; + } + return ["index-of", this.needle.serialize(), this.haystack.serialize()]; + } +} + +export default IndexOf; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/interpolate.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/interpolate.js new file mode 100644 index 0000000000000000000000000000000000000000..98a1b65e4f25fcd43ea3ddfc8ee410959c01de04 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/interpolate.js @@ -0,0 +1,267 @@ +// @flow + +import UnitBezier from '@mapbox/unitbezier'; + +import * as interpolate from '../../util/interpolate'; +import {toString, NumberType, ColorType} from '../types'; +import {findStopLessThanOrEqualTo} from '../stops'; +import {hcl, lab} from '../../util/color_spaces'; + +import type {Stops} from '../stops'; +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +export type InterpolationType = + { name: 'linear' } | + { name: 'exponential', base: number } | + { name: 'cubic-bezier', controlPoints: [number, number, number, number] }; + +class Interpolate implements Expression { + type: Type; + + operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab'; + interpolation: InterpolationType; + input: Expression; + labels: Array; + outputs: Array; + + constructor(type: Type, operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab', interpolation: InterpolationType, input: Expression, stops: Stops) { + this.type = type; + this.operator = operator; + this.interpolation = interpolation; + this.input = input; + + this.labels = []; + this.outputs = []; + for (const [label, expression] of stops) { + this.labels.push(label); + this.outputs.push(expression); + } + } + + static interpolationFactor(interpolation: InterpolationType, input: number, lower: number, upper: number) { + let t = 0; + if (interpolation.name === 'exponential') { + t = exponentialInterpolation(input, interpolation.base, lower, upper); + } else if (interpolation.name === 'linear') { + t = exponentialInterpolation(input, 1, lower, upper); + } else if (interpolation.name === 'cubic-bezier') { + const c = interpolation.controlPoints; + const ub = new UnitBezier(c[0], c[1], c[2], c[3]); + t = ub.solve(exponentialInterpolation(input, 1, lower, upper)); + } + return t; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + let [operator, interpolation, input, ...rest] = args; + + if (!Array.isArray(interpolation) || interpolation.length === 0) { + return context.error(`Expected an interpolation type expression.`, 1); + } + + if (interpolation[0] === 'linear') { + interpolation = {name: 'linear'}; + } else if (interpolation[0] === 'exponential') { + const base = interpolation[1]; + if (typeof base !== 'number') + return context.error(`Exponential interpolation requires a numeric base.`, 1, 1); + interpolation = { + name: 'exponential', + base + }; + } else if (interpolation[0] === 'cubic-bezier') { + const controlPoints = interpolation.slice(1); + if ( + controlPoints.length !== 4 || + controlPoints.some(t => typeof t !== 'number' || t < 0 || t > 1) + ) { + return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1); + } + + interpolation = { + name: 'cubic-bezier', + controlPoints: (controlPoints: any) + }; + } else { + return context.error(`Unknown interpolation type ${String(interpolation[0])}`, 1, 0); + } + + if (args.length - 1 < 4) { + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + } + + if ((args.length - 1) % 2 !== 0) { + return context.error(`Expected an even number of arguments.`); + } + + input = context.parse(input, 2, NumberType); + if (!input) return null; + + const stops: Stops = []; + + let outputType: Type = (null: any); + if (operator === 'interpolate-hcl' || operator === 'interpolate-lab') { + outputType = ColorType; + } else if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + + for (let i = 0; i < rest.length; i += 2) { + const label = rest[i]; + const value = rest[i + 1]; + + const labelKey = i + 3; + const valueKey = i + 4; + + if (typeof label !== 'number') { + return context.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + + const parsed = context.parse(value, valueKey, outputType); + if (!parsed) return null; + outputType = outputType || parsed.type; + stops.push([label, parsed]); + } + + if (outputType.kind !== 'number' && + outputType.kind !== 'color' && + !( + outputType.kind === 'array' && + outputType.itemType.kind === 'number' && + typeof outputType.N === 'number' + ) + ) { + return context.error(`Type ${toString(outputType)} is not interpolatable.`); + } + + return new Interpolate(outputType, (operator: any), interpolation, input, stops); + } + + evaluate(ctx: EvaluationContext) { + const labels = this.labels; + const outputs = this.outputs; + + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + + const value = ((this.input.evaluate(ctx): any): number); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + + const stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + + const index = findStopLessThanOrEqualTo(labels, value); + const lower = labels[index]; + const upper = labels[index + 1]; + const t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper); + + const outputLower = outputs[index].evaluate(ctx); + const outputUpper = outputs[index + 1].evaluate(ctx); + + if (this.operator === 'interpolate') { + return (interpolate[this.type.kind.toLowerCase()]: any)(outputLower, outputUpper, t); // eslint-disable-line import/namespace + } else if (this.operator === 'interpolate-hcl') { + return hcl.reverse(hcl.interpolate(hcl.forward(outputLower), hcl.forward(outputUpper), t)); + } else { + return lab.reverse(lab.interpolate(lab.forward(outputLower), lab.forward(outputUpper), t)); + } + } + + eachChild(fn: (_: Expression) => void) { + fn(this.input); + for (const expression of this.outputs) { + fn(expression); + } + } + + outputDefined(): boolean { + return this.outputs.every(out => out.outputDefined()); + } + + serialize(): Array { + let interpolation; + if (this.interpolation.name === 'linear') { + interpolation = ["linear"]; + } else if (this.interpolation.name === 'exponential') { + if (this.interpolation.base === 1) { + interpolation = ["linear"]; + } else { + interpolation = ["exponential", this.interpolation.base]; + } + } else { + interpolation = ["cubic-bezier" ].concat(this.interpolation.controlPoints); + } + + const serialized = [this.operator, interpolation, this.input.serialize()]; + + for (let i = 0; i < this.labels.length; i++) { + serialized.push( + this.labels[i], + this.outputs[i].serialize() + ); + } + return serialized; + } +} + +/** + * Returns a ratio that can be used to interpolate between exponential function + * stops. + * How it works: Two consecutive stop values define a (scaled and shifted) exponential function `f(x) = a * base^x + b`, where `base` is the user-specified base, + * and `a` and `b` are constants affording sufficient degrees of freedom to fit + * the function to the given stops. + * + * Here's a bit of algebra that lets us compute `f(x)` directly from the stop + * values without explicitly solving for `a` and `b`: + * + * First stop value: `f(x0) = y0 = a * base^x0 + b` + * Second stop value: `f(x1) = y1 = a * base^x1 + b` + * => `y1 - y0 = a(base^x1 - base^x0)` + * => `a = (y1 - y0)/(base^x1 - base^x0)` + * + * Desired value: `f(x) = y = a * base^x + b` + * => `f(x) = y0 + a * (base^x - base^x0)` + * + * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a + * little algebra: + * ``` + * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) + * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) + * ``` + * + * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have + * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as + * an interpolation factor between the two stops' output values. + * + * (Note: a slightly different form for `ratio`, + * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer + * expensive `Math.pow()` operations.) + * + * @private +*/ +function exponentialInterpolation(input, base, lowerValue, upperValue) { + const difference = upperValue - lowerValue; + const progress = input - lowerValue; + + if (difference === 0) { + return 0; + } else if (base === 1) { + return progress / difference; + } else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } +} + +export default Interpolate; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/length.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/length.js new file mode 100644 index 0000000000000000000000000000000000000000..abaaf0bc049a94d2ac9322b00661a89a86e29283 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/length.js @@ -0,0 +1,61 @@ +// @flow + +import {NumberType, toString} from '../types'; + +import {typeOf} from '../values'; +import RuntimeError from '../runtime_error'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +class Length implements Expression { + type: Type; + input: Expression; + + constructor(input: Expression) { + this.type = NumberType; + this.input = input; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length !== 2) + return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`); + + const input = context.parse(args[1], 1); + if (!input) return null; + + if (input.type.kind !== 'array' && input.type.kind !== 'string' && input.type.kind !== 'value') + return context.error(`Expected argument of type string or array, but found ${toString(input.type)} instead.`); + + return new Length(input); + } + + evaluate(ctx: EvaluationContext) { + const input = this.input.evaluate(ctx); + if (typeof input === 'string') { + return input.length; + } else if (Array.isArray(input)) { + return input.length; + } else { + throw new RuntimeError(`Expected value to be of type string or array, but found ${toString(typeOf(input))} instead.`); + } + } + + eachChild(fn: (_: Expression) => void) { + fn(this.input); + } + + outputDefined() { + return false; + } + + serialize() { + const serialized = ["length"]; + this.eachChild(child => { serialized.push(child.serialize()); }); + return serialized; + } +} + +export default Length; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/let.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/let.js new file mode 100644 index 0000000000000000000000000000000000000000..cfa449d8a7e67bcdfa6c0eb60529bc65d70b95ab --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/let.js @@ -0,0 +1,72 @@ +// @flow + +import type {Type} from '../types'; +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; + +class Let implements Expression { + type: Type; + bindings: Array<[string, Expression]>; + result: Expression; + + constructor(bindings: Array<[string, Expression]>, result: Expression) { + this.type = result.type; + this.bindings = [].concat(bindings); + this.result = result; + } + + evaluate(ctx: EvaluationContext) { + return this.result.evaluate(ctx); + } + + eachChild(fn: (_: Expression) => void) { + for (const binding of this.bindings) { + fn(binding[1]); + } + fn(this.result); + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length < 4) + return context.error(`Expected at least 3 arguments, but found ${args.length - 1} instead.`); + + const bindings: Array<[string, Expression]> = []; + for (let i = 1; i < args.length - 1; i += 2) { + const name = args[i]; + + if (typeof name !== 'string') { + return context.error(`Expected string, but found ${typeof name} instead.`, i); + } + + if (/[^a-zA-Z0-9_]/.test(name)) { + return context.error(`Variable names must contain only alphanumeric characters or '_'.`, i); + } + + const value = context.parse(args[i + 1], i + 1); + if (!value) return null; + + bindings.push([name, value]); + } + + const result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings); + if (!result) return null; + + return new Let(bindings, result); + } + + outputDefined() { + return this.result.outputDefined(); + } + + serialize() { + const serialized = ["let"]; + for (const [name, expr] of this.bindings) { + serialized.push(name, expr.serialize()); + } + serialized.push(this.result.serialize()); + return serialized; + } +} + +export default Let; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/literal.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/literal.js new file mode 100644 index 0000000000000000000000000000000000000000..cdb45dd7fdbf236529ab45f5123ddca11dcbd9c1 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/literal.js @@ -0,0 +1,77 @@ +// @flow + +import assert from 'assert'; +import {isValue, typeOf, Color} from '../values'; +import Formatted from '../types/formatted'; + +import type {Type} from '../types'; +import type {Value} from '../values'; +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; + +class Literal implements Expression { + type: Type; + value: Value; + + constructor(type: Type, value: Value) { + this.type = type; + this.value = value; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length !== 2) + return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`); + + if (!isValue(args[1])) + return context.error(`invalid value`); + + const value = (args[1]: any); + let type = typeOf(value); + + // special case: infer the item type if possible for zero-length arrays + const expected = context.expectedType; + if ( + type.kind === 'array' && + type.N === 0 && + expected && + expected.kind === 'array' && + (typeof expected.N !== 'number' || expected.N === 0) + ) { + type = expected; + } + + return new Literal(type, value); + } + + evaluate() { + return this.value; + } + + eachChild() {} + + outputDefined() { + return true; + } + + serialize(): Array { + if (this.type.kind === 'array' || this.type.kind === 'object') { + return ["literal", this.value]; + } else if (this.value instanceof Color) { + // Constant-folding can generate Literal expressions that you + // couldn't actually generate with a "literal" expression, + // so we have to implement an equivalent serialization here + return ["rgba"].concat(this.value.toArray()); + } else if (this.value instanceof Formatted) { + // Same as Color + return this.value.serialize(); + } else { + assert(this.value === null || + typeof this.value === 'string' || + typeof this.value === 'number' || + typeof this.value === 'boolean'); + return (this.value: any); + } + } +} + +export default Literal; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/match.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/match.js new file mode 100644 index 0000000000000000000000000000000000000000..ec4d1c30fae61a4ed47ba2b6023d6de11a34bbd3 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/match.js @@ -0,0 +1,158 @@ +// @flow + +import assert from 'assert'; + +import {typeOf} from '../values'; +import {ValueType, type Type} from '../types'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; + +// Map input label values to output expression index +type Cases = {[number | string]: number}; + +class Match implements Expression { + type: Type; + inputType: Type; + + input: Expression; + cases: Cases; + outputs: Array; + otherwise: Expression; + + constructor(inputType: Type, outputType: Type, input: Expression, cases: Cases, outputs: Array, otherwise: Expression) { + this.inputType = inputType; + this.type = outputType; + this.input = input; + this.cases = cases; + this.outputs = outputs; + this.otherwise = otherwise; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length < 5) + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + if (args.length % 2 !== 1) + return context.error(`Expected an even number of arguments.`); + + let inputType; + let outputType; + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + const cases = {}; + const outputs = []; + for (let i = 2; i < args.length - 1; i += 2) { + let labels = args[i]; + const value = args[i + 1]; + + if (!Array.isArray(labels)) { + labels = [labels]; + } + + const labelContext = context.concat(i); + if (labels.length === 0) { + return labelContext.error('Expected at least one branch label.'); + } + + for (const label of labels) { + if (typeof label !== 'number' && typeof label !== 'string') { + return labelContext.error(`Branch labels must be numbers or strings.`); + } else if (typeof label === 'number' && Math.abs(label) > Number.MAX_SAFE_INTEGER) { + return labelContext.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`); + + } else if (typeof label === 'number' && Math.floor(label) !== label) { + return labelContext.error(`Numeric branch labels must be integer values.`); + + } else if (!inputType) { + inputType = typeOf(label); + } else if (labelContext.checkSubtype(inputType, typeOf(label))) { + return null; + } + + if (typeof cases[String(label)] !== 'undefined') { + return labelContext.error('Branch labels must be unique.'); + } + + cases[String(label)] = outputs.length; + } + + const result = context.parse(value, i, outputType); + if (!result) return null; + outputType = outputType || result.type; + outputs.push(result); + } + + const input = context.parse(args[1], 1, ValueType); + if (!input) return null; + + const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType); + if (!otherwise) return null; + + assert(inputType && outputType); + + if (input.type.kind !== 'value' && context.concat(1).checkSubtype((inputType: any), input.type)) { + return null; + } + + return new Match((inputType: any), (outputType: any), input, cases, outputs, otherwise); + } + + evaluate(ctx: EvaluationContext) { + const input = (this.input.evaluate(ctx): any); + const output = (typeOf(input) === this.inputType && this.outputs[this.cases[input]]) || this.otherwise; + return output.evaluate(ctx); + } + + eachChild(fn: (_: Expression) => void) { + fn(this.input); + this.outputs.forEach(fn); + fn(this.otherwise); + } + + outputDefined(): boolean { + return this.outputs.every(out => out.outputDefined()) && this.otherwise.outputDefined(); + } + + serialize(): Array { + const serialized = ["match", this.input.serialize()]; + + // Sort so serialization has an arbitrary defined order, even though + // branch order doesn't affect evaluation + const sortedLabels = Object.keys(this.cases).sort(); + + // Group branches by unique match expression to support condensed + // serializations of the form [case1, case2, ...] -> matchExpression + const groupedByOutput: Array<[number, Array]> = []; + const outputLookup: {[index: number]: number} = {}; // lookup index into groupedByOutput for a given output expression + for (const label of sortedLabels) { + const outputIndex = outputLookup[this.cases[label]]; + if (outputIndex === undefined) { + // First time seeing this output, add it to the end of the grouped list + outputLookup[this.cases[label]] = groupedByOutput.length; + groupedByOutput.push([this.cases[label], [label]]); + } else { + // We've seen this expression before, add the label to that output's group + groupedByOutput[outputIndex][1].push(label); + } + } + + const coerceLabel = (label) => this.inputType.kind === 'number' ? Number(label) : label; + + for (const [outputIndex, labels] of groupedByOutput) { + if (labels.length === 1) { + // Only a single label matches this output expression + serialized.push(coerceLabel(labels[0])); + } else { + // Array of literal labels pointing to this output expression + serialized.push(labels.map(coerceLabel)); + } + serialized.push(this.outputs[outputIndex].serialize()); + } + serialized.push(this.otherwise.serialize()); + return serialized; + } +} + +export default Match; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/number_format.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/number_format.js new file mode 100644 index 0000000000000000000000000000000000000000..754503fb1979c4c32348fbcb2de61885f2020d3c --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/number_format.js @@ -0,0 +1,142 @@ +// @flow + +import {StringType, NumberType} from '../types'; + +import type {Expression} from '../expression'; +import type EvaluationContext from '../evaluation_context'; +import type ParsingContext from '../parsing_context'; +import type {Type} from '../types'; + +declare var Intl: { + NumberFormat: Class +}; + +declare class Intl$NumberFormat { + constructor ( + locales?: string | string[], + options?: NumberFormatOptions + ): Intl$NumberFormat; + + static ( + locales?: string | string[], + options?: NumberFormatOptions + ): Intl$NumberFormat; + + format(a: number): string; + + resolvedOptions(): any; +} + +type NumberFormatOptions = { + style?: 'decimal' | 'currency' | 'percent'; + currency?: null | string; + minimumFractionDigits?: null | string; + maximumFractionDigits?: null | string; +}; + +export default class NumberFormat implements Expression { + type: Type; + number: Expression; + locale: Expression | null; // BCP 47 language tag + currency: Expression | null; // ISO 4217 currency code, required if style=currency + minFractionDigits: Expression | null; // Default 0 + maxFractionDigits: Expression | null; // Default 3 + + constructor(number: Expression, + locale: Expression | null, + currency: Expression | null, + minFractionDigits: Expression | null, + maxFractionDigits: Expression | null) { + this.type = StringType; + this.number = number; + this.locale = locale; + this.currency = currency; + this.minFractionDigits = minFractionDigits; + this.maxFractionDigits = maxFractionDigits; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext): ?Expression { + if (args.length !== 3) + return context.error(`Expected two arguments.`); + + const number = context.parse(args[1], 1, NumberType); + if (!number) return null; + + const options = (args[2]: any); + if (typeof options !== "object" || Array.isArray(options)) + return context.error(`NumberFormat options argument must be an object.`); + + let locale = null; + if (options['locale']) { + locale = context.parse(options['locale'], 1, StringType); + if (!locale) return null; + } + + let currency = null; + if (options['currency']) { + currency = context.parse(options['currency'], 1, StringType); + if (!currency) return null; + } + + let minFractionDigits = null; + if (options['min-fraction-digits']) { + minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType); + if (!minFractionDigits) return null; + } + + let maxFractionDigits = null; + if (options['max-fraction-digits']) { + maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType); + if (!maxFractionDigits) return null; + } + + return new NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits); + } + + evaluate(ctx: EvaluationContext) { + return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], + { + style: this.currency ? "currency" : "decimal", + currency: this.currency ? this.currency.evaluate(ctx) : undefined, + minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : undefined, + maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : undefined, + }).format(this.number.evaluate(ctx)); + } + + eachChild(fn: (_: Expression) => void) { + fn(this.number); + if (this.locale) { + fn(this.locale); + } + if (this.currency) { + fn(this.currency); + } + if (this.minFractionDigits) { + fn(this.minFractionDigits); + } + if (this.maxFractionDigits) { + fn(this.maxFractionDigits); + } + } + + outputDefined() { + return false; + } + + serialize() { + const options = {}; + if (this.locale) { + options['locale'] = this.locale.serialize(); + } + if (this.currency) { + options['currency'] = this.currency.serialize(); + } + if (this.minFractionDigits) { + options['min-fraction-digits'] = this.minFractionDigits.serialize(); + } + if (this.maxFractionDigits) { + options['max-fraction-digits'] = this.maxFractionDigits.serialize(); + } + return ["number-format", this.number.serialize(), options]; + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/slice.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/slice.js new file mode 100644 index 0000000000000000000000000000000000000000..09a47c10e9a19f708c144e8fd62d95ddeeb47bc3 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/slice.js @@ -0,0 +1,86 @@ +// @flow + +import {ValueType, NumberType, StringType, array, toString, isValidType, isValidNativeType} from '../types'; +import RuntimeError from '../runtime_error'; +import {typeOf} from '../values'; + +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +class Slice implements Expression { + type: Type; + input: Expression; + beginIndex: Expression; + endIndex: ?Expression; + + constructor(type: Type, input: Expression, beginIndex: Expression, endIndex?: Expression) { + this.type = type; + this.input = input; + this.beginIndex = beginIndex; + this.endIndex = endIndex; + + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length <= 2 || args.length >= 5) { + return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`); + } + + const input = context.parse(args[1], 1, ValueType); + const beginIndex = context.parse(args[2], 2, NumberType); + + if (!input || !beginIndex) return null; + + if (!isValidType(input.type, [array(ValueType), StringType, ValueType])) { + return context.error(`Expected first argument to be of type array or string, but found ${toString(input.type)} instead`); + } + + if (args.length === 4) { + const endIndex = context.parse(args[3], 3, NumberType); + if (!endIndex) return null; + return new Slice(input.type, input, beginIndex, endIndex); + } else { + return new Slice(input.type, input, beginIndex); + } + } + + evaluate(ctx: EvaluationContext) { + const input = (this.input.evaluate(ctx): any); + const beginIndex = (this.beginIndex.evaluate(ctx): number); + + if (!isValidNativeType(input, ['string', 'array'])) { + throw new RuntimeError(`Expected first argument to be of type array or string, but found ${toString(typeOf(input))} instead.`); + } + + if (this.endIndex) { + const endIndex = (this.endIndex.evaluate(ctx): number); + return input.slice(beginIndex, endIndex); + } + + return input.slice(beginIndex); + } + + eachChild(fn: (_: Expression) => void) { + fn(this.input); + fn(this.beginIndex); + if (this.endIndex) { + fn(this.endIndex); + } + } + + outputDefined() { + return false; + } + + serialize() { + if (this.endIndex != null && this.endIndex !== undefined) { + const endIndex = this.endIndex.serialize(); + return ["slice", this.input.serialize(), this.beginIndex.serialize(), endIndex]; + } + return ["slice", this.input.serialize(), this.beginIndex.serialize()]; + } +} + +export default Slice; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/step.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/step.js new file mode 100644 index 0000000000000000000000000000000000000000..3e2058290b54ca6bb11198fcd329d84e17c5eba4 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/step.js @@ -0,0 +1,120 @@ +// @flow + +import {NumberType} from '../types'; + +import {findStopLessThanOrEqualTo} from '../stops'; + +import type {Stops} from '../stops'; +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {Type} from '../types'; + +class Step implements Expression { + type: Type; + + input: Expression; + labels: Array; + outputs: Array; + + constructor(type: Type, input: Expression, stops: Stops) { + this.type = type; + this.input = input; + + this.labels = []; + this.outputs = []; + for (const [label, expression] of stops) { + this.labels.push(label); + this.outputs.push(expression); + } + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length - 1 < 4) { + return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`); + } + + if ((args.length - 1) % 2 !== 0) { + return context.error(`Expected an even number of arguments.`); + } + + const input = context.parse(args[1], 1, NumberType); + if (!input) return null; + + const stops: Stops = []; + + let outputType: Type = (null: any); + if (context.expectedType && context.expectedType.kind !== 'value') { + outputType = context.expectedType; + } + + for (let i = 1; i < args.length; i += 2) { + const label = i === 1 ? -Infinity : args[i]; + const value = args[i + 1]; + + const labelKey = i; + const valueKey = i + 1; + + if (typeof label !== 'number') { + return context.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey); + } + + if (stops.length && stops[stops.length - 1][0] >= label) { + return context.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.', labelKey); + } + + const parsed = context.parse(value, valueKey, outputType); + if (!parsed) return null; + outputType = outputType || parsed.type; + stops.push([label, parsed]); + } + + return new Step(outputType, input, stops); + } + + evaluate(ctx: EvaluationContext) { + const labels = this.labels; + const outputs = this.outputs; + + if (labels.length === 1) { + return outputs[0].evaluate(ctx); + } + + const value = ((this.input.evaluate(ctx): any): number); + if (value <= labels[0]) { + return outputs[0].evaluate(ctx); + } + + const stopCount = labels.length; + if (value >= labels[stopCount - 1]) { + return outputs[stopCount - 1].evaluate(ctx); + } + + const index = findStopLessThanOrEqualTo(labels, value); + return outputs[index].evaluate(ctx); + } + + eachChild(fn: (_: Expression) => void) { + fn(this.input); + for (const expression of this.outputs) { + fn(expression); + } + } + + outputDefined(): boolean { + return this.outputs.every(out => out.outputDefined()); + } + + serialize() { + const serialized = ["step", this.input.serialize()]; + for (let i = 0; i < this.labels.length; i++) { + if (i > 0) { + serialized.push(this.labels[i]); + } + serialized.push(this.outputs[i].serialize()); + } + return serialized; + } +} + +export default Step; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/var.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/var.js new file mode 100644 index 0000000000000000000000000000000000000000..aa97e6cc2e43fedfe5769591dbabee010042c6fd --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/var.js @@ -0,0 +1,46 @@ +// @flow + +import type {Type} from '../types'; +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; + +class Var implements Expression { + type: Type; + name: string; + boundExpression: Expression; + + constructor(name: string, boundExpression: Expression) { + this.type = boundExpression.type; + this.name = name; + this.boundExpression = boundExpression; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length !== 2 || typeof args[1] !== 'string') + return context.error(`'var' expression requires exactly one string literal argument.`); + + const name = args[1]; + if (!context.scope.has(name)) { + return context.error(`Unknown variable "${name}". Make sure "${name}" has been bound in an enclosing "let" expression before using it.`, 1); + } + + return new Var(name, context.scope.get(name)); + } + + evaluate(ctx: EvaluationContext) { + return this.boundExpression.evaluate(ctx); + } + + eachChild() {} + + outputDefined() { + return false; + } + + serialize() { + return ["var", this.name]; + } +} + +export default Var; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/definitions/within.js b/node_modules/mapbox-gl/src/style-spec/expression/definitions/within.js new file mode 100644 index 0000000000000000000000000000000000000000..67d60beec45f36ccbc34df80f35fcdf849b10882 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/definitions/within.js @@ -0,0 +1,342 @@ +// @flow + +import {isValue} from '../values'; +import type {Type} from '../types'; +import {BooleanType} from '../types'; +import type {Expression} from '../expression'; +import type ParsingContext from '../parsing_context'; +import type EvaluationContext from '../evaluation_context'; +import type {GeoJSON, GeoJSONPolygon, GeoJSONMultiPolygon} from '@mapbox/geojson-types'; +import Point from '@mapbox/point-geometry'; +import type {CanonicalTileID} from '../../../source/tile_id'; + +type GeoJSONPolygons =| GeoJSONPolygon | GeoJSONMultiPolygon; + +// minX, minY, maxX, maxY +type BBox = [number, number, number, number]; +const EXTENT = 8192; + +function updateBBox(bbox: BBox, coord: Point) { + bbox[0] = Math.min(bbox[0], coord[0]); + bbox[1] = Math.min(bbox[1], coord[1]); + bbox[2] = Math.max(bbox[2], coord[0]); + bbox[3] = Math.max(bbox[3], coord[1]); +} + +function mercatorXfromLng(lng: number) { + return (180 + lng) / 360; +} + +function mercatorYfromLat(lat: number) { + return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360; +} + +function boxWithinBox(bbox1: BBox, bbox2: BBox) { + if (bbox1[0] <= bbox2[0]) return false; + if (bbox1[2] >= bbox2[2]) return false; + if (bbox1[1] <= bbox2[1]) return false; + if (bbox1[3] >= bbox2[3]) return false; + return true; +} + +function getTileCoordinates(p, canonical: CanonicalTileID) { + const x = mercatorXfromLng(p[0]); + const y = mercatorYfromLat(p[1]); + const tilesAtZoom = Math.pow(2, canonical.z); + return [Math.round(x * tilesAtZoom * EXTENT), Math.round(y * tilesAtZoom * EXTENT)]; +} + +function onBoundary(p, p1, p2) { + const x1 = p[0] - p1[0]; + const y1 = p[1] - p1[1]; + const x2 = p[0] - p2[0]; + const y2 = p[1] - p2[1]; + return (x1 * y2 - x2 * y1 === 0) && (x1 * x2 <= 0) && (y1 * y2 <= 0); +} + +function rayIntersect(p, p1, p2) { + return ((p1[1] > p[1]) !== (p2[1] > p[1])) && (p[0] < (p2[0] - p1[0]) * (p[1] - p1[1]) / (p2[1] - p1[1]) + p1[0]); +} + +// ray casting algorithm for detecting if point is in polygon +function pointWithinPolygon(point, rings) { + let inside = false; + for (let i = 0, len = rings.length; i < len; i++) { + const ring = rings[i]; + for (let j = 0, len2 = ring.length; j < len2 - 1; j++) { + if (onBoundary(point, ring[j], ring[j + 1])) return false; + if (rayIntersect(point, ring[j], ring[j + 1])) inside = !inside; + } + } + return inside; +} + +function pointWithinPolygons(point, polygons) { + for (let i = 0; i < polygons.length; i++) { + if (pointWithinPolygon(point, polygons[i])) return true; + } + return false; +} + +function perp(v1, v2) { + return (v1[0] * v2[1] - v1[1] * v2[0]); +} + +// check if p1 and p2 are in different sides of line segment q1->q2 +function twoSided(p1, p2, q1, q2) { + // q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3) + const x1 = p1[0] - q1[0]; + const y1 = p1[1] - q1[1]; + const x2 = p2[0] - q1[0]; + const y2 = p2[1] - q1[1]; + const x3 = q2[0] - q1[0]; + const y3 = q2[1] - q1[1]; + const det1 = (x1 * y3 - x3 * y1); + const det2 = (x2 * y3 - x3 * y2); + if ((det1 > 0 && det2 < 0) || (det1 < 0 && det2 > 0)) return true; + return false; +} +// a, b are end points for line segment1, c and d are end points for line segment2 +function lineIntersectLine(a, b, c, d) { + // check if two segments are parallel or not + // precondition is end point a, b is inside polygon, if line a->b is + // parallel to polygon edge c->d, then a->b won't intersect with c->d + const vectorP = [b[0] - a[0], b[1] - a[1]]; + const vectorQ = [d[0] - c[0], d[1] - c[1]]; + if (perp(vectorQ, vectorP) === 0) return false; + + // If lines are intersecting with each other, the relative location should be: + // a and b lie in different sides of segment c->d + // c and d lie in different sides of segment a->b + if (twoSided(a, b, c, d) && twoSided(c, d, a, b)) return true; + return false; +} + +function lineIntersectPolygon(p1, p2, polygon) { + for (const ring of polygon) { + // loop through every edge of the ring + for (let j = 0; j < ring.length - 1; ++j) { + if (lineIntersectLine(p1, p2, ring[j], ring[j + 1])) { + return true; + } + } + } + return false; +} + +function lineStringWithinPolygon(line, polygon) { + // First, check if geometry points of line segments are all inside polygon + for (let i = 0; i < line.length; ++i) { + if (!pointWithinPolygon(line[i], polygon)) { + return false; + } + } + + // Second, check if there is line segment intersecting polygon edge + for (let i = 0; i < line.length - 1; ++i) { + if (lineIntersectPolygon(line[i], line[i + 1], polygon)) { + return false; + } + } + return true; +} + +function lineStringWithinPolygons(line, polygons) { + for (let i = 0; i < polygons.length; i++) { + if (lineStringWithinPolygon(line, polygons[i])) return true; + } + return false; +} + +function getTilePolygon(coordinates, bbox, canonical) { + const polygon = []; + for (let i = 0; i < coordinates.length; i++) { + const ring = []; + for (let j = 0; j < coordinates[i].length; j++) { + const coord = getTileCoordinates(coordinates[i][j], canonical); + updateBBox(bbox, coord); + ring.push(coord); + } + polygon.push(ring); + } + return polygon; +} + +function getTilePolygons(coordinates, bbox, canonical) { + const polygons = []; + for (let i = 0; i < coordinates.length; i++) { + const polygon = getTilePolygon(coordinates[i], bbox, canonical); + polygons.push(polygon); + } + return polygons; +} + +function updatePoint(p, bbox, polyBBox, worldSize) { + if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) { + const halfWorldSize = worldSize * 0.5; + let shift = (p[0] - polyBBox[0] > halfWorldSize) ? -worldSize : (polyBBox[0] - p[0] > halfWorldSize) ? worldSize : 0; + if (shift === 0) { + shift = (p[0] - polyBBox[2] > halfWorldSize) ? -worldSize : (polyBBox[2] - p[0] > halfWorldSize) ? worldSize : 0; + } + p[0] += shift; + } + updateBBox(bbox, p); +} + +function resetBBox(bbox) { + bbox[0] = bbox[1] = Infinity; + bbox[2] = bbox[3] = -Infinity; +} + +function getTilePoints(geometry, pointBBox, polyBBox, canonical) { + const worldSize = Math.pow(2, canonical.z) * EXTENT; + const shifts = [canonical.x * EXTENT, canonical.y * EXTENT]; + const tilePoints = []; + for (const points of geometry) { + for (const point of points) { + const p = [point.x + shifts[0], point.y + shifts[1]]; + updatePoint(p, pointBBox, polyBBox, worldSize); + tilePoints.push(p); + } + } + return tilePoints; +} + +function getTileLines(geometry, lineBBox, polyBBox, canonical) { + const worldSize = Math.pow(2, canonical.z) * EXTENT; + const shifts = [canonical.x * EXTENT, canonical.y * EXTENT]; + const tileLines = []; + for (const line of geometry) { + const tileLine = []; + for (const point of line) { + const p = [point.x + shifts[0], point.y + shifts[1]]; + updateBBox(lineBBox, p); + tileLine.push(p); + } + tileLines.push(tileLine); + } + if (lineBBox[2] - lineBBox[0] <= worldSize / 2) { + resetBBox(lineBBox); + for (const line of tileLines) { + for (const p of line) { + updatePoint(p, lineBBox, polyBBox, worldSize); + } + } + } + return tileLines; +} + +function pointsWithinPolygons(ctx: EvaluationContext, polygonGeometry: GeoJSONPolygons) { + const pointBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const polyBBox = [Infinity, Infinity, -Infinity, -Infinity]; + + const canonical = ctx.canonicalID(); + + if (polygonGeometry.type === 'Polygon') { + const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) return false; + + for (const point of tilePoints) { + if (!pointWithinPolygon(point, tilePolygon)) return false; + } + } + if (polygonGeometry.type === 'MultiPolygon') { + const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical); + if (!boxWithinBox(pointBBox, polyBBox)) return false; + + for (const point of tilePoints) { + if (!pointWithinPolygons(point, tilePolygons)) return false; + } + } + + return true; +} + +function linesWithinPolygons(ctx: EvaluationContext, polygonGeometry: GeoJSONPolygons) { + const lineBBox = [Infinity, Infinity, -Infinity, -Infinity]; + const polyBBox = [Infinity, Infinity, -Infinity, -Infinity]; + + const canonical = ctx.canonicalID(); + + if (polygonGeometry.type === 'Polygon') { + const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical); + const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) return false; + + for (const line of tileLines) { + if (!lineStringWithinPolygon(line, tilePolygon)) return false; + } + } + if (polygonGeometry.type === 'MultiPolygon') { + const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical); + const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical); + if (!boxWithinBox(lineBBox, polyBBox)) return false; + + for (const line of tileLines) { + if (!lineStringWithinPolygons(line, tilePolygons)) return false; + } + } + return true; +} + +class Within implements Expression { + type: Type; + geojson: GeoJSON + geometries: GeoJSONPolygons; + + constructor(geojson: GeoJSON, geometries: GeoJSONPolygons) { + this.type = BooleanType; + this.geojson = geojson; + this.geometries = geometries; + } + + static parse(args: $ReadOnlyArray, context: ParsingContext) { + if (args.length !== 2) + return context.error(`'within' expression requires exactly one argument, but found ${args.length - 1} instead.`); + if (isValue(args[1])) { + const geojson = (args[1]: Object); + if (geojson.type === 'FeatureCollection') { + for (let i = 0; i < geojson.features.length; ++i) { + const type = geojson.features[i].geometry.type; + if (type === 'Polygon' || type === 'MultiPolygon') { + return new Within(geojson, geojson.features[i].geometry); + } + } + } else if (geojson.type === 'Feature') { + const type = geojson.geometry.type; + if (type === 'Polygon' || type === 'MultiPolygon') { + return new Within(geojson, geojson.geometry); + } + } else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') { + return new Within(geojson, geojson); + } + } + return context.error(`'within' expression requires valid geojson object that contains polygon geometry type.`); + } + + evaluate(ctx: EvaluationContext) { + if (ctx.geometry() != null && ctx.canonicalID() != null) { + if (ctx.geometryType() === 'Point') { + return pointsWithinPolygons(ctx, this.geometries); + } else if (ctx.geometryType() === 'LineString') { + return linesWithinPolygons(ctx, this.geometries); + } + } + return false; + } + + eachChild() {} + + outputDefined(): boolean { + return true; + } + + serialize(): Array { + return ["within", this.geojson]; + } + +} + +export default Within; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/evaluation_context.js b/node_modules/mapbox-gl/src/style-spec/expression/evaluation_context.js new file mode 100644 index 0000000000000000000000000000000000000000..1e7a6d587e1d47faedc101498fc9b4380705c578 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/evaluation_context.js @@ -0,0 +1,59 @@ +// @flow + +import {Color} from './values'; +import type {FormattedSection} from './types/formatted'; +import type {GlobalProperties, Feature, FeatureState} from './index'; +import type {CanonicalTileID} from '../../source/tile_id'; + +const geometryTypes = ['Unknown', 'Point', 'LineString', 'Polygon']; + +class EvaluationContext { + globals: GlobalProperties; + feature: ?Feature; + featureState: ?FeatureState; + formattedSection: ?FormattedSection; + availableImages: ?Array; + canonical: ?CanonicalTileID; + + _parseColorCache: {[_: string]: ?Color}; + + constructor() { + this.globals = (null: any); + this.feature = null; + this.featureState = null; + this.formattedSection = null; + this._parseColorCache = {}; + this.availableImages = null; + this.canonical = null; + } + + id() { + return this.feature && 'id' in this.feature ? this.feature.id : null; + } + + geometryType() { + return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null; + } + + geometry() { + return this.feature && 'geometry' in this.feature ? this.feature.geometry : null; + } + + canonicalID() { + return this.canonical; + } + + properties() { + return this.feature && this.feature.properties || {}; + } + + parseColor(input: string): ?Color { + let cached = this._parseColorCache[input]; + if (!cached) { + cached = this._parseColorCache[input] = Color.parse(input); + } + return cached; + } +} + +export default EvaluationContext; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/expression.js b/node_modules/mapbox-gl/src/style-spec/expression/expression.js new file mode 100644 index 0000000000000000000000000000000000000000..3404686ede68b4c921aec29da08c5549367912a3 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/expression.js @@ -0,0 +1,27 @@ +// @flow + +import type {Type} from './types'; +import type ParsingContext from './parsing_context'; +import type EvaluationContext from './evaluation_context'; + +type SerializedExpression = Array | string | number | boolean | null; + +export interface Expression { + +type: Type; + + evaluate(ctx: EvaluationContext): any; + + eachChild(fn: Expression => void): void; + + /** + * Statically analyze the expression, attempting to enumerate possible outputs. Returns + * false if the complete set of outputs is statically undecidable, otherwise true. + */ + outputDefined(): boolean; + + serialize(): SerializedExpression; +} + +export type ExpressionParser = (args: $ReadOnlyArray, context: ParsingContext) => ?Expression; +export type ExpressionRegistration = Class & { +parse: ExpressionParser }; +export type ExpressionRegistry = {[_: string]: ExpressionRegistration}; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/index.js b/node_modules/mapbox-gl/src/style-spec/expression/index.js new file mode 100644 index 0000000000000000000000000000000000000000..736ad8fdc215aa9be44049231389e0b6acd48d67 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/index.js @@ -0,0 +1,392 @@ +// @flow + +import assert from 'assert'; + +import extend from '../util/extend'; +import ParsingError from './parsing_error'; +import ParsingContext from './parsing_context'; +import EvaluationContext from './evaluation_context'; +import CompoundExpression from './compound_expression'; +import Step from './definitions/step'; +import Interpolate from './definitions/interpolate'; +import Coalesce from './definitions/coalesce'; +import Let from './definitions/let'; +import definitions from './definitions'; +import * as isConstant from './is_constant'; +import RuntimeError from './runtime_error'; +import {success, error} from '../util/result'; +import {supportsPropertyExpression, supportsZoomExpression, supportsInterpolation} from '../util/properties'; + +import type {Type, EvaluationKind} from './types'; +import type {Value} from './values'; +import type {Expression} from './expression'; +import type {StylePropertySpecification} from '../style-spec'; +import type {Result} from '../util/result'; +import type {InterpolationType} from './definitions/interpolate'; +import type {PropertyValueSpecification} from '../types'; +import type {FormattedSection} from './types/formatted'; +import type Point from '@mapbox/point-geometry'; +import type {CanonicalTileID} from '../../source/tile_id'; + +export type Feature = { + +type: 1 | 2 | 3 | 'Unknown' | 'Point' | 'MultiPoint' | 'LineString' | 'MultiLineString' | 'Polygon' | 'MultiPolygon', + +id?: any, + +properties: {[_: string]: any}, + +patterns?: {[_: string]: {"min": string, "mid": string, "max": string}}, + +geometry?: Array> +}; + +export type FeatureState = {[_: string]: any}; + +export type GlobalProperties = $ReadOnly<{ + zoom: number, + heatmapDensity?: number, + lineProgress?: number, + isSupportedScript?: (_: string) => boolean, + accumulated?: Value +}>; + +export class StyleExpression { + expression: Expression; + + _evaluator: EvaluationContext; + _defaultValue: Value; + _warningHistory: {[key: string]: boolean}; + _enumValues: ?{[_: string]: any}; + + constructor(expression: Expression, propertySpec: ?StylePropertySpecification) { + this.expression = expression; + this._warningHistory = {}; + this._evaluator = new EvaluationContext(); + this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null; + this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null; + } + + evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any { + this._evaluator.globals = globals; + this._evaluator.feature = feature; + this._evaluator.featureState = featureState; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection; + + return this.expression.evaluate(this._evaluator); + } + + evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any { + this._evaluator.globals = globals; + this._evaluator.feature = feature || null; + this._evaluator.featureState = featureState || null; + this._evaluator.canonical = canonical; + this._evaluator.availableImages = availableImages || null; + this._evaluator.formattedSection = formattedSection || null; + + try { + const val = this.expression.evaluate(this._evaluator); + // eslint-disable-next-line no-self-compare + if (val === null || val === undefined || (typeof val === 'number' && val !== val)) { + return this._defaultValue; + } + if (this._enumValues && !(val in this._enumValues)) { + throw new RuntimeError(`Expected value to be one of ${Object.keys(this._enumValues).map(v => JSON.stringify(v)).join(', ')}, but found ${JSON.stringify(val)} instead.`); + } + return val; + } catch (e) { + if (!this._warningHistory[e.message]) { + this._warningHistory[e.message] = true; + if (typeof console !== 'undefined') { + console.warn(e.message); + } + } + return this._defaultValue; + } + } +} + +export function isExpression(expression: mixed) { + return Array.isArray(expression) && expression.length > 0 && + typeof expression[0] === 'string' && expression[0] in definitions; +} + +/** + * Parse and typecheck the given style spec JSON expression. If + * options.defaultValue is provided, then the resulting StyleExpression's + * `evaluate()` method will handle errors by logging a warning (once per + * message) and returning the default value. Otherwise, it will throw + * evaluation errors. + * + * @private + */ +export function createExpression(expression: mixed, propertySpec: ?StylePropertySpecification): Result> { + const parser = new ParsingContext(definitions, [], propertySpec ? getExpectedType(propertySpec) : undefined); + + // For string-valued properties, coerce to string at the top level rather than asserting. + const parsed = parser.parse(expression, undefined, undefined, undefined, + propertySpec && propertySpec.type === 'string' ? {typeAnnotation: 'coerce'} : undefined); + + if (!parsed) { + assert(parser.errors.length > 0); + return error(parser.errors); + } + + return success(new StyleExpression(parsed, propertySpec)); +} + +export class ZoomConstantExpression { + kind: Kind; + isStateDependent: boolean; + _styleExpression: StyleExpression; + + constructor(kind: Kind, expression: StyleExpression) { + this.kind = kind; + this._styleExpression = expression; + this.isStateDependent = kind !== ('constant': EvaluationKind) && !isConstant.isStateConstant(expression.expression); + } + + evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); + } + + evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); + } +} + +export class ZoomDependentExpression { + kind: Kind; + zoomStops: Array; + isStateDependent: boolean; + + _styleExpression: StyleExpression; + interpolationType: ?InterpolationType; + + constructor(kind: Kind, expression: StyleExpression, zoomStops: Array, interpolationType?: InterpolationType) { + this.kind = kind; + this.zoomStops = zoomStops; + this._styleExpression = expression; + this.isStateDependent = kind !== ('camera': EvaluationKind) && !isConstant.isStateConstant(expression.expression); + this.interpolationType = interpolationType; + } + + evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any { + return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection); + } + + evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any { + return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection); + } + + interpolationFactor(input: number, lower: number, upper: number): number { + if (this.interpolationType) { + return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper); + } else { + return 0; + } + } +} + +export type ConstantExpression = { + kind: 'constant', + +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array) => any, +} + +export type SourceExpression = { + kind: 'source', + isStateDependent: boolean, + +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection) => any, +}; + +export type CameraExpression = { + kind: 'camera', + +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array) => any, + +interpolationFactor: (input: number, lower: number, upper: number) => number, + zoomStops: Array, + interpolationType: ?InterpolationType +}; + +export type CompositeExpression = { + kind: 'composite', + isStateDependent: boolean, + +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection) => any, + +interpolationFactor: (input: number, lower: number, upper: number) => number, + zoomStops: Array, + interpolationType: ?InterpolationType +}; + +export type StylePropertyExpression = + | ConstantExpression + | SourceExpression + | CameraExpression + | CompositeExpression; + +export function createPropertyExpression(expression: mixed, propertySpec: StylePropertySpecification): Result> { + expression = createExpression(expression, propertySpec); + if (expression.result === 'error') { + return expression; + } + + const parsed = expression.value.expression; + + const isFeatureConstant = isConstant.isFeatureConstant(parsed); + if (!isFeatureConstant && !supportsPropertyExpression(propertySpec)) { + return error([new ParsingError('', 'data expressions not supported')]); + } + + const isZoomConstant = isConstant.isGlobalPropertyConstant(parsed, ['zoom']); + if (!isZoomConstant && !supportsZoomExpression(propertySpec)) { + return error([new ParsingError('', 'zoom expressions not supported')]); + } + + const zoomCurve = findZoomCurve(parsed); + if (!zoomCurve && !isZoomConstant) { + return error([new ParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]); + } else if (zoomCurve instanceof ParsingError) { + return error([zoomCurve]); + } else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) { + return error([new ParsingError('', '"interpolate" expressions cannot be used with this property')]); + } + + if (!zoomCurve) { + return success(isFeatureConstant ? + (new ZoomConstantExpression('constant', expression.value): ConstantExpression) : + (new ZoomConstantExpression('source', expression.value): SourceExpression)); + } + + const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined; + + return success(isFeatureConstant ? + (new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType): CameraExpression) : + (new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType): CompositeExpression)); +} + +import {isFunction, createFunction} from '../function'; +import {Color} from './values'; + +// serialization wrapper for old-style stop functions normalized to the +// expression interface +export class StylePropertyFunction { + _parameters: PropertyValueSpecification; + _specification: StylePropertySpecification; + + kind: EvaluationKind; + evaluate: (globals: GlobalProperties, feature?: Feature) => any; + interpolationFactor: ?(input: number, lower: number, upper: number) => number; + zoomStops: ?Array; + + constructor(parameters: PropertyValueSpecification, specification: StylePropertySpecification) { + this._parameters = parameters; + this._specification = specification; + extend(this, createFunction(this._parameters, this._specification)); + } + + static deserialize(serialized: {_parameters: PropertyValueSpecification, _specification: StylePropertySpecification}) { + return ((new StylePropertyFunction(serialized._parameters, serialized._specification)): StylePropertyFunction); + } + + static serialize(input: StylePropertyFunction) { + return { + _parameters: input._parameters, + _specification: input._specification + }; + } +} + +export function normalizePropertyExpression(value: PropertyValueSpecification, specification: StylePropertySpecification): StylePropertyExpression { + if (isFunction(value)) { + return (new StylePropertyFunction(value, specification): any); + + } else if (isExpression(value)) { + const expression = createPropertyExpression(value, specification); + if (expression.result === 'error') { + // this should have been caught in validation + throw new Error(expression.value.map(err => `${err.key}: ${err.message}`).join(', ')); + } + return expression.value; + + } else { + let constant: any = value; + if (typeof value === 'string' && specification.type === 'color') { + constant = Color.parse(value); + } + return { + kind: 'constant', + evaluate: () => constant + }; + } +} + +// Zoom-dependent expressions may only use ["zoom"] as the input to a top-level "step" or "interpolate" +// expression (collectively referred to as a "curve"). The curve may be wrapped in one or more "let" or +// "coalesce" expressions. +function findZoomCurve(expression: Expression): Step | Interpolate | ParsingError | null { + let result = null; + if (expression instanceof Let) { + result = findZoomCurve(expression.result); + + } else if (expression instanceof Coalesce) { + for (const arg of expression.args) { + result = findZoomCurve(arg); + if (result) { + break; + } + } + + } else if ((expression instanceof Step || expression instanceof Interpolate) && + expression.input instanceof CompoundExpression && + expression.input.name === 'zoom') { + + result = expression; + } + + if (result instanceof ParsingError) { + return result; + } + + expression.eachChild((child) => { + const childResult = findZoomCurve(child); + if (childResult instanceof ParsingError) { + result = childResult; + } else if (!result && childResult) { + result = new ParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'); + } else if (result && childResult && result !== childResult) { + result = new ParsingError('', 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'); + } + }); + + return result; +} + +import {ColorType, StringType, NumberType, BooleanType, ValueType, FormattedType, ResolvedImageType, array} from './types'; + +function getExpectedType(spec: StylePropertySpecification): Type { + const types = { + color: ColorType, + string: StringType, + number: NumberType, + enum: StringType, + boolean: BooleanType, + formatted: FormattedType, + resolvedImage: ResolvedImageType + }; + + if (spec.type === 'array') { + return array(types[spec.value] || ValueType, spec.length); + } + + return types[spec.type]; +} + +function getDefaultValue(spec: StylePropertySpecification): Value { + if (spec.type === 'color' && isFunction(spec.default)) { + // Special case for heatmap-color: it uses the 'default:' to define a + // default color ramp, but createExpression expects a simple value to fall + // back to in case of runtime errors + return new Color(0, 0, 0, 0); + } else if (spec.type === 'color') { + return Color.parse(spec.default) || null; + } else if (spec.default === undefined) { + return null; + } else { + return spec.default; + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/expression/is_constant.js b/node_modules/mapbox-gl/src/style-spec/expression/is_constant.js new file mode 100644 index 0000000000000000000000000000000000000000..bb997e899a582b6bfe8e959046c5d9e80b550e6f --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/is_constant.js @@ -0,0 +1,59 @@ +// @flow + +import CompoundExpression from './compound_expression'; +import Within from './definitions/within'; +import type {Expression} from './expression.js'; + +function isFeatureConstant(e: Expression) { + if (e instanceof CompoundExpression) { + if (e.name === 'get' && e.args.length === 1) { + return false; + } else if (e.name === 'feature-state') { + return false; + } else if (e.name === 'has' && e.args.length === 1) { + return false; + } else if ( + e.name === 'properties' || + e.name === 'geometry-type' || + e.name === 'id' + ) { + return false; + } else if (/^filter-/.test(e.name)) { + return false; + } + } + + if (e instanceof Within) { + return false; + } + + let result = true; + e.eachChild(arg => { + if (result && !isFeatureConstant(arg)) { result = false; } + }); + return result; +} + +function isStateConstant(e: Expression) { + if (e instanceof CompoundExpression) { + if (e.name === 'feature-state') { + return false; + } + } + let result = true; + e.eachChild(arg => { + if (result && !isStateConstant(arg)) { result = false; } + }); + return result; +} + +function isGlobalPropertyConstant(e: Expression, properties: Array) { + if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) { return false; } + let result = true; + e.eachChild((arg) => { + if (result && !isGlobalPropertyConstant(arg, properties)) { result = false; } + }); + return result; +} + +export {isFeatureConstant, isGlobalPropertyConstant, isStateConstant}; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/parsing_context.js b/node_modules/mapbox-gl/src/style-spec/expression/parsing_context.js new file mode 100644 index 0000000000000000000000000000000000000000..7cf8ce94e8c63454db74ea0940a732096ad4fbb2 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/parsing_context.js @@ -0,0 +1,233 @@ +// @flow + +import Scope from './scope'; +import {checkSubtype} from './types'; +import ParsingError from './parsing_error'; +import Literal from './definitions/literal'; +import Assertion from './definitions/assertion'; +import Coercion from './definitions/coercion'; +import EvaluationContext from './evaluation_context'; +import CompoundExpression from './compound_expression'; +import CollatorExpression from './definitions/collator'; +import Within from './definitions/within'; +import {isGlobalPropertyConstant, isFeatureConstant} from './is_constant'; +import Var from './definitions/var'; + +import type {Expression, ExpressionRegistry} from './expression'; +import type {Type} from './types'; + +/** + * State associated parsing at a given point in an expression tree. + * @private + */ +class ParsingContext { + registry: ExpressionRegistry; + path: Array; + key: string; + scope: Scope; + errors: Array; + + // The expected type of this expression. Provided only to allow Expression + // implementations to infer argument types: Expression#parse() need not + // check that the output type of the parsed expression matches + // `expectedType`. + expectedType: ?Type; + + constructor( + registry: ExpressionRegistry, + path: Array = [], + expectedType: ?Type, + scope: Scope = new Scope(), + errors: Array = [] + ) { + this.registry = registry; + this.path = path; + this.key = path.map(part => `[${part}]`).join(''); + this.scope = scope; + this.errors = errors; + this.expectedType = expectedType; + } + + /** + * @param expr the JSON expression to parse + * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed + * @param options + * @param options.omitTypeAnnotations set true to omit inferred type annotations. Caller beware: with this option set, the parsed expression's type will NOT satisfy `expectedType` if it would normally be wrapped in an inferred annotation. + * @private + */ + parse( + expr: mixed, + index?: number, + expectedType?: ?Type, + bindings?: Array<[string, Expression]>, + options: {typeAnnotation?: 'assert' | 'coerce' | 'omit'} = {} + ): ?Expression { + if (index) { + return this.concat(index, expectedType, bindings)._parse(expr, options); + } + return this._parse(expr, options); + } + + _parse(expr: mixed, options: {typeAnnotation?: 'assert' | 'coerce' | 'omit'}): ?Expression { + if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') { + expr = ['literal', expr]; + } + + function annotate(parsed, type, typeAnnotation: 'assert' | 'coerce' | 'omit') { + if (typeAnnotation === 'assert') { + return new Assertion(type, [parsed]); + } else if (typeAnnotation === 'coerce') { + return new Coercion(type, [parsed]); + } else { + return parsed; + } + } + + if (Array.isArray(expr)) { + if (expr.length === 0) { + return this.error(`Expected an array with at least one element. If you wanted a literal array, use ["literal", []].`); + } + + const op = expr[0]; + if (typeof op !== 'string') { + this.error(`Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use ["literal", [...]].`, 0); + return null; + } + + const Expr = this.registry[op]; + if (Expr) { + let parsed = Expr.parse(expr, this); + if (!parsed) return null; + + if (this.expectedType) { + const expected = this.expectedType; + const actual = parsed.type; + + // When we expect a number, string, boolean, or array but have a value, wrap it in an assertion. + // When we expect a color or formatted string, but have a string or value, wrap it in a coercion. + // Otherwise, we do static type-checking. + // + // These behaviors are overridable for: + // * The "coalesce" operator, which needs to omit type annotations. + // * String-valued properties (e.g. `text-field`), where coercion is more convenient than assertion. + // + if ((expected.kind === 'string' || expected.kind === 'number' || expected.kind === 'boolean' || expected.kind === 'object' || expected.kind === 'array') && actual.kind === 'value') { + parsed = annotate(parsed, expected, options.typeAnnotation || 'assert'); + } else if ((expected.kind === 'color' || expected.kind === 'formatted' || expected.kind === 'resolvedImage') && (actual.kind === 'value' || actual.kind === 'string')) { + parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce'); + } else if (this.checkSubtype(expected, actual)) { + return null; + } + } + + // If an expression's arguments are all literals, we can evaluate + // it immediately and replace it with a literal value in the + // parsed/compiled result. Expressions that expect an image should + // not be resolved here so we can later get the available images. + if (!(parsed instanceof Literal) && (parsed.type.kind !== 'resolvedImage') && isConstant(parsed)) { + const ec = new EvaluationContext(); + try { + parsed = new Literal(parsed.type, parsed.evaluate(ec)); + } catch (e) { + this.error(e.message); + return null; + } + } + + return parsed; + } + + return this.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0); + } else if (typeof expr === 'undefined') { + return this.error(`'undefined' value invalid. Use null instead.`); + } else if (typeof expr === 'object') { + return this.error(`Bare objects invalid. Use ["literal", {...}] instead.`); + } else { + return this.error(`Expected an array, but found ${typeof expr} instead.`); + } + } + + /** + * Returns a copy of this context suitable for parsing the subexpression at + * index `index`, optionally appending to 'let' binding map. + * + * Note that `errors` property, intended for collecting errors while + * parsing, is copied by reference rather than cloned. + * @private + */ + concat(index: number, expectedType?: ?Type, bindings?: Array<[string, Expression]>) { + const path = typeof index === 'number' ? this.path.concat(index) : this.path; + const scope = bindings ? this.scope.concat(bindings) : this.scope; + return new ParsingContext( + this.registry, + path, + expectedType || null, + scope, + this.errors + ); + } + + /** + * Push a parsing (or type checking) error into the `this.errors` + * @param error The message + * @param keys Optionally specify the source of the error at a child + * of the current expression at `this.key`. + * @private + */ + error(error: string, ...keys: Array) { + const key = `${this.key}${keys.map(k => `[${k}]`).join('')}`; + this.errors.push(new ParsingError(key, error)); + } + + /** + * Returns null if `t` is a subtype of `expected`; otherwise returns an + * error message and also pushes it to `this.errors`. + */ + checkSubtype(expected: Type, t: Type): ?string { + const error = checkSubtype(expected, t); + if (error) this.error(error); + return error; + } +} + +export default ParsingContext; + +function isConstant(expression: Expression) { + if (expression instanceof Var) { + return isConstant(expression.boundExpression); + } else if (expression instanceof CompoundExpression && expression.name === 'error') { + return false; + } else if (expression instanceof CollatorExpression) { + // Although the results of a Collator expression with fixed arguments + // generally shouldn't change between executions, we can't serialize them + // as constant expressions because results change based on environment. + return false; + } else if (expression instanceof Within) { + return false; + } + + const isTypeAnnotation = expression instanceof Coercion || + expression instanceof Assertion; + + let childrenConstant = true; + expression.eachChild(child => { + // We can _almost_ assume that if `expressions` children are constant, + // they would already have been evaluated to Literal values when they + // were parsed. Type annotations are the exception, because they might + // have been inferred and added after a child was parsed. + + // So we recurse into isConstant() for the children of type annotations, + // but otherwise simply check whether they are Literals. + if (isTypeAnnotation) { + childrenConstant = childrenConstant && isConstant(child); + } else { + childrenConstant = childrenConstant && child instanceof Literal; + } + }); + if (!childrenConstant) { + return false; + } + + return isFeatureConstant(expression) && + isGlobalPropertyConstant(expression, ['zoom', 'heatmap-density', 'line-progress', 'accumulated', 'is-supported-script']); +} diff --git a/node_modules/mapbox-gl/src/style-spec/expression/parsing_error.js b/node_modules/mapbox-gl/src/style-spec/expression/parsing_error.js new file mode 100644 index 0000000000000000000000000000000000000000..8f676e81313dc39341fd55de3b70ae8042420cea --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/parsing_error.js @@ -0,0 +1,13 @@ +// @flow + +class ParsingError extends Error { + key: string; + message: string; + constructor(key: string, message: string) { + super(message); + this.message = message; + this.key = key; + } +} + +export default ParsingError; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/runtime_error.js b/node_modules/mapbox-gl/src/style-spec/expression/runtime_error.js new file mode 100644 index 0000000000000000000000000000000000000000..6c7c1144851e1ea965021b2d287da4a861873789 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/runtime_error.js @@ -0,0 +1,17 @@ +// @flow + +class RuntimeError { + name: string; + message: string; + + constructor(message: string) { + this.name = 'ExpressionEvaluationError'; + this.message = message; + } + + toJSON() { + return this.message; + } +} + +export default RuntimeError; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/scope.js b/node_modules/mapbox-gl/src/style-spec/expression/scope.js new file mode 100644 index 0000000000000000000000000000000000000000..b47e7cda5bd927904ec68d6554ebcd4d2b494ddd --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/scope.js @@ -0,0 +1,36 @@ +// @flow + +import type {Expression} from './expression'; + +/** + * Tracks `let` bindings during expression parsing. + * @private + */ +class Scope { + parent: ?Scope; + bindings: {[_: string]: Expression}; + constructor(parent?: Scope, bindings: Array<[string, Expression]> = []) { + this.parent = parent; + this.bindings = {}; + for (const [name, expression] of bindings) { + this.bindings[name] = expression; + } + } + + concat(bindings: Array<[string, Expression]>) { + return new Scope(this, bindings); + } + + get(name: string): Expression { + if (this.bindings[name]) { return this.bindings[name]; } + if (this.parent) { return this.parent.get(name); } + throw new Error(`${name} not found in scope.`); + } + + has(name: string): boolean { + if (this.bindings[name]) return true; + return this.parent ? this.parent.has(name) : false; + } +} + +export default Scope; diff --git a/node_modules/mapbox-gl/src/style-spec/expression/stops.js b/node_modules/mapbox-gl/src/style-spec/expression/stops.js new file mode 100644 index 0000000000000000000000000000000000000000..770ab4acfbaf8f98de3b8feb868892c6027953a5 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/stops.js @@ -0,0 +1,39 @@ +// @flow + +import RuntimeError from './runtime_error'; + +import type {Expression} from './expression'; + +export type Stops = Array<[number, Expression]>; + +/** + * Returns the index of the last stop <= input, or 0 if it doesn't exist. + * @private + */ +export function findStopLessThanOrEqualTo(stops: Array, input: number) { + const lastIndex = stops.length - 1; + let lowerIndex = 0; + let upperIndex = lastIndex; + let currentIndex = 0; + let currentValue, nextValue; + + while (lowerIndex <= upperIndex) { + currentIndex = Math.floor((lowerIndex + upperIndex) / 2); + currentValue = stops[currentIndex]; + nextValue = stops[currentIndex + 1]; + + if (currentValue <= input) { + if (currentIndex === lastIndex || input < nextValue) { // Search complete + return currentIndex; + } + + lowerIndex = currentIndex + 1; + } else if (currentValue > input) { + upperIndex = currentIndex - 1; + } else { + throw new RuntimeError('Input is not a number.'); + } + } + + return 0; +} diff --git a/node_modules/mapbox-gl/src/style-spec/expression/types.js b/node_modules/mapbox-gl/src/style-spec/expression/types.js new file mode 100644 index 0000000000000000000000000000000000000000..320c713de9496d087211dd488597e0c09c7f3b79 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/types.js @@ -0,0 +1,126 @@ +// @flow + +export type NullTypeT = { kind: 'null' }; +export type NumberTypeT = { kind: 'number' }; +export type StringTypeT = { kind: 'string' }; +export type BooleanTypeT = { kind: 'boolean' }; +export type ColorTypeT = { kind: 'color' }; +export type ObjectTypeT = { kind: 'object' }; +export type ValueTypeT = { kind: 'value' }; +export type ErrorTypeT = { kind: 'error' }; +export type CollatorTypeT = { kind: 'collator' }; +export type FormattedTypeT = { kind: 'formatted' }; +export type ResolvedImageTypeT = { kind: 'resolvedImage' }; + +export type EvaluationKind = 'constant' | 'source' | 'camera' | 'composite'; + +export type Type = + NullTypeT | + NumberTypeT | + StringTypeT | + BooleanTypeT | + ColorTypeT | + ObjectTypeT | + ValueTypeT | + ArrayType | // eslint-disable-line no-use-before-define + ErrorTypeT | + CollatorTypeT | + FormattedTypeT | + ResolvedImageTypeT + +export type ArrayType = { + kind: 'array', + itemType: Type, + N: ?number +} + +export type NativeType = 'number' | 'string' | 'boolean' | 'null' | 'array' | 'object' + +export const NullType = {kind: 'null'}; +export const NumberType = {kind: 'number'}; +export const StringType = {kind: 'string'}; +export const BooleanType = {kind: 'boolean'}; +export const ColorType = {kind: 'color'}; +export const ObjectType = {kind: 'object'}; +export const ValueType = {kind: 'value'}; +export const ErrorType = {kind: 'error'}; +export const CollatorType = {kind: 'collator'}; +export const FormattedType = {kind: 'formatted'}; +export const ResolvedImageType = {kind: 'resolvedImage'}; + +export function array(itemType: Type, N: ?number): ArrayType { + return { + kind: 'array', + itemType, + N + }; +} + +export function toString(type: Type): string { + if (type.kind === 'array') { + const itemType = toString(type.itemType); + return typeof type.N === 'number' ? + `array<${itemType}, ${type.N}>` : + type.itemType.kind === 'value' ? 'array' : `array<${itemType}>`; + } else { + return type.kind; + } +} + +const valueMemberTypes = [ + NullType, + NumberType, + StringType, + BooleanType, + ColorType, + FormattedType, + ObjectType, + array(ValueType), + ResolvedImageType +]; + +/** + * Returns null if `t` is a subtype of `expected`; otherwise returns an + * error message. + * @private + */ +export function checkSubtype(expected: Type, t: Type): ?string { + if (t.kind === 'error') { + // Error is a subtype of every type + return null; + } else if (expected.kind === 'array') { + if (t.kind === 'array' && + ((t.N === 0 && t.itemType.kind === 'value') || !checkSubtype(expected.itemType, t.itemType)) && + (typeof expected.N !== 'number' || expected.N === t.N)) { + return null; + } + } else if (expected.kind === t.kind) { + return null; + } else if (expected.kind === 'value') { + for (const memberType of valueMemberTypes) { + if (!checkSubtype(memberType, t)) { + return null; + } + } + } + + return `Expected ${toString(expected)} but found ${toString(t)} instead.`; +} + +export function isValidType(provided: Type, allowedTypes: Array): boolean { + return allowedTypes.some(t => t.kind === provided.kind); +} + +export function isValidNativeType(provided: any, allowedTypes: Array): boolean { + return allowedTypes.some(t => { + if (t === 'null') { + return provided === null; + } else if (t === 'array') { + return Array.isArray(provided); + } else if (t === 'object') { + return provided && !Array.isArray(provided) && typeof provided === 'object'; + } else { + return t === typeof provided; + } + }); +} diff --git a/node_modules/mapbox-gl/src/style-spec/expression/types/collator.js b/node_modules/mapbox-gl/src/style-spec/expression/types/collator.js new file mode 100644 index 0000000000000000000000000000000000000000..c9bcd61589f5b87b009c0c5b7c1a0ecc6c8f93e3 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/types/collator.js @@ -0,0 +1,61 @@ +// @flow + +// Flow type declarations for Intl cribbed from +// https://github.com/facebook/flow/issues/1270 + +declare var Intl: { + Collator: Class +}; + +declare class Intl$Collator { + constructor ( + locales?: string | string[], + options?: CollatorOptions + ): Intl$Collator; + + static ( + locales?: string | string[], + options?: CollatorOptions + ): Intl$Collator; + + compare (a: string, b: string): number; + + resolvedOptions(): any; +} + +type CollatorOptions = { + localeMatcher?: 'lookup' | 'best fit', + usage?: 'sort' | 'search', + sensitivity?: 'base' | 'accent' | 'case' | 'variant', + ignorePunctuation?: boolean, + numeric?: boolean, + caseFirst?: 'upper' | 'lower' | 'false' +} + +export default class Collator { + locale: string | null; + sensitivity: 'base' | 'accent' | 'case' | 'variant'; + collator: Intl$Collator; + + constructor(caseSensitive: boolean, diacriticSensitive: boolean, locale: string | null) { + if (caseSensitive) + this.sensitivity = diacriticSensitive ? 'variant' : 'case'; + else + this.sensitivity = diacriticSensitive ? 'accent' : 'base'; + + this.locale = locale; + this.collator = new Intl.Collator(this.locale ? this.locale : [], + {sensitivity: this.sensitivity, usage: 'search'}); + } + + compare(lhs: string, rhs: string): number { + return this.collator.compare(lhs, rhs); + } + + resolvedLocale(): string { + // We create a Collator without "usage: search" because we don't want + // the search options encoded in our result (e.g. "en-u-co-search") + return new Intl.Collator(this.locale ? this.locale : []) + .resolvedOptions().locale; + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/expression/types/formatted.js b/node_modules/mapbox-gl/src/style-spec/expression/types/formatted.js new file mode 100644 index 0000000000000000000000000000000000000000..378a0a2bd5d313cdad5f28c6665691d5fe0ac2ee --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/types/formatted.js @@ -0,0 +1,73 @@ +// @flow +import type Color from '../../util/color'; +import type ResolvedImage from '../types/resolved_image'; + +export class FormattedSection { + text: string; + image: ResolvedImage | null; + scale: number | null; + fontStack: string | null; + textColor: Color | null; + + constructor(text: string, image: ResolvedImage | null, scale: number | null, fontStack: string | null, textColor: Color | null) { + this.text = text; + this.image = image; + this.scale = scale; + this.fontStack = fontStack; + this.textColor = textColor; + } +} + +export default class Formatted { + sections: Array; + + constructor(sections: Array) { + this.sections = sections; + } + + static fromString(unformatted: string): Formatted { + return new Formatted([new FormattedSection(unformatted, null, null, null, null)]); + } + + isEmpty(): boolean { + if (this.sections.length === 0) return true; + return !this.sections.some(section => section.text.length !== 0 || + (section.image && section.image.name.length !== 0)); + } + + static factory(text: Formatted | string): Formatted { + if (text instanceof Formatted) { + return text; + } else { + return Formatted.fromString(text); + } + } + + toString(): string { + if (this.sections.length === 0) return ''; + return this.sections.map(section => section.text).join(''); + } + + serialize(): Array { + const serialized: Array = ["format"]; + for (const section of this.sections) { + if (section.image) { + serialized.push(["image", section.image.name]); + continue; + } + serialized.push(section.text); + const options: { [key: string]: mixed } = {}; + if (section.fontStack) { + options["text-font"] = ["literal", section.fontStack.split(',')]; + } + if (section.scale) { + options["font-scale"] = section.scale; + } + if (section.textColor) { + options["text-color"] = (["rgba"]: Array).concat(section.textColor.toArray()); + } + serialized.push(options); + } + return serialized; + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/expression/types/resolved_image.js b/node_modules/mapbox-gl/src/style-spec/expression/types/resolved_image.js new file mode 100644 index 0000000000000000000000000000000000000000..a9e92f8fedb8417b45c3a11cfaf0835f2053c215 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/types/resolved_image.js @@ -0,0 +1,29 @@ +// @flow + +export type ResolvedImageOptions = { + name: string, + available: boolean +}; + +export default class ResolvedImage { + name: string; + available: boolean; + + constructor(options: ResolvedImageOptions) { + this.name = options.name; + this.available = options.available; + } + + toString(): string { + return this.name; + } + + static fromString(name: string): ResolvedImage | null { + if (!name) return null; // treat empty values as no image + return new ResolvedImage({name, available: false}); + } + + serialize(): Array { + return ["image", this.name]; + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/expression/values.js b/node_modules/mapbox-gl/src/style-spec/expression/values.js new file mode 100644 index 0000000000000000000000000000000000000000..6c5e5407dc97b071636d16caa9f7b9a1858d7373 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/expression/values.js @@ -0,0 +1,123 @@ +// @flow + +import assert from 'assert'; + +import Color from '../util/color'; +import Collator from './types/collator'; +import Formatted from './types/formatted'; +import ResolvedImage from './types/resolved_image'; +import {NullType, NumberType, StringType, BooleanType, ColorType, ObjectType, ValueType, CollatorType, FormattedType, ResolvedImageType, array} from './types'; + +import type {Type} from './types'; + +export function validateRGBA(r: mixed, g: mixed, b: mixed, a?: mixed): string | null { + if (!( + typeof r === 'number' && r >= 0 && r <= 255 && + typeof g === 'number' && g >= 0 && g <= 255 && + typeof b === 'number' && b >= 0 && b <= 255 + )) { + const value = typeof a === 'number' ? [r, g, b, a] : [r, g, b]; + return `Invalid rgba value [${value.join(', ')}]: 'r', 'g', and 'b' must be between 0 and 255.`; + } + + if (!( + typeof a === 'undefined' || (typeof a === 'number' && a >= 0 && a <= 1) + )) { + return `Invalid rgba value [${[r, g, b, a].join(', ')}]: 'a' must be between 0 and 1.`; + } + + return null; +} + +export type Value = null | string | boolean | number | Color | Collator | Formatted | ResolvedImage | $ReadOnlyArray | { +[string]: Value } + +export function isValue(mixed: mixed): boolean { + if (mixed === null) { + return true; + } else if (typeof mixed === 'string') { + return true; + } else if (typeof mixed === 'boolean') { + return true; + } else if (typeof mixed === 'number') { + return true; + } else if (mixed instanceof Color) { + return true; + } else if (mixed instanceof Collator) { + return true; + } else if (mixed instanceof Formatted) { + return true; + } else if (mixed instanceof ResolvedImage) { + return true; + } else if (Array.isArray(mixed)) { + for (const item of mixed) { + if (!isValue(item)) { + return false; + } + } + return true; + } else if (typeof mixed === 'object') { + for (const key in mixed) { + if (!isValue(mixed[key])) { + return false; + } + } + return true; + } else { + return false; + } +} + +export function typeOf(value: Value): Type { + if (value === null) { + return NullType; + } else if (typeof value === 'string') { + return StringType; + } else if (typeof value === 'boolean') { + return BooleanType; + } else if (typeof value === 'number') { + return NumberType; + } else if (value instanceof Color) { + return ColorType; + } else if (value instanceof Collator) { + return CollatorType; + } else if (value instanceof Formatted) { + return FormattedType; + } else if (value instanceof ResolvedImage) { + return ResolvedImageType; + } else if (Array.isArray(value)) { + const length = value.length; + let itemType: Type | typeof undefined; + + for (const item of value) { + const t = typeOf(item); + if (!itemType) { + itemType = t; + } else if (itemType === t) { + continue; + } else { + itemType = ValueType; + break; + } + } + + return array(itemType || ValueType, length); + } else { + assert(typeof value === 'object'); + return ObjectType; + } +} + +export function toString(value: Value) { + const type = typeof value; + if (value === null) { + return ''; + } else if (type === 'string' || type === 'number' || type === 'boolean') { + return String(value); + } else if (value instanceof Color || value instanceof Formatted || value instanceof ResolvedImage) { + return value.toString(); + } else { + return JSON.stringify(value); + } +} + +export {Color, Collator}; diff --git a/node_modules/mapbox-gl/src/style-spec/feature_filter/README.md b/node_modules/mapbox-gl/src/style-spec/feature_filter/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6501c01a0f9960382ef25aefc63f9ddee15fbbb5 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/feature_filter/README.md @@ -0,0 +1,55 @@ +## Filter + +Filter expressions are used to target specific data in a layer. This library implements the semantics specified by the [Mapbox GL JS spec](https://www.mapbox.com/mapbox-gl-style-spec/#filter). + +### API + +`featureFilter(filter)` + +Given a filter expressed as nested arrays, return a new function +that evaluates whether a given feature (with a .properties or .tags property) +passes its test. + +#### Parameters + +| parameter | type | description | +| --------- | ----- | ---------------- | +| `filter` | Array | mapbox gl filter | + +**Returns** `Function`, filter-evaluating function + +### Usage + +``` javascript +var ff = require('@mapbox/mapbox-gl-style-spec').featureFilter; + +// will match a feature with class of street_limited, +// AND an admin_level less than or equal to 3, +// that's NOT a polygon. +var filter = [ + "all", + ["==", "class", "street_limited"], + ["<=", "admin_level", 3], + ["!=", "$type", "Polygon"] +] + +// will match a feature that has a class of +// wetland OR wetland_noveg. +// ["in", "class", "wetland", "wetland_noveg"] + +// testFilter will be a function that returns a boolean +var testFilter = ff(filter); + +// Layer feature that you're testing. Must have type +// and properties keys. +var feature = { + type: 2, + properties: { + class: "street_limited", + admin_level: 1 + } +}; + +// will return a boolean based on whether the feature matched the filter +return testFilter({zoom: 0}, feature); +``` diff --git a/node_modules/mapbox-gl/src/style-spec/feature_filter/convert.js b/node_modules/mapbox-gl/src/style-spec/feature_filter/convert.js new file mode 100644 index 0000000000000000000000000000000000000000..d7d473c2c4a3bf08444d1c74f4a4316911a2be52 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/feature_filter/convert.js @@ -0,0 +1,208 @@ +// @flow + +import {isExpressionFilter} from './index'; + +import type {FilterSpecification} from '../types'; + +type ExpectedTypes = {[_: string]: 'string' | 'number' | 'boolean'}; + +/** + * Convert the given legacy filter to (the JSON representation of) an + * equivalent expression + * @private + */ +export default function convertFilter(filter: FilterSpecification): mixed { + return _convertFilter(filter, {}); +} + +/* + * Convert the given filter to an expression, storing the expected types for + * any feature properties referenced in expectedTypes. + * + * These expected types are needed in order to construct preflight type checks + * needed for handling 'any' filters. A preflight type check is necessary in + * order to mimic legacy filters' semantics around expected type mismatches. + * For example, consider the legacy filter: + * + * ["any", ["all", [">", "y", 0], [">", "y", 0]], [">", "x", 0]] + * + * Naively, we might convert this to the expression: + * + * ["any", ["all", [">", ["get", "y"], 0], [">", ["get", "z"], 0]], [">", ["get", "x"], 0]] + * + * But if we tried to evaluate this against, say `{x: 1, y: null, z: 0}`, the + * [">", ["get", "y"], 0] would cause an evaluation error, leading to the + * entire filter returning false. Legacy filter semantics, though, ask for + * [">", "y", 0] to simply return `false` when `y` is of the wrong type, + * allowing the subsequent terms of the outer "any" expression to be evaluated + * (resulting, in this case, in a `true` value, because x > 0). + * + * We account for this by inserting a preflight type-checking expression before + * each "any" term, allowing us to avoid evaluating the actual converted filter + * if any type mismatches would cause it to produce an evalaution error: + * + * ["any", + * ["case", + * ["all", ["==", ["typeof", ["get", "y"]], "number"], ["==", ["typeof", ["get", "z"], "number]], + * ["all", [">", ["get", "y"], 0], [">", ["get", "z"], 0]], + * false + * ], + * ["case", + * ["==", ["typeof", ["get", "x"], "number"]], + * [">", ["get", "x"], 0], + * false + * ] + * ] + * + * An alternative, possibly more direct approach would be to use type checks + * in the conversion of each comparison operator, so that the converted version + * of each individual ==, >=, etc. would mimic the legacy filter semantics. The + * downside of this approach is that it can lead to many more type checks than + * would otherwise be necessary: outside the context of an "any" expression, + * bailing out due to a runtime type error (expression semantics) and returning + * false (legacy filter semantics) are equivalent: they cause the filter to + * produce a `false` result. + */ +function _convertFilter(filter: FilterSpecification, expectedTypes: ExpectedTypes): mixed { + if (isExpressionFilter(filter)) { return filter; } + + if (!filter) return true; + const op = filter[0]; + if (filter.length <= 1) return (op !== 'any'); + + let converted; + + if ( + op === '==' || + op === '!=' || + op === '<' || + op === '>' || + op === '<=' || + op === '>=' + ) { + const [, property, value] = (filter: any); + converted = convertComparisonOp(property, value, op, expectedTypes); + } else if (op === 'any') { + const children = (filter: any).slice(1).map(f => { + const types = {}; + const child = _convertFilter(f, types); + const typechecks = runtimeTypeChecks(types); + return typechecks === true ? child : ['case', typechecks, child, false]; + }); + return ['any'].concat(children); + } else if (op === 'all') { + const children = (filter: any).slice(1).map(f => _convertFilter(f, expectedTypes)); + return children.length > 1 ? ['all'].concat(children) : [].concat(...children); + } else if (op === 'none') { + return ['!', _convertFilter(['any'].concat(filter.slice(1)), {})]; + } else if (op === 'in') { + converted = convertInOp((filter[1]: any), filter.slice(2)); + } else if (op === '!in') { + converted = convertInOp((filter[1]: any), filter.slice(2), true); + } else if (op === 'has') { + converted = convertHasOp((filter[1]: any)); + } else if (op === '!has') { + converted = ['!', convertHasOp((filter[1]: any))]; + } else { + converted = true; + } + + return converted; +} + +// Given a set of feature properties and an expected type for each one, +// construct an boolean expression that tests whether each property has the +// right type. +// E.g.: for {name: 'string', population: 'number'}, return +// [ 'all', +// ['==', ['typeof', ['get', 'name'], 'string']], +// ['==', ['typeof', ['get', 'population'], 'number]] +// ] +function runtimeTypeChecks(expectedTypes: ExpectedTypes) { + const conditions = []; + for (const property in expectedTypes) { + const get = property === '$id' ? ['id'] : ['get', property]; + conditions.push(['==', ['typeof', get], expectedTypes[property]]); + } + if (conditions.length === 0) return true; + if (conditions.length === 1) return conditions[0]; + return ['all'].concat(conditions); +} + +function convertComparisonOp(property: string, value: any, op: string, expectedTypes: ?ExpectedTypes) { + let get; + if (property === '$type') { + return [op, ['geometry-type'], value]; + } else if (property === '$id') { + get = ['id']; + } else { + get = ['get', property]; + } + + if (expectedTypes && value !== null) { + const type = ((typeof value): any); + expectedTypes[property] = type; + } + + if (op === '==' && property !== '$id' && value === null) { + return [ + 'all', + ['has', property], // missing property != null for legacy filters + ['==', get, null] + ]; + } else if (op === '!=' && property !== '$id' && value === null) { + return [ + 'any', + ['!', ['has', property]], // missing property != null for legacy filters + ['!=', get, null] + ]; + } + + return [op, get, value]; +} + +function convertInOp(property: string, values: Array, negate = false) { + if (values.length === 0) return negate; + + let get; + if (property === '$type') { + get = ['geometry-type']; + } else if (property === '$id') { + get = ['id']; + } else { + get = ['get', property]; + } + + // Determine if the list of values to be searched is homogenously typed. + // If so (and if the type is string or number), then we can use a + // [match, input, [...values], true, false] construction rather than a + // bunch of `==` tests. + let uniformTypes = true; + const type = typeof values[0]; + for (const value of values) { + if (typeof value !== type) { + uniformTypes = false; + break; + } + } + + if (uniformTypes && (type === 'string' || type === 'number')) { + // Match expressions must have unique values. + const uniqueValues = values.sort().filter((v, i) => i === 0 || values[i - 1] !== v); + return ['match', get, uniqueValues, !negate, negate]; + } + + return [ negate ? 'all' : 'any' ].concat( + values.map(v => [negate ? '!=' : '==', get, v]) + ); +} + +function convertHasOp(property: string) { + if (property === '$type') { + return true; + } else if (property === '$id') { + return ['!=', ['id'], null]; + } else { + return ['has', property]; + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/feature_filter/index.js b/node_modules/mapbox-gl/src/style-spec/feature_filter/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a096d14ed73c96fa049afa1f4032583f0032bfbc --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/feature_filter/index.js @@ -0,0 +1,175 @@ +// @flow + +import {createExpression} from '../expression'; +import type {GlobalProperties, Feature} from '../expression'; +import type {CanonicalTileID} from '../../source/tile_id'; + +type FilterExpression = (globalProperties: GlobalProperties, feature: Feature, canonical?: CanonicalTileID) => boolean; +export type FeatureFilter ={filter: FilterExpression, needGeometry: boolean}; + +export default createFilter; +export {isExpressionFilter}; + +function isExpressionFilter(filter: any) { + if (filter === true || filter === false) { + return true; + } + + if (!Array.isArray(filter) || filter.length === 0) { + return false; + } + switch (filter[0]) { + case 'has': + return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type'; + + case 'in': + return filter.length >= 3 && (typeof filter[1] !== 'string' || Array.isArray(filter[2])); + + case '!in': + case '!has': + case 'none': + return false; + + case '==': + case '!=': + case '>': + case '>=': + case '<': + case '<=': + return filter.length !== 3 || (Array.isArray(filter[1]) || Array.isArray(filter[2])); + + case 'any': + case 'all': + for (const f of filter.slice(1)) { + if (!isExpressionFilter(f) && typeof f !== 'boolean') { + return false; + } + } + return true; + + default: + return true; + } +} + +const filterSpec = { + 'type': 'boolean', + 'default': false, + 'transition': false, + 'property-type': 'data-driven', + 'expression': { + 'interpolated': false, + 'parameters': ['zoom', 'feature'] + } +}; + +/** + * Given a filter expressed as nested arrays, return a new function + * that evaluates whether a given feature (with a .properties or .tags property) + * passes its test. + * + * @private + * @param {Array} filter mapbox gl filter + * @returns {Function} filter-evaluating function + */ +function createFilter(filter: any): FeatureFilter { + if (filter === null || filter === undefined) { + return {filter: () => true, needGeometry: false}; + } + + if (!isExpressionFilter(filter)) { + filter = convertFilter(filter); + } + + const compiled = createExpression(filter, filterSpec); + if (compiled.result === 'error') { + throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', ')); + } else { + const needGeometry = geometryNeeded(filter); + return {filter: (globalProperties: GlobalProperties, feature: Feature, canonical?: CanonicalTileID) => compiled.value.evaluate(globalProperties, feature, {}, canonical), + needGeometry}; + } +} + +// Comparison function to sort numbers and strings +function compare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} + +function geometryNeeded(filter) { + if (!Array.isArray(filter)) return false; + if (filter[0] === 'within') return true; + for (let index = 1; index < filter.length; index++) { + if (geometryNeeded(filter[index])) return true; + } + return false; +} + +function convertFilter(filter: ?Array): mixed { + if (!filter) return true; + const op = filter[0]; + if (filter.length <= 1) return (op !== 'any'); + const converted = + op === '==' ? convertComparisonOp(filter[1], filter[2], '==') : + op === '!=' ? convertNegation(convertComparisonOp(filter[1], filter[2], '==')) : + op === '<' || + op === '>' || + op === '<=' || + op === '>=' ? convertComparisonOp(filter[1], filter[2], op) : + op === 'any' ? convertDisjunctionOp(filter.slice(1)) : + op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter)) : + op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter).map(convertNegation)) : + op === 'in' ? convertInOp(filter[1], filter.slice(2)) : + op === '!in' ? convertNegation(convertInOp(filter[1], filter.slice(2))) : + op === 'has' ? convertHasOp(filter[1]) : + op === '!has' ? convertNegation(convertHasOp(filter[1])) : + op === 'within' ? filter : + true; + return converted; +} + +function convertComparisonOp(property: string, value: any, op: string) { + switch (property) { + case '$type': + return [`filter-type-${op}`, value]; + case '$id': + return [`filter-id-${op}`, value]; + default: + return [`filter-${op}`, property, value]; + } +} + +function convertDisjunctionOp(filters: Array>) { + return ['any'].concat(filters.map(convertFilter)); +} + +function convertInOp(property: string, values: Array) { + if (values.length === 0) { return false; } + switch (property) { + case '$type': + return [`filter-type-in`, ['literal', values]]; + case '$id': + return [`filter-id-in`, ['literal', values]]; + default: + if (values.length > 200 && !values.some(v => typeof v !== typeof values[0])) { + return ['filter-in-large', property, ['literal', values.sort(compare)]]; + } else { + return ['filter-in-small', property, ['literal', values]]; + } + } +} + +function convertHasOp(property: string) { + switch (property) { + case '$type': + return true; + case '$id': + return [`filter-has-id`]; + default: + return [`filter-has`, property]; + } +} + +function convertNegation(filter: mixed) { + return ['!', filter]; +} diff --git a/node_modules/mapbox-gl/src/style-spec/format.js b/node_modules/mapbox-gl/src/style-spec/format.js new file mode 100644 index 0000000000000000000000000000000000000000..d32d0e4abf3cbdd498b873adeb49963ebb95c5ec --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/format.js @@ -0,0 +1,51 @@ + +import reference from './reference/latest.js'; +import stringifyPretty from 'json-stringify-pretty-compact'; + +function sortKeysBy(obj, reference) { + const result = {}; + for (const key in reference) { + if (obj[key] !== undefined) { + result[key] = obj[key]; + } + } + for (const key in obj) { + if (result[key] === undefined) { + result[key] = obj[key]; + } + } + return result; +} + +/** + * Format a Mapbox GL Style. Returns a stringified style with its keys + * sorted in the same order as the reference style. + * + * The optional `space` argument is passed to + * [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) + * to generate formatted output. + * + * If `space` is unspecified, a default of `2` spaces will be used. + * + * @private + * @param {Object} style a Mapbox GL Style + * @param {number} [space] space argument to pass to `JSON.stringify` + * @returns {string} stringified formatted JSON + * @example + * var fs = require('fs'); + * var format = require('mapbox-gl-style-spec').format; + * var style = fs.readFileSync('./source.json', 'utf8'); + * fs.writeFileSync('./dest.json', format(style)); + * fs.writeFileSync('./dest.min.json', format(style, 0)); + */ +function format(style, space = 2) { + style = sortKeysBy(style, reference.$root); + + if (style.layers) { + style.layers = style.layers.map((layer) => sortKeysBy(layer, reference.layer)); + } + + return stringifyPretty(style, {indent: space}); +} + +export default format; diff --git a/node_modules/mapbox-gl/src/style-spec/function/convert.js b/node_modules/mapbox-gl/src/style-spec/function/convert.js new file mode 100644 index 0000000000000000000000000000000000000000..34624f4238598fd5c2cc972a668801900fbfbc00 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/function/convert.js @@ -0,0 +1,270 @@ +// @flow + +import assert from 'assert'; +import type {StylePropertySpecification} from '../style-spec'; + +export default convertFunction; + +function convertLiteral(value) { + return typeof value === 'object' ? ['literal', value] : value; +} + +function convertFunction(parameters: any, propertySpec: StylePropertySpecification) { + let stops = parameters.stops; + if (!stops) { + // identity function + return convertIdentityFunction(parameters, propertySpec); + } + + const zoomAndFeatureDependent = stops && typeof stops[0][0] === 'object'; + const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + const zoomDependent = zoomAndFeatureDependent || !featureDependent; + + stops = stops.map((stop) => { + if (!featureDependent && propertySpec.tokens && typeof stop[1] === 'string') { + return [stop[0], convertTokenString(stop[1])]; + } + return [stop[0], convertLiteral(stop[1])]; + }); + + if (zoomAndFeatureDependent) { + return convertZoomAndPropertyFunction(parameters, propertySpec, stops); + } else if (zoomDependent) { + return convertZoomFunction(parameters, propertySpec, stops); + } else { + return convertPropertyFunction(parameters, propertySpec, stops); + } +} + +function convertIdentityFunction(parameters, propertySpec): Array { + const get = ['get', parameters.property]; + + if (parameters.default === undefined) { + // By default, expressions for string-valued properties get coerced. To preserve + // legacy function semantics, insert an explicit assertion instead. + return propertySpec.type === 'string' ? ['string', get] : get; + } else if (propertySpec.type === 'enum') { + return [ + 'match', + get, + Object.keys(propertySpec.values), + get, + parameters.default + ]; + } else { + const expression = [propertySpec.type === 'color' ? 'to-color' : propertySpec.type, get, convertLiteral(parameters.default)]; + if (propertySpec.type === 'array') { + expression.splice(1, 0, propertySpec.value, propertySpec.length || null); + } + return expression; + } +} + +function getInterpolateOperator(parameters) { + switch (parameters.colorSpace) { + case 'hcl': return 'interpolate-hcl'; + case 'lab': return 'interpolate-lab'; + default: return 'interpolate'; + } +} + +function convertZoomAndPropertyFunction(parameters, propertySpec, stops) { + const featureFunctionParameters = {}; + const featureFunctionStops = {}; + const zoomStops = []; + for (let s = 0; s < stops.length; s++) { + const stop = stops[s]; + const zoom = stop[0].zoom; + if (featureFunctionParameters[zoom] === undefined) { + featureFunctionParameters[zoom] = { + zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default, + }; + featureFunctionStops[zoom] = []; + zoomStops.push(zoom); + } + featureFunctionStops[zoom].push([stop[0].value, stop[1]]); + } + + // the interpolation type for the zoom dimension of a zoom-and-property + // function is determined directly from the style property specification + // for which it's being used: linear for interpolatable properties, step + // otherwise. + const functionType = getFunctionType({}, propertySpec); + if (functionType === 'exponential') { + const expression = [getInterpolateOperator(parameters), ['linear'], ['zoom']]; + + for (const z of zoomStops) { + const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]); + appendStopPair(expression, z, output, false); + } + + return expression; + } else { + const expression = ['step', ['zoom']]; + + for (const z of zoomStops) { + const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]); + appendStopPair(expression, z, output, true); + } + + fixupDegenerateStepCurve(expression); + + return expression; + } +} + +function coalesce(a, b) { + if (a !== undefined) return a; + if (b !== undefined) return b; +} + +function getFallback(parameters, propertySpec) { + const defaultValue = convertLiteral(coalesce(parameters.default, propertySpec.default)); + + /* + * Some fields with type: resolvedImage have an undefined default. + * Because undefined is an invalid value for resolvedImage, set fallback to + * an empty string instead of undefined to ensure output + * passes validation. + */ + if (defaultValue === undefined && propertySpec.type === 'resolvedImage') { + return ''; + } + return defaultValue; +} + +function convertPropertyFunction(parameters, propertySpec, stops) { + const type = getFunctionType(parameters, propertySpec); + const get = ['get', parameters.property]; + if (type === 'categorical' && typeof stops[0][0] === 'boolean') { + assert(parameters.stops.length > 0 && parameters.stops.length <= 2); + const expression = ['case']; + for (const stop of stops) { + expression.push(['==', get, stop[0]], stop[1]); + } + + expression.push(getFallback(parameters, propertySpec)); + return expression; + } else if (type === 'categorical') { + const expression = ['match', get]; + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], false); + } + expression.push(getFallback(parameters, propertySpec)); + return expression; + } else if (type === 'interval') { + const expression = ['step', ['number', get]]; + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], true); + } + fixupDegenerateStepCurve(expression); + return parameters.default === undefined ? expression : [ + 'case', + ['==', ['typeof', get], 'number'], + expression, + convertLiteral(parameters.default) + ]; + } else if (type === 'exponential') { + const base = parameters.base !== undefined ? parameters.base : 1; + const expression = [ + getInterpolateOperator(parameters), + base === 1 ? ["linear"] : ["exponential", base], + ["number", get] + ]; + + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], false); + } + return parameters.default === undefined ? expression : [ + 'case', + ['==', ['typeof', get], 'number'], + expression, + convertLiteral(parameters.default) + ]; + } else { + throw new Error(`Unknown property function type ${type}`); + } +} + +function convertZoomFunction(parameters, propertySpec, stops, input = ['zoom']) { + const type = getFunctionType(parameters, propertySpec); + let expression; + let isStep = false; + if (type === 'interval') { + expression = ['step', input]; + isStep = true; + } else if (type === 'exponential') { + const base = parameters.base !== undefined ? parameters.base : 1; + expression = [getInterpolateOperator(parameters), base === 1 ? ["linear"] : ["exponential", base], input]; + + } else { + throw new Error(`Unknown zoom function type "${type}"`); + } + + for (const stop of stops) { + appendStopPair(expression, stop[0], stop[1], isStep); + } + + fixupDegenerateStepCurve(expression); + + return expression; +} + +function fixupDegenerateStepCurve(expression) { + // degenerate step curve (i.e. a constant function): add a noop stop + if (expression[0] === 'step' && expression.length === 3) { + expression.push(0); + expression.push(expression[3]); + } +} + +function appendStopPair(curve, input, output, isStep) { + // Skip duplicate stop values. They were not validated for functions, but they are for expressions. + // https://github.com/mapbox/mapbox-gl-js/issues/4107 + if (curve.length > 3 && input === curve[curve.length - 2]) { + return; + } + // step curves don't get the first input value, as it is redundant. + if (!(isStep && curve.length === 2)) { + curve.push(input); + } + curve.push(output); +} + +function getFunctionType(parameters, propertySpec) { + if (parameters.type) { + return parameters.type; + } else { + assert(propertySpec.expression); + return (propertySpec.expression: any).interpolated ? 'exponential' : 'interval'; + } +} + +// "String with {name} token" => ["concat", "String with ", ["get", "name"], " token"] +export function convertTokenString(s: string) { + const result = ['concat']; + const re = /{([^{}]+)}/g; + let pos = 0; + for (let match = re.exec(s); match !== null; match = re.exec(s)) { + const literal = s.slice(pos, re.lastIndex - match[0].length); + pos = re.lastIndex; + if (literal.length > 0) result.push(literal); + result.push(['get', match[1]]); + } + + if (result.length === 1) { + return s; + } + + if (pos < s.length) { + result.push(s.slice(pos)); + } else if (result.length === 2) { + return ['to-string', result[1]]; + } + + return result; +} + diff --git a/node_modules/mapbox-gl/src/style-spec/function/index.js b/node_modules/mapbox-gl/src/style-spec/function/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a78b575f7349aa41c900ead213a4dd2f7fe3f22e --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/function/index.js @@ -0,0 +1,262 @@ + +import * as colorSpaces from '../util/color_spaces'; +import Color from '../util/color'; +import extend from '../util/extend'; +import getType from '../util/get_type'; +import * as interpolate from '../util/interpolate'; +import Interpolate from '../expression/definitions/interpolate'; +import Formatted from '../expression/types/formatted'; +import ResolvedImage from '../expression/types/resolved_image'; +import {supportsInterpolation} from '../util/properties'; +import {findStopLessThanOrEqualTo} from '../expression/stops'; + +export function isFunction(value) { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function identityFunction(x) { + return x; +} + +export function createFunction(parameters, propertySpec) { + const isColor = propertySpec.type === 'color'; + const zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === 'object'; + const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined; + const zoomDependent = zoomAndFeatureDependent || !featureDependent; + const type = parameters.type || (supportsInterpolation(propertySpec) ? 'exponential' : 'interval'); + + if (isColor) { + parameters = extend({}, parameters); + + if (parameters.stops) { + parameters.stops = parameters.stops.map((stop) => { + return [stop[0], Color.parse(stop[1])]; + }); + } + + if (parameters.default) { + parameters.default = Color.parse(parameters.default); + } else { + parameters.default = Color.parse(propertySpec.default); + } + } + + if (parameters.colorSpace && parameters.colorSpace !== 'rgb' && !colorSpaces[parameters.colorSpace]) { // eslint-disable-line import/namespace + throw new Error(`Unknown color space: ${parameters.colorSpace}`); + } + + let innerFun; + let hashedStops; + let categoricalKeyType; + if (type === 'exponential') { + innerFun = evaluateExponentialFunction; + } else if (type === 'interval') { + innerFun = evaluateIntervalFunction; + } else if (type === 'categorical') { + innerFun = evaluateCategoricalFunction; + + // For categorical functions, generate an Object as a hashmap of the stops for fast searching + hashedStops = Object.create(null); + for (const stop of parameters.stops) { + hashedStops[stop[0]] = stop[1]; + } + + // Infer key type based on first stop key-- used to encforce strict type checking later + categoricalKeyType = typeof parameters.stops[0][0]; + + } else if (type === 'identity') { + innerFun = evaluateIdentityFunction; + } else { + throw new Error(`Unknown function type "${type}"`); + } + + if (zoomAndFeatureDependent) { + const featureFunctions = {}; + const zoomStops = []; + for (let s = 0; s < parameters.stops.length; s++) { + const stop = parameters.stops[s]; + const zoom = stop[0].zoom; + if (featureFunctions[zoom] === undefined) { + featureFunctions[zoom] = { + zoom, + type: parameters.type, + property: parameters.property, + default: parameters.default, + stops: [] + }; + zoomStops.push(zoom); + } + featureFunctions[zoom].stops.push([stop[0].value, stop[1]]); + } + + const featureFunctionStops = []; + for (const z of zoomStops) { + featureFunctionStops.push([featureFunctions[z].zoom, createFunction(featureFunctions[z], propertySpec)]); + } + + const interpolationType = {name: 'linear'}; + return { + kind: 'composite', + interpolationType, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), + zoomStops: featureFunctionStops.map(s => s[0]), + evaluate({zoom}, properties) { + return evaluateExponentialFunction({ + stops: featureFunctionStops, + base: parameters.base + }, propertySpec, zoom).evaluate(zoom, properties); + } + }; + } else if (zoomDependent) { + const interpolationType = type === 'exponential' ? + {name: 'exponential', base: parameters.base !== undefined ? parameters.base : 1} : null; + return { + kind: 'camera', + interpolationType, + interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType), + zoomStops: parameters.stops.map(s => s[0]), + evaluate: ({zoom}) => innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType) + }; + } else { + return { + kind: 'source', + evaluate(_, feature) { + const value = feature && feature.properties ? feature.properties[parameters.property] : undefined; + if (value === undefined) { + return coalesce(parameters.default, propertySpec.default); + } + return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType); + } + }; + } +} + +function coalesce(a, b, c) { + if (a !== undefined) return a; + if (b !== undefined) return b; + if (c !== undefined) return c; +} + +function evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) { + const evaluated = typeof input === keyType ? hashedStops[input] : undefined; // Enforce strict typing on input + return coalesce(evaluated, parameters.default, propertySpec.default); +} + +function evaluateIntervalFunction(parameters, propertySpec, input) { + // Edge cases + if (getType(input) !== 'number') return coalesce(parameters.default, propertySpec.default); + const n = parameters.stops.length; + if (n === 1) return parameters.stops[0][1]; + if (input <= parameters.stops[0][0]) return parameters.stops[0][1]; + if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1]; + + const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input); + + return parameters.stops[index][1]; +} + +function evaluateExponentialFunction(parameters, propertySpec, input) { + const base = parameters.base !== undefined ? parameters.base : 1; + + // Edge cases + if (getType(input) !== 'number') return coalesce(parameters.default, propertySpec.default); + const n = parameters.stops.length; + if (n === 1) return parameters.stops[0][1]; + if (input <= parameters.stops[0][0]) return parameters.stops[0][1]; + if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1]; + + const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input); + const t = interpolationFactor( + input, base, + parameters.stops[index][0], + parameters.stops[index + 1][0]); + + const outputLower = parameters.stops[index][1]; + const outputUpper = parameters.stops[index + 1][1]; + let interp = interpolate[propertySpec.type] || identityFunction; // eslint-disable-line import/namespace + + if (parameters.colorSpace && parameters.colorSpace !== 'rgb') { + const colorspace = colorSpaces[parameters.colorSpace]; // eslint-disable-line import/namespace + interp = (a, b) => colorspace.reverse(colorspace.interpolate(colorspace.forward(a), colorspace.forward(b), t)); + } + + if (typeof outputLower.evaluate === 'function') { + return { + evaluate(...args) { + const evaluatedLower = outputLower.evaluate.apply(undefined, args); + const evaluatedUpper = outputUpper.evaluate.apply(undefined, args); + // Special case for fill-outline-color, which has no spec default. + if (evaluatedLower === undefined || evaluatedUpper === undefined) { + return undefined; + } + return interp(evaluatedLower, evaluatedUpper, t); + } + }; + } + + return interp(outputLower, outputUpper, t); +} + +function evaluateIdentityFunction(parameters, propertySpec, input) { + if (propertySpec.type === 'color') { + input = Color.parse(input); + } else if (propertySpec.type === 'formatted') { + input = Formatted.fromString(input.toString()); + } else if (propertySpec.type === 'resolvedImage') { + input = ResolvedImage.fromString(input.toString()); + } else if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) { + input = undefined; + } + return coalesce(input, parameters.default, propertySpec.default); +} + +/** + * Returns a ratio that can be used to interpolate between exponential function + * stops. + * + * How it works: + * Two consecutive stop values define a (scaled and shifted) exponential + * function `f(x) = a * base^x + b`, where `base` is the user-specified base, + * and `a` and `b` are constants affording sufficient degrees of freedom to fit + * the function to the given stops. + * + * Here's a bit of algebra that lets us compute `f(x)` directly from the stop + * values without explicitly solving for `a` and `b`: + * + * First stop value: `f(x0) = y0 = a * base^x0 + b` + * Second stop value: `f(x1) = y1 = a * base^x1 + b` + * => `y1 - y0 = a(base^x1 - base^x0)` + * => `a = (y1 - y0)/(base^x1 - base^x0)` + * + * Desired value: `f(x) = y = a * base^x + b` + * => `f(x) = y0 + a * (base^x - base^x0)` + * + * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a + * little algebra: + * ``` + * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0) + * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0) + * ``` + * + * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have + * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as + * an interpolation factor between the two stops' output values. + * + * (Note: a slightly different form for `ratio`, + * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer + * expensive `Math.pow()` operations.) + * + * @private + */ +function interpolationFactor(input, base, lowerValue, upperValue) { + const difference = upperValue - lowerValue; + const progress = input - lowerValue; + + if (difference === 0) { + return 0; + } else if (base === 1) { + return progress / difference; + } else { + return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/group_by_layout.js b/node_modules/mapbox-gl/src/style-spec/group_by_layout.js new file mode 100644 index 0000000000000000000000000000000000000000..73238a87c164f909d9bcfc81b9ca794d0941c3e8 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/group_by_layout.js @@ -0,0 +1,75 @@ + +import refProperties from './util/ref_properties'; + +function stringify(obj) { + const type = typeof obj; + if (type === 'number' || type === 'boolean' || type === 'string' || obj === undefined || obj === null) + return JSON.stringify(obj); + + if (Array.isArray(obj)) { + let str = '['; + for (const val of obj) { + str += `${stringify(val)},`; + } + return `${str}]`; + } + + const keys = Object.keys(obj).sort(); + + let str = '{'; + for (let i = 0; i < keys.length; i++) { + str += `${JSON.stringify(keys[i])}:${stringify(obj[keys[i]])},`; + } + return `${str}}`; +} + +function getKey(layer) { + let key = ''; + for (const k of refProperties) { + key += `/${stringify(layer[k])}`; + } + return key; +} + +export default groupByLayout; + +/** + * Given an array of layers, return an array of arrays of layers where all + * layers in each group have identical layout-affecting properties. These + * are the properties that were formerly used by explicit `ref` mechanism + * for layers: 'type', 'source', 'source-layer', 'minzoom', 'maxzoom', + * 'filter', and 'layout'. + * + * The input is not modified. The output layers are references to the + * input layers. + * + * @private + * @param {Array} layers + * @param {Object} [cachedKeys] - an object to keep already calculated keys. + * @returns {Array>} + */ +function groupByLayout(layers, cachedKeys) { + const groups = {}; + + for (let i = 0; i < layers.length; i++) { + + const k = (cachedKeys && cachedKeys[layers[i].id]) || getKey(layers[i]); + // update the cache if there is one + if (cachedKeys) + cachedKeys[layers[i].id] = k; + + let group = groups[k]; + if (!group) { + group = groups[k] = []; + } + group.push(layers[i]); + } + + const result = []; + + for (const k in groups) { + result.push(groups[k]); + } + + return result; +} diff --git a/node_modules/mapbox-gl/src/style-spec/migrate.js b/node_modules/mapbox-gl/src/style-spec/migrate.js new file mode 100644 index 0000000000000000000000000000000000000000..d17de6afa9e37598a5bb688062356197a999f79a --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/migrate.js @@ -0,0 +1,36 @@ + +import migrateToV8 from './migrate/v8'; +import migrateToExpressions from './migrate/expressions'; + +/** + * Migrate a Mapbox GL Style to the latest version. + * + * @private + * @alias migrate + * @param {object} style a Mapbox GL Style + * @returns {Object} a migrated style + * @example + * var fs = require('fs'); + * var migrate = require('mapbox-gl-style-spec').migrate; + * var style = fs.readFileSync('./style.json', 'utf8'); + * fs.writeFileSync('./style.json', JSON.stringify(migrate(style))); + */ +export default function(style) { + let migrated = false; + + if (style.version === 7) { + style = migrateToV8(style); + migrated = true; + } + + if (style.version === 8) { + migrated = migrateToExpressions(style); + migrated = true; + } + + if (!migrated) { + throw new Error('cannot migrate from', style.version); + } + + return style; +} diff --git a/node_modules/mapbox-gl/src/style-spec/migrate/expressions.js b/node_modules/mapbox-gl/src/style-spec/migrate/expressions.js new file mode 100644 index 0000000000000000000000000000000000000000..544e6d15d0670ece970efe15dd1cff747969095a --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/migrate/expressions.js @@ -0,0 +1,39 @@ +// @flow + +import { + eachLayer, + eachProperty +} from '../visit'; +import {isExpression} from '../expression'; +import convertFunction, {convertTokenString} from '../function/convert'; +import convertFilter from '../feature_filter/convert'; + +import type {StyleSpecification} from '../types'; + +/** + * Migrate the given style object in place to use expressions. Specifically, + * this will convert (a) "stop" functions, and (b) legacy filters to their + * expression equivalents. + */ +export default function(style: StyleSpecification) { + const converted = []; + + eachLayer(style, (layer) => { + if (layer.filter) { + layer.filter = (convertFilter(layer.filter): any); + } + }); + + eachProperty(style, {paint: true, layout: true}, ({path, value, reference, set}) => { + if (isExpression(value)) return; + if (typeof value === 'object' && !Array.isArray(value)) { + set(convertFunction(value, reference)); + converted.push(path.join('.')); + } else if (reference.tokens && typeof value === 'string') { + set(convertTokenString(value)); + } + }); + + return style; +} + diff --git a/node_modules/mapbox-gl/src/style-spec/migrate/v8.js b/node_modules/mapbox-gl/src/style-spec/migrate/v8.js new file mode 100644 index 0000000000000000000000000000000000000000..632b938ee42d88a80d174002ec72895792d5320b --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/migrate/v8.js @@ -0,0 +1,203 @@ + +import URL from 'url'; +import {eachSource, eachLayer, eachProperty} from '../visit'; + +function eachLayout(layer, callback) { + for (const k in layer) { + if (k.indexOf('layout') === 0) { + callback(layer[k], k); + } + } +} + +function eachPaint(layer, callback) { + for (const k in layer) { + if (k.indexOf('paint') === 0) { + callback(layer[k], k); + } + } +} + +function resolveConstant(style, value) { + if (typeof value === 'string' && value[0] === '@') { + return resolveConstant(style, style.constants[value]); + } else { + return value; + } +} + +function isFunction(value) { + return Array.isArray(value.stops); +} + +function renameProperty(obj, from, to) { + obj[to] = obj[from]; delete obj[from]; +} + +export default function(style) { + style.version = 8; + + // Rename properties, reverse coordinates in source and layers + eachSource(style, (source) => { + if (source.type === 'video' && source.url !== undefined) { + renameProperty(source, 'url', 'urls'); + } + if (source.type === 'video') { + source.coordinates.forEach((coord) => { + return coord.reverse(); + }); + } + }); + + eachLayer(style, (layer) => { + eachLayout(layer, (layout) => { + if (layout['symbol-min-distance'] !== undefined) { + renameProperty(layout, 'symbol-min-distance', 'symbol-spacing'); + } + }); + + eachPaint(layer, (paint) => { + if (paint['background-image'] !== undefined) { + renameProperty(paint, 'background-image', 'background-pattern'); + } + if (paint['line-image'] !== undefined) { + renameProperty(paint, 'line-image', 'line-pattern'); + } + if (paint['fill-image'] !== undefined) { + renameProperty(paint, 'fill-image', 'fill-pattern'); + } + }); + }); + + // Inline Constants + eachProperty(style, {paint: true, layout: true}, (property) => { + const value = resolveConstant(style, property.value); + + if (isFunction(value)) { + value.stops.forEach((stop) => { + stop[1] = resolveConstant(style, stop[1]); + }); + } + + property.set(value); + }); + delete style.constants; + + eachLayer(style, (layer) => { + // get rid of text-max-size, icon-max-size + // turn text-size, icon-size into layout properties + // https://github.com/mapbox/mapbox-gl-style-spec/issues/255 + + eachLayout(layer, (layout) => { + delete layout['text-max-size']; + delete layout['icon-max-size']; + }); + + eachPaint(layer, (paint) => { + if (paint['text-size']) { + if (!layer.layout) layer.layout = {}; + layer.layout['text-size'] = paint['text-size']; + delete paint['text-size']; + } + + if (paint['icon-size']) { + if (!layer.layout) layer.layout = {}; + layer.layout['icon-size'] = paint['icon-size']; + delete paint['icon-size']; + } + }); + }); + + function migrateFontstackURL(input) { + const inputParsed = URL.parse(input); + const inputPathnameParts = inputParsed.pathname.split('/'); + + if (inputParsed.protocol !== 'mapbox:') { + return input; + + } else if (inputParsed.hostname === 'fontstack') { + assert(decodeURI(inputParsed.pathname) === '/{fontstack}/{range}.pbf'); + return 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf'; + + } else if (inputParsed.hostname === 'fonts') { + assert(inputPathnameParts[1] === 'v1'); + assert(decodeURI(inputPathnameParts[3]) === '{fontstack}'); + assert(decodeURI(inputPathnameParts[4]) === '{range}.pbf'); + return `mapbox://fonts/${inputPathnameParts[2]}/{fontstack}/{range}.pbf`; + + } else { + assert(false); + } + + function assert(predicate) { + if (!predicate) { + throw new Error(`Invalid font url: "${input}"`); + } + } + } + + if (style.glyphs) { + style.glyphs = migrateFontstackURL(style.glyphs); + } + + function migrateFontStack(font) { + function splitAndTrim(string) { + return string.split(',').map((s) => { + return s.trim(); + }); + } + + if (Array.isArray(font)) { + // Assume it's a previously migrated font-array. + return font; + + } else if (typeof font === 'string') { + return splitAndTrim(font); + + } else if (typeof font === 'object') { + font.stops.forEach((stop) => { + stop[1] = splitAndTrim(stop[1]); + }); + return font; + + } else { + throw new Error("unexpected font value"); + } + } + + eachLayer(style, (layer) => { + eachLayout(layer, (layout) => { + if (layout['text-font']) { + layout['text-font'] = migrateFontStack(layout['text-font']); + } + }); + }); + + // Reverse order of symbol layers. This is an imperfect migration. + // + // The order of a symbol layer in the layers list affects two things: + // - how it is drawn relative to other layers (like oneway arrows below bridges) + // - the placement priority compared to other layers + // + // It's impossible to reverse the placement priority without breaking the draw order + // in some cases. This migration only reverses the order of symbol layers that + // are above all other types of layers. + // + // Symbol layers that are at the top of the map preserve their priority. + // Symbol layers that are below another type (line, fill) of layer preserve their draw order. + + let firstSymbolLayer = 0; + for (let i = style.layers.length - 1; i >= 0; i--) { + const layer = style.layers[i]; + if (layer.type !== 'symbol') { + firstSymbolLayer = i + 1; + break; + } + } + + const symbolLayers = style.layers.splice(firstSymbolLayer); + symbolLayers.reverse(); + style.layers = style.layers.concat(symbolLayers); + + return style; +} diff --git a/node_modules/mapbox-gl/src/style-spec/migrate/v9.js b/node_modules/mapbox-gl/src/style-spec/migrate/v9.js new file mode 100644 index 0000000000000000000000000000000000000000..bb182dbfea17ecc9dc196f26b8d8df40d3af3c73 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/migrate/v9.js @@ -0,0 +1,26 @@ + +import deref from '../deref'; + +function eachLayer(style, callback) { + for (const k in style.layers) { + callback(style.layers[k]); + } +} + +export default function(style) { + style.version = 9; + + // remove user-specified refs + style.layers = deref(style.layers); + + // remove class-specific paint properties + eachLayer(style, (layer) => { + for (const k in layer) { + if (/paint\..*/.test(k)) { + delete layer[k]; + } + } + }); + + return style; +} diff --git a/node_modules/mapbox-gl/src/style-spec/package.json b/node_modules/mapbox-gl/src/style-spec/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c1f20eeafe4fa66c05072f264d43cf96406496a8 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/package.json @@ -0,0 +1,41 @@ +{ + "name": "@mapbox/mapbox-gl-style-spec", + "description": "a specification for mapbox gl styles", + "version": "13.18.0-dev", + "author": "Mapbox", + "keywords": [ + "mapbox", + "mapbox-gl", + "mapbox-gl-js" + ], + "license": "ISC", + "main": "./dist/index.js", + "module": "./dist/index.es.js", + "scripts": { + "copy-flow-typed": "cp -R ../../flow-typed .", + "build": "../../node_modules/.bin/rollup -c && ../../node_modules/.bin/rollup -c --environment esm", + "prepublish": "git clean -fdx && yarn copy-flow-typed && yarn build", + "postpublish": "rm -r flow-typed dist/index.js" + }, + "repository": { + "type": "git", + "url": "git@github.com:mapbox/mapbox-gl-js.git" + }, + "bin": { + "gl-style-migrate": "bin/gl-style-migrate", + "gl-style-validate": "bin/gl-style-validate", + "gl-style-format": "bin/gl-style-format", + "gl-style-composite": "bin/gl-style-composite" + }, + "dependencies": { + "@mapbox/jsonlint-lines-primitives": "~2.0.2", + "@mapbox/unitbezier": "^0.0.0", + "@mapbox/point-geometry": "^0.1.0", + "csscolorparser": "~1.0.2", + "json-stringify-pretty-compact": "^2.0.0", + "minimist": "^1.2.5", + "rw": "^1.3.3", + "sort-object": "^0.3.2" + }, + "sideEffects": false +} diff --git a/node_modules/mapbox-gl/src/style-spec/read_style.js b/node_modules/mapbox-gl/src/style-spec/read_style.js new file mode 100644 index 0000000000000000000000000000000000000000..1fd2aa72ee6b575014ed6f1a81b169c9e9a909c5 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/read_style.js @@ -0,0 +1,14 @@ +import ParsingError from './error/parsing_error'; +import jsonlint from '@mapbox/jsonlint-lines-primitives'; + +export default function readStyle(style) { + if (style instanceof String || typeof style === 'string' || style instanceof Buffer) { + try { + return jsonlint.parse(style.toString()); + } catch (e) { + throw new ParsingError(e); + } + } + + return style; +} diff --git a/node_modules/mapbox-gl/src/style-spec/reference/latest.js b/node_modules/mapbox-gl/src/style-spec/reference/latest.js new file mode 100644 index 0000000000000000000000000000000000000000..ab337fd3976efd23c834cc555be4fca281964922 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/reference/latest.js @@ -0,0 +1,3 @@ + +import spec from './v8.json'; +export default spec; diff --git a/node_modules/mapbox-gl/src/style-spec/reference/v8.json b/node_modules/mapbox-gl/src/style-spec/reference/v8.json new file mode 100644 index 0000000000000000000000000000000000000000..0a29e67b372b9f4b73e528d85bd42977c3744d03 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/reference/v8.json @@ -0,0 +1,5914 @@ +{ + "$version": 8, + "$root": { + "version": { + "required": true, + "type": "enum", + "values": [ + 8 + ], + "doc": "Style specification version number. Must be 8.", + "example": 8 + }, + "name": { + "type": "string", + "doc": "A human-readable name for the style.", + "example": "Bright" + }, + "metadata": { + "type": "*", + "doc": "Arbitrary properties useful to track with the stylesheet, but do not influence rendering. Properties should be prefixed to avoid collisions, like 'mapbox:'." + }, + "center": { + "type": "array", + "value": "number", + "doc": "Default map center in longitude and latitude. The style center will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + "example": [ + -73.9749, + 40.7736 + ] + }, + "zoom": { + "type": "number", + "doc": "Default zoom level. The style zoom will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + "example": 12.5 + }, + "bearing": { + "type": "number", + "default": 0, + "period": 360, + "units": "degrees", + "doc": "Default bearing, in degrees. The bearing is the compass direction that is \"up\"; for example, a bearing of 90° orients the map so that east is up. This value will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + "example": 29 + }, + "pitch": { + "type": "number", + "default": 0, + "units": "degrees", + "doc": "Default pitch, in degrees. Zero is perpendicular to the surface, for a look straight down at the map, while a greater value like 60 looks ahead towards the horizon. The style pitch will be used only if the map has not been positioned by other means (e.g. map options or user interaction).", + "example": 50 + }, + "light": { + "type": "light", + "doc": "The global light source.", + "example": { + "anchor": "viewport", + "color": "white", + "intensity": 0.4 + } + }, + "sources": { + "required": true, + "type": "sources", + "doc": "Data source specifications.", + "example": { + "mapbox-streets": { + "type": "vector", + "url": "mapbox://mapbox.mapbox-streets-v6" + } + } + }, + "sprite": { + "type": "string", + "doc": "A base URL for retrieving the sprite image and metadata. The extensions `.png`, `.json` and scale factor `@2x.png` will be automatically appended. This property is required if any layer uses the `background-pattern`, `fill-pattern`, `line-pattern`, `fill-extrusion-pattern`, or `icon-image` properties. The URL must be absolute, containing the [scheme, authority and path components](https://en.wikipedia.org/wiki/URL#Syntax).", + "example": "mapbox://sprites/mapbox/bright-v8" + }, + "glyphs": { + "type": "string", + "doc": "A URL template for loading signed-distance-field glyph sets in PBF format. The URL must include `{fontstack}` and `{range}` tokens. This property is required if any layer uses the `text-field` layout property. The URL must be absolute, containing the [scheme, authority and path components](https://en.wikipedia.org/wiki/URL#Syntax).", + "example": "mapbox://fonts/mapbox/{fontstack}/{range}.pbf" + }, + "transition": { + "type": "transition", + "doc": "A global transition definition to use as a default across properties, to be used for timing transitions between one value and the next when no property-specific transition is set. Collision-based symbol fading is controlled independently of the style's `transition` property.", + "example": { + "duration": 300, + "delay": 0 + } + }, + "layers": { + "required": true, + "type": "array", + "value": "layer", + "doc": "Layers will be drawn in the order of this array.", + "example": [ + { + "id": "water", + "source": "mapbox-streets", + "source-layer": "water", + "type": "fill", + "paint": { + "fill-color": "#00ffff" + } + } + ] + } + }, + "sources": { + "*": { + "type": "source", + "doc": "Specification of a data source. For vector and raster sources, either TileJSON or a URL to a TileJSON must be provided. For image and video sources, a URL must be provided. For GeoJSON sources, a URL or inline GeoJSON must be provided." + } + }, + "source": [ + "source_vector", + "source_raster", + "source_raster_dem", + "source_geojson", + "source_video", + "source_image" + ], + "source_vector": { + "type": { + "required": true, + "type": "enum", + "values": { + "vector": { + "doc": "A vector tile source." + } + }, + "doc": "The type of the source." + }, + "url": { + "type": "string", + "doc": "A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://`." + }, + "tiles": { + "type": "array", + "value": "string", + "doc": "An array of one or more tile source URLs, as in the TileJSON spec." + }, + "bounds": { + "type": "array", + "value": "number", + "length": 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ], + "doc": "An array containing the longitude and latitude of the southwest and northeast corners of the source's bounding box in the following order: `[sw.lng, sw.lat, ne.lng, ne.lat]`. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL." + }, + "scheme": { + "type": "enum", + "values": { + "xyz": { + "doc": "Slippy map tilenames scheme." + }, + "tms": { + "doc": "OSGeo spec scheme." + } + }, + "default": "xyz", + "doc": "Influences the y direction of the tile coordinates. The global-mercator (aka Spherical Mercator) profile is assumed." + }, + "minzoom": { + "type": "number", + "default": 0, + "doc": "Minimum zoom level for which tiles are available, as in the TileJSON spec." + }, + "maxzoom": { + "type": "number", + "default": 22, + "doc": "Maximum zoom level for which tiles are available, as in the TileJSON spec. Data from tiles at the maxzoom are used when displaying the map at higher zoom levels." + }, + "attribution": { + "type": "string", + "doc": "Contains an attribution to be displayed when the map is shown to a user." + }, + "promoteId": { + "type": "promoteId", + "doc": "A property to use as a feature id (for feature state). Either a property name, or an object of the form `{: }`. If specified as a string for a vector tile source, the same property is used across all its source layers." + }, + "volatile": { + "type": "boolean", + "default": false, + "doc": "A setting to determine whether a source's tiles are cached locally.", + "sdk-support": { + "basic functionality": { + "android": "9.3.0", + "ios": "5.10.0" + } + } + }, + "*": { + "type": "*", + "doc": "Other keys to configure the data source." + } + }, + "source_raster": { + "type": { + "required": true, + "type": "enum", + "values": { + "raster": { + "doc": "A raster tile source." + } + }, + "doc": "The type of the source." + }, + "url": { + "type": "string", + "doc": "A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://`." + }, + "tiles": { + "type": "array", + "value": "string", + "doc": "An array of one or more tile source URLs, as in the TileJSON spec." + }, + "bounds": { + "type": "array", + "value": "number", + "length": 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ], + "doc": "An array containing the longitude and latitude of the southwest and northeast corners of the source's bounding box in the following order: `[sw.lng, sw.lat, ne.lng, ne.lat]`. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL." + }, + "minzoom": { + "type": "number", + "default": 0, + "doc": "Minimum zoom level for which tiles are available, as in the TileJSON spec." + }, + "maxzoom": { + "type": "number", + "default": 22, + "doc": "Maximum zoom level for which tiles are available, as in the TileJSON spec. Data from tiles at the maxzoom are used when displaying the map at higher zoom levels." + }, + "tileSize": { + "type": "number", + "default": 512, + "units": "pixels", + "doc": "The minimum visual size to display tiles for this layer. Only configurable for raster layers." + }, + "scheme": { + "type": "enum", + "values": { + "xyz": { + "doc": "Slippy map tilenames scheme." + }, + "tms": { + "doc": "OSGeo spec scheme." + } + }, + "default": "xyz", + "doc": "Influences the y direction of the tile coordinates. The global-mercator (aka Spherical Mercator) profile is assumed." + }, + "attribution": { + "type": "string", + "doc": "Contains an attribution to be displayed when the map is shown to a user." + }, + "volatile": { + "type": "boolean", + "default": false, + "doc": "A setting to determine whether a source's tiles are cached locally.", + "sdk-support": { + "basic functionality": { + "android": "9.3.0", + "ios": "5.10.0" + } + } + }, + "*": { + "type": "*", + "doc": "Other keys to configure the data source." + } + }, + "source_raster_dem": { + "type": { + "required": true, + "type": "enum", + "values": { + "raster-dem": { + "doc": "A RGB-encoded raster DEM source" + } + }, + "doc": "The type of the source." + }, + "url": { + "type": "string", + "doc": "A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://`." + }, + "tiles": { + "type": "array", + "value": "string", + "doc": "An array of one or more tile source URLs, as in the TileJSON spec." + }, + "bounds": { + "type": "array", + "value": "number", + "length": 4, + "default": [ + -180, + -85.051129, + 180, + 85.051129 + ], + "doc": "An array containing the longitude and latitude of the southwest and northeast corners of the source's bounding box in the following order: `[sw.lng, sw.lat, ne.lng, ne.lat]`. When this property is included in a source, no tiles outside of the given bounds are requested by Mapbox GL." + }, + "minzoom": { + "type": "number", + "default": 0, + "doc": "Minimum zoom level for which tiles are available, as in the TileJSON spec." + }, + "maxzoom": { + "type": "number", + "default": 22, + "doc": "Maximum zoom level for which tiles are available, as in the TileJSON spec. Data from tiles at the maxzoom are used when displaying the map at higher zoom levels." + }, + "tileSize": { + "type": "number", + "default": 512, + "units": "pixels", + "doc": "The minimum visual size to display tiles for this layer. Only configurable for raster layers." + }, + "attribution": { + "type": "string", + "doc": "Contains an attribution to be displayed when the map is shown to a user." + }, + "encoding": { + "type": "enum", + "values": { + "terrarium": { + "doc": "Terrarium format PNG tiles. See https://aws.amazon.com/es/public-datasets/terrain/ for more info." + }, + "mapbox": { + "doc": "Mapbox Terrain RGB tiles. See https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb for more info." + } + }, + "default": "mapbox", + "doc": "The encoding used by this source. Mapbox Terrain RGB is used by default" + }, + "volatile": { + "type": "boolean", + "default": false, + "doc": "A setting to determine whether a source's tiles are cached locally.", + "sdk-support": { + "basic functionality": { + "android": "9.3.0", + "ios": "5.10.0" + } + } + }, + "*": { + "type": "*", + "doc": "Other keys to configure the data source." + } + }, + "source_geojson": { + "type": { + "required": true, + "type": "enum", + "values": { + "geojson": { + "doc": "A GeoJSON data source." + } + }, + "doc": "The data type of the GeoJSON source." + }, + "data": { + "type": "*", + "doc": "A URL to a GeoJSON file, or inline GeoJSON." + }, + "maxzoom": { + "type": "number", + "default": 18, + "doc": "Maximum zoom level at which to create vector tiles (higher means greater detail at high zoom levels)." + }, + "attribution": { + "type": "string", + "doc": "Contains an attribution to be displayed when the map is shown to a user." + }, + "buffer": { + "type": "number", + "default": 128, + "maximum": 512, + "minimum": 0, + "doc": "Size of the tile buffer on each side. A value of 0 produces no buffer. A value of 512 produces a buffer as wide as the tile itself. Larger values produce fewer rendering artifacts near tile edges and slower performance." + }, + "filter": { + "type": "*", + "doc": "An expression for filtering features prior to processing them for rendering." + }, + "tolerance": { + "type": "number", + "default": 0.375, + "doc": "Douglas-Peucker simplification tolerance (higher means simpler geometries and faster performance)." + }, + "cluster": { + "type": "boolean", + "default": false, + "doc": "If the data is a collection of point features, setting this to true clusters the points by radius into groups. Cluster groups become new `Point` features in the source with additional properties:\n * `cluster` Is `true` if the point is a cluster \n * `cluster_id` A unqiue id for the cluster to be used in conjunction with the [cluster inspection methods](https://www.mapbox.com/mapbox-gl-js/api/#geojsonsource#getclusterexpansionzoom)\n * `point_count` Number of original points grouped into this cluster\n * `point_count_abbreviated` An abbreviated point count" + }, + "clusterRadius": { + "type": "number", + "default": 50, + "minimum": 0, + "doc": "Radius of each cluster if clustering is enabled. A value of 512 indicates a radius equal to the width of a tile." + }, + "clusterMaxZoom": { + "type": "number", + "doc": "Max zoom on which to cluster points if clustering is enabled. Defaults to one zoom less than maxzoom (so that last zoom features are not clustered). Clusters are re-evaluated at integer zoom levels so setting clusterMaxZoom to 14 means the clusters will be displayed until z15." + }, + "clusterMinPoints": { + "type": "number", + "doc": "Minimum number of points necessary to form a cluster if clustering is enabled. Defaults to `2`." + }, + "clusterProperties": { + "type": "*", + "doc": "An object defining custom properties on the generated clusters if clustering is enabled, aggregating values from clustered points. Has the form `{\"property_name\": [operator, map_expression]}`. `operator` is any expression function that accepts at least 2 operands (e.g. `\"+\"` or `\"max\"`) — it accumulates the property value from clusters/points the cluster contains; `map_expression` produces the value of a single point.\n\nExample: `{\"sum\": [\"+\", [\"get\", \"scalerank\"]]}`.\n\nFor more advanced use cases, in place of `operator`, you can use a custom reduce expression that references a special `[\"accumulated\"]` value, e.g.:\n`{\"sum\": [[\"+\", [\"accumulated\"], [\"get\", \"sum\"]], [\"get\", \"scalerank\"]]}`" + }, + "lineMetrics": { + "type": "boolean", + "default": false, + "doc": "Whether to calculate line distance metrics. This is required for line layers that specify `line-gradient` values." + }, + "generateId": { + "type": "boolean", + "default": false, + "doc": "Whether to generate ids for the geojson features. When enabled, the `feature.id` property will be auto assigned based on its index in the `features` array, over-writing any previous values." + }, + "promoteId": { + "type": "promoteId", + "doc": "A property to use as a feature id (for feature state). Either a property name, or an object of the form `{: }`." + } + }, + "source_video": { + "type": { + "required": true, + "type": "enum", + "values": { + "video": { + "doc": "A video data source." + } + }, + "doc": "The data type of the video source." + }, + "urls": { + "required": true, + "type": "array", + "value": "string", + "doc": "URLs to video content in order of preferred format." + }, + "coordinates": { + "required": true, + "doc": "Corners of video specified in longitude, latitude pairs.", + "type": "array", + "length": 4, + "value": { + "type": "array", + "length": 2, + "value": "number", + "doc": "A single longitude, latitude pair." + } + } + }, + "source_image": { + "type": { + "required": true, + "type": "enum", + "values": { + "image": { + "doc": "An image data source." + } + }, + "doc": "The data type of the image source." + }, + "url": { + "required": true, + "type": "string", + "doc": "URL that points to an image." + }, + "coordinates": { + "required": true, + "doc": "Corners of image specified in longitude, latitude pairs.", + "type": "array", + "length": 4, + "value": { + "type": "array", + "length": 2, + "value": "number", + "doc": "A single longitude, latitude pair." + } + } + }, + "layer": { + "id": { + "type": "string", + "doc": "Unique layer name.", + "required": true + }, + "type": { + "type": "enum", + "values": { + "fill": { + "doc": "A filled polygon with an optional stroked border.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + } + }, + "line": { + "doc": "A stroked line.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + } + }, + "symbol": { + "doc": "An icon or a text label.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + } + }, + "circle": { + "doc": "A filled circle.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + } + }, + "heatmap": { + "doc": "A heatmap.", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "fill-extrusion": { + "doc": "An extruded (3D) polygon.", + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + } + }, + "raster": { + "doc": "Raster map textures such as satellite imagery.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + } + }, + "hillshade": { + "doc": "Client-side hillshading visualization based on DEM data. Currently, the implementation only supports Mapbox Terrain RGB and Mapzen Terrarium tiles.", + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "background": { + "doc": "The background color or pattern of the map.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + } + } + }, + "doc": "Rendering type of this layer.", + "required": true + }, + "metadata": { + "type": "*", + "doc": "Arbitrary properties useful to track with the layer, but do not influence rendering. Properties should be prefixed to avoid collisions, like 'mapbox:'." + }, + "source": { + "type": "string", + "doc": "Name of a source description to be used for this layer. Required for all layer types except `background`." + }, + "source-layer": { + "type": "string", + "doc": "Layer to use from a vector tile source. Required for vector tile sources; prohibited for all other source types, including GeoJSON sources." + }, + "minzoom": { + "type": "number", + "minimum": 0, + "maximum": 24, + "doc": "The minimum zoom level for the layer. At zoom levels less than the minzoom, the layer will be hidden." + }, + "maxzoom": { + "type": "number", + "minimum": 0, + "maximum": 24, + "doc": "The maximum zoom level for the layer. At zoom levels equal to or greater than the maxzoom, the layer will be hidden." + }, + "filter": { + "type": "filter", + "doc": "A expression specifying conditions on source features. Only features that match the filter are displayed. Zoom expressions in filters are only evaluated at integer zoom levels. The `feature-state` expression is not supported in filter expressions." + }, + "layout": { + "type": "layout", + "doc": "Layout properties for the layer." + }, + "paint": { + "type": "paint", + "doc": "Default paint properties for this layer." + } + }, + "layout": [ + "layout_fill", + "layout_line", + "layout_circle", + "layout_heatmap", + "layout_fill-extrusion", + "layout_symbol", + "layout_raster", + "layout_hillshade", + "layout_background" + ], + "layout_background": { + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "property-type": "constant" + } + }, + "layout_fill": { + "fill-sort-key": { + "type": "number", + "doc": "Sorts features in ascending order based on this value. Features with a higher sort key will appear above features with a lower sort key.", + "sdk-support": { + "basic functionality": { + "js": "1.2.0", + "android": "9.1.0", + "ios": "5.8.0", + "macos": "0.15.0" + }, + "data-driven styling": { + "js": "1.2.0", + "android": "9.1.0", + "ios": "5.8.0", + "macos": "0.15.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "property-type": "constant" + } + }, + "layout_circle": { + "circle-sort-key": { + "type": "number", + "doc": "Sorts features in ascending order based on this value. Features with a higher sort key will appear above features with a lower sort key.", + "sdk-support": { + "basic functionality": { + "js": "1.2.0", + "android": "9.2.0", + "ios": "5.9.0", + "macos": "0.16.0" + }, + "data-driven styling": { + "js": "1.2.0", + "android": "9.2.0", + "ios": "5.9.0", + "macos": "0.16.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "property-type": "constant" + } + }, + "layout_heatmap": { + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "property-type": "constant" + } + }, + "layout_fill-extrusion": { + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "property-type": "constant" + } + }, + "layout_line": { + "line-cap": { + "type": "enum", + "values": { + "butt": { + "doc": "A cap with a squared-off end which is drawn to the exact endpoint of the line." + }, + "round": { + "doc": "A cap with a rounded end which is drawn beyond the endpoint of the line at a radius of one-half of the line's width and centered on the endpoint of the line." + }, + "square": { + "doc": "A cap with a squared-off end which is drawn beyond the endpoint of the line at a distance of one-half of the line's width." + } + }, + "default": "butt", + "doc": "The display of line endings.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-join": { + "type": "enum", + "values": { + "bevel": { + "doc": "A join with a squared-off end which is drawn beyond the endpoint of the line at a distance of one-half of the line's width." + }, + "round": { + "doc": "A join with a rounded end which is drawn beyond the endpoint of the line at a radius of one-half of the line's width and centered on the endpoint of the line." + }, + "miter": { + "doc": "A join with a sharp, angled corner which is drawn with the outer sides beyond the endpoint of the path until they meet." + } + }, + "default": "miter", + "doc": "The display of lines when joining.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.40.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "line-miter-limit": { + "type": "number", + "default": 2, + "doc": "Used to automatically convert miter joins to bevel joins for sharp angles.", + "requires": [ + { + "line-join": "miter" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-round-limit": { + "type": "number", + "default": 1.05, + "doc": "Used to automatically convert round joins to miter joins for shallow angles.", + "requires": [ + { + "line-join": "round" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-sort-key": { + "type": "number", + "doc": "Sorts features in ascending order based on this value. Features with a higher sort key will appear above features with a lower sort key.", + "sdk-support": { + "basic functionality": { + "js": "1.2.0", + "android": "9.1.0", + "ios": "5.8.0", + "macos": "0.15.0" + }, + "data-driven styling": { + "js": "1.2.0", + "android": "9.1.0", + "ios": "5.8.0", + "macos": "0.15.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "property-type": "constant" + } + }, + "layout_symbol": { + "symbol-placement": { + "type": "enum", + "values": { + "point": { + "doc": "The label is placed at the point where the geometry is located." + }, + "line": { + "doc": "The label is placed along the line of the geometry. Can only be used on `LineString` and `Polygon` geometries." + }, + "line-center": { + "doc": "The label is placed at the center of the line of the geometry. Can only be used on `LineString` and `Polygon` geometries. Note that a single feature in a vector tile may contain multiple line geometries." + } + }, + "default": "point", + "doc": "Label placement relative to its geometry.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "`line-center` value": { + "js": "0.47.0", + "android": "6.4.0", + "ios": "4.3.0", + "macos": "0.10.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-spacing": { + "type": "number", + "default": 250, + "minimum": 1, + "units": "pixels", + "doc": "Distance between two symbol anchors.", + "requires": [ + { + "symbol-placement": "line" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-avoid-edges": { + "type": "boolean", + "default": false, + "doc": "If true, the symbols will not cross tile edges to avoid mutual collisions. Recommended in layers that don't have enough padding in the vector tile to prevent collisions, or if it is a point symbol layer placed after a line symbol layer. When using a client that supports global collision detection, like Mapbox GL JS version 0.42.0 or greater, enabling this property is not needed to prevent clipped labels at tile boundaries.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "symbol-sort-key": { + "type": "number", + "doc": "Sorts features in ascending order based on this value. Features with lower sort keys are drawn and placed first. When `icon-allow-overlap` or `text-allow-overlap` is `false`, features with a lower sort key will have priority during placement. When `icon-allow-overlap` or `text-allow-overlap` is set to `true`, features with a higher sort key will overlap over features with a lower sort key.", + "sdk-support": { + "basic functionality": { + "js": "0.53.0", + "android": "7.4.0", + "ios": "4.11.0", + "macos": "0.14.0" + }, + "data-driven styling": { + "js": "0.53.0", + "android": "7.4.0", + "ios": "4.11.0", + "macos": "0.14.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "symbol-z-order": { + "type": "enum", + "values": { + "auto": { + "doc": "Sorts symbols by `symbol-sort-key` if set. Otherwise, sorts symbols by their y-position relative to the viewport if `icon-allow-overlap` or `text-allow-overlap` is set to `true` or `icon-ignore-placement` or `text-ignore-placement` is `false`." + }, + "viewport-y": { + "doc": "Sorts symbols by their y-position relative to the viewport if `icon-allow-overlap` or `text-allow-overlap` is set to `true` or `icon-ignore-placement` or `text-ignore-placement` is `false`." + }, + "source": { + "doc": "Sorts symbols by `symbol-sort-key` if set. Otherwise, no sorting is applied; symbols are rendered in the same order as the source data." + } + }, + "default": "auto", + "doc": "Determines whether overlapping symbols in the same layer are rendered in the order that they appear in the data source or by their y-position relative to the viewport. To control the order and prioritization of symbols otherwise, use `symbol-sort-key`.", + "sdk-support": { + "basic functionality": { + "js": "0.49.0", + "android": "6.6.0", + "ios": "4.5.0", + "macos": "0.12.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-allow-overlap": { + "type": "boolean", + "default": false, + "doc": "If true, the icon will be visible even if it collides with other previously drawn symbols.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-ignore-placement": { + "type": "boolean", + "default": false, + "doc": "If true, other symbols can be visible even if they collide with the icon.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-optional": { + "type": "boolean", + "default": false, + "doc": "If true, text will display without their corresponding icons when the icon collides with other symbols and the text does not.", + "requires": [ + "icon-image", + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-rotation-alignment": { + "type": "enum", + "values": { + "map": { + "doc": "When `symbol-placement` is set to `point`, aligns icons east-west. When `symbol-placement` is set to `line` or `line-center`, aligns icon x-axes with the line." + }, + "viewport": { + "doc": "Produces icons whose x-axes are aligned with the x-axis of the viewport, regardless of the value of `symbol-placement`." + }, + "auto": { + "doc": "When `symbol-placement` is set to `point`, this is equivalent to `viewport`. When `symbol-placement` is set to `line` or `line-center`, this is equivalent to `map`." + } + }, + "default": "auto", + "doc": "In combination with `symbol-placement`, determines the rotation behavior of icons.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "`auto` value": { + "js": "0.25.0", + "android": "4.2.0", + "ios": "3.4.0", + "macos": "0.3.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-size": { + "type": "number", + "default": 1, + "minimum": 0, + "units": "factor of the original icon size", + "doc": "Scales the original size of the icon by the provided factor. The new pixel size of the image will be the original pixel size multiplied by `icon-size`. 1 is the original size; 3 triples the size of the image.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.35.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-text-fit": { + "type": "enum", + "values": { + "none": { + "doc": "The icon is displayed at its intrinsic aspect ratio." + }, + "width": { + "doc": "The icon is scaled in the x-dimension to fit the width of the text." + }, + "height": { + "doc": "The icon is scaled in the y-dimension to fit the height of the text." + }, + "both": { + "doc": "The icon is scaled in both x- and y-dimensions." + } + }, + "default": "none", + "doc": "Scales the icon to fit around the associated text.", + "requires": [ + "icon-image", + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.21.0", + "android": "4.2.0", + "ios": "3.4.0", + "macos": "0.2.1" + }, + "stretchable icons": { + "js": "1.6.0", + "android": "9.2.0", + "ios": "5.8.0", + "macos": "0.15.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-text-fit-padding": { + "type": "array", + "value": "number", + "length": 4, + "default": [ + 0, + 0, + 0, + 0 + ], + "units": "pixels", + "doc": "Size of the additional area added to dimensions determined by `icon-text-fit`, in clockwise order: top, right, bottom, left.", + "requires": [ + "icon-image", + "text-field", + { + "icon-text-fit": [ + "both", + "width", + "height" + ] + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.21.0", + "android": "4.2.0", + "ios": "3.4.0", + "macos": "0.2.1" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-image": { + "type": "resolvedImage", + "doc": "Name of image in sprite to use for drawing an image background.", + "tokens": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.35.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-rotate": { + "type": "number", + "default": 0, + "period": 360, + "units": "degrees", + "doc": "Rotates the icon clockwise.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.21.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-padding": { + "type": "number", + "default": 2, + "minimum": 0, + "units": "pixels", + "doc": "Size of the additional area around the icon bounding box used for detecting symbol collisions.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-keep-upright": { + "type": "boolean", + "default": false, + "doc": "If true, the icon may be flipped to prevent it from being rendered upside-down.", + "requires": [ + "icon-image", + { + "icon-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-offset": { + "type": "array", + "value": "number", + "length": 2, + "default": [ + 0, + 0 + ], + "doc": "Offset distance of icon from its anchor. Positive values indicate right and down, while negative values indicate left and up. Each component is multiplied by the value of `icon-size` to obtain the final offset in pixels. When combined with `icon-rotate` the offset will be as if the rotated direction was up.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-anchor": { + "type": "enum", + "values": { + "center": { + "doc": "The center of the icon is placed closest to the anchor." + }, + "left": { + "doc": "The left side of the icon is placed closest to the anchor." + }, + "right": { + "doc": "The right side of the icon is placed closest to the anchor." + }, + "top": { + "doc": "The top of the icon is placed closest to the anchor." + }, + "bottom": { + "doc": "The bottom of the icon is placed closest to the anchor." + }, + "top-left": { + "doc": "The top left corner of the icon is placed closest to the anchor." + }, + "top-right": { + "doc": "The top right corner of the icon is placed closest to the anchor." + }, + "bottom-left": { + "doc": "The bottom left corner of the icon is placed closest to the anchor." + }, + "bottom-right": { + "doc": "The bottom right corner of the icon is placed closest to the anchor." + } + }, + "default": "center", + "doc": "Part of the icon placed closest to the anchor.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.40.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + }, + "data-driven styling": { + "js": "0.40.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "icon-pitch-alignment": { + "type": "enum", + "values": { + "map": { + "doc": "The icon is aligned to the plane of the map." + }, + "viewport": { + "doc": "The icon is aligned to the plane of the viewport." + }, + "auto": { + "doc": "Automatically matches the value of `icon-rotation-alignment`." + } + }, + "default": "auto", + "doc": "Orientation of icon when map is pitched.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.39.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-pitch-alignment": { + "type": "enum", + "values": { + "map": { + "doc": "The text is aligned to the plane of the map." + }, + "viewport": { + "doc": "The text is aligned to the plane of the viewport." + }, + "auto": { + "doc": "Automatically matches the value of `text-rotation-alignment`." + } + }, + "default": "auto", + "doc": "Orientation of text when map is pitched.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.21.0", + "android": "4.2.0", + "ios": "3.4.0", + "macos": "0.2.1" + }, + "`auto` value": { + "js": "0.25.0", + "android": "4.2.0", + "ios": "3.4.0", + "macos": "0.3.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotation-alignment": { + "type": "enum", + "values": { + "map": { + "doc": "When `symbol-placement` is set to `point`, aligns text east-west. When `symbol-placement` is set to `line` or `line-center`, aligns text x-axes with the line." + }, + "viewport": { + "doc": "Produces glyphs whose x-axes are aligned with the x-axis of the viewport, regardless of the value of `symbol-placement`." + }, + "auto": { + "doc": "When `symbol-placement` is set to `point`, this is equivalent to `viewport`. When `symbol-placement` is set to `line` or `line-center`, this is equivalent to `map`." + } + }, + "default": "auto", + "doc": "In combination with `symbol-placement`, determines the rotation behavior of the individual glyphs forming the text.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "`auto` value": { + "js": "0.25.0", + "android": "4.2.0", + "ios": "3.4.0", + "macos": "0.3.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-field": { + "type": "formatted", + "default": "", + "tokens": true, + "doc": "Value to use for a text label. If a plain `string` is provided, it will be treated as a `formatted` with default/inherited formatting options.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-font": { + "type": "array", + "value": "string", + "default": [ + "Open Sans Regular", + "Arial Unicode MS Regular" + ], + "doc": "Font stack to use for displaying text.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-size": { + "type": "number", + "default": 16, + "minimum": 0, + "units": "pixels", + "doc": "Font size.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.35.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-width": { + "type": "number", + "default": 10, + "minimum": 0, + "units": "ems", + "doc": "The maximum line width for text wrapping.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.40.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-line-height": { + "type": "number", + "default": 1.2, + "units": "ems", + "doc": "Text leading value for multi-line text.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-letter-spacing": { + "type": "number", + "default": 0, + "units": "ems", + "doc": "Text tracking amount.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.40.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-justify": { + "type": "enum", + "values": { + "auto": { + "doc": "The text is aligned towards the anchor position." + }, + "left": { + "doc": "The text is aligned to the left." + }, + "center": { + "doc": "The text is centered." + }, + "right": { + "doc": "The text is aligned to the right." + } + }, + "default": "center", + "doc": "Text justification options.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.39.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + }, + "auto": { + "js": "0.54.0", + "android": "7.4.0", + "ios": "4.10.0", + "macos": "0.14.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-radial-offset": { + "type": "number", + "units": "ems", + "default": 0, + "doc": "Radial offset of text, in the direction of the symbol's anchor. Useful in combination with `text-variable-anchor`, which defaults to using the two-dimensional `text-offset` if present.", + "sdk-support": { + "basic functionality": { + "js": "0.54.0", + "android": "7.4.0", + "ios": "4.10.0", + "macos": "0.14.0" + }, + "data-driven styling": { + "js": "0.54.0", + "android": "7.4.0", + "ios": "4.10.0", + "macos": "0.14.0" + } + }, + "requires": [ + "text-field" + ], + "property-type": "data-driven", + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + } + }, + "text-variable-anchor": { + "type": "array", + "value": "enum", + "values": { + "center": { + "doc": "The center of the text is placed closest to the anchor." + }, + "left": { + "doc": "The left side of the text is placed closest to the anchor." + }, + "right": { + "doc": "The right side of the text is placed closest to the anchor." + }, + "top": { + "doc": "The top of the text is placed closest to the anchor." + }, + "bottom": { + "doc": "The bottom of the text is placed closest to the anchor." + }, + "top-left": { + "doc": "The top left corner of the text is placed closest to the anchor." + }, + "top-right": { + "doc": "The top right corner of the text is placed closest to the anchor." + }, + "bottom-left": { + "doc": "The bottom left corner of the text is placed closest to the anchor." + }, + "bottom-right": { + "doc": "The bottom right corner of the text is placed closest to the anchor." + } + }, + "requires": [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + "doc": "To increase the chance of placing high-priority labels on the map, you can provide an array of `text-anchor` locations: the renderer will attempt to place the label at each location, in order, before moving onto the next label. Use `text-justify: auto` to choose justification based on anchor position. To apply an offset, use the `text-radial-offset` or the two-dimensional `text-offset`.", + "sdk-support": { + "basic functionality": { + "js": "0.54.0", + "android": "7.4.0", + "ios": "4.10.0", + "macos": "0.14.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-anchor": { + "type": "enum", + "values": { + "center": { + "doc": "The center of the text is placed closest to the anchor." + }, + "left": { + "doc": "The left side of the text is placed closest to the anchor." + }, + "right": { + "doc": "The right side of the text is placed closest to the anchor." + }, + "top": { + "doc": "The top of the text is placed closest to the anchor." + }, + "bottom": { + "doc": "The bottom of the text is placed closest to the anchor." + }, + "top-left": { + "doc": "The top left corner of the text is placed closest to the anchor." + }, + "top-right": { + "doc": "The top right corner of the text is placed closest to the anchor." + }, + "bottom-left": { + "doc": "The bottom left corner of the text is placed closest to the anchor." + }, + "bottom-right": { + "doc": "The bottom right corner of the text is placed closest to the anchor." + } + }, + "default": "center", + "doc": "Part of the text placed closest to the anchor.", + "requires": [ + "text-field", + { + "!": "text-variable-anchor" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.39.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-max-angle": { + "type": "number", + "default": 45, + "units": "degrees", + "doc": "Maximum angle change between adjacent characters.", + "requires": [ + "text-field", + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-writing-mode": { + "type": "array", + "value": "enum", + "values": { + "horizontal": { + "doc": "If a text's language supports horizontal writing mode, symbols with point placement would be laid out horizontally." + }, + "vertical": { + "doc": "If a text's language supports vertical writing mode, symbols with point placement would be laid out vertically." + } + }, + "doc": "The property allows control over a symbol's orientation. Note that the property values act as a hint, so that a symbol whose language doesn’t support the provided orientation will be laid out in its natural orientation. Example: English point symbol will be rendered horizontally even if array value contains single 'vertical' enum value. The order of elements in an array define priority order for the placement of an orientation variant.", + "requires": [ + "text-field", + { + "symbol-placement": [ + "point" + ] + } + ], + "sdk-support": { + "basic functionality": { + "js": "1.3.0", + "android": "8.3.0", + "ios": "5.3.0", + "macos": "0.15.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-rotate": { + "type": "number", + "default": 0, + "period": 360, + "units": "degrees", + "doc": "Rotates the text clockwise.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.35.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-padding": { + "type": "number", + "default": 2, + "minimum": 0, + "units": "pixels", + "doc": "Size of the additional area around the text bounding box used for detecting symbol collisions.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-keep-upright": { + "type": "boolean", + "default": true, + "doc": "If true, the text may be flipped vertically to prevent it from being rendered upside-down.", + "requires": [ + "text-field", + { + "text-rotation-alignment": "map" + }, + { + "symbol-placement": [ + "line", + "line-center" + ] + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-transform": { + "type": "enum", + "values": { + "none": { + "doc": "The text is not altered." + }, + "uppercase": { + "doc": "Forces all letters to be displayed in uppercase." + }, + "lowercase": { + "doc": "Forces all letters to be displayed in lowercase." + } + }, + "default": "none", + "doc": "Specifies how to capitalize text, similar to the CSS `text-transform` property.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-offset": { + "type": "array", + "doc": "Offset distance of text from its anchor. Positive values indicate right and down, while negative values indicate left and up. If used with text-variable-anchor, input values will be taken as absolute values. Offsets along the x- and y-axis will be applied automatically based on the anchor position.", + "value": "number", + "units": "ems", + "length": 2, + "default": [ + 0, + 0 + ], + "requires": [ + "text-field", + { + "!": "text-radial-offset" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.35.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "data-driven" + }, + "text-allow-overlap": { + "type": "boolean", + "default": false, + "doc": "If true, the text will be visible even if it collides with other previously drawn symbols.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-ignore-placement": { + "type": "boolean", + "default": false, + "doc": "If true, other symbols can be visible even if they collide with the text.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-optional": { + "type": "boolean", + "default": false, + "doc": "If true, icons will display without their corresponding text when the text collides with other symbols and the icon does not.", + "requires": [ + "text-field", + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "property-type": "constant" + } + }, + "layout_raster": { + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "property-type": "constant" + } + }, + "layout_hillshade": { + "visibility": { + "type": "enum", + "values": { + "visible": { + "doc": "The layer is shown." + }, + "none": { + "doc": "The layer is not shown." + } + }, + "default": "visible", + "doc": "Whether this layer is displayed.", + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "property-type": "constant" + } + }, + "filter": { + "type": "array", + "value": "*", + "doc": "A filter selects specific features from a layer." + }, + "filter_operator": { + "type": "enum", + "values": { + "==": { + "doc": "`[\"==\", key, value]` equality: `feature[key] = value`" + }, + "!=": { + "doc": "`[\"!=\", key, value]` inequality: `feature[key] ≠ value`" + }, + ">": { + "doc": "`[\">\", key, value]` greater than: `feature[key] > value`" + }, + ">=": { + "doc": "`[\">=\", key, value]` greater than or equal: `feature[key] ≥ value`" + }, + "<": { + "doc": "`[\"<\", key, value]` less than: `feature[key] < value`" + }, + "<=": { + "doc": "`[\"<=\", key, value]` less than or equal: `feature[key] ≤ value`" + }, + "in": { + "doc": "`[\"in\", key, v0, ..., vn]` set inclusion: `feature[key] ∈ {v0, ..., vn}`" + }, + "!in": { + "doc": "`[\"!in\", key, v0, ..., vn]` set exclusion: `feature[key] ∉ {v0, ..., vn}`" + }, + "all": { + "doc": "`[\"all\", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`" + }, + "any": { + "doc": "`[\"any\", f0, ..., fn]` logical `OR`: `f0 ∨ ... ∨ fn`" + }, + "none": { + "doc": "`[\"none\", f0, ..., fn]` logical `NOR`: `¬f0 ∧ ... ∧ ¬fn`" + }, + "has": { + "doc": "`[\"has\", key]` `feature[key]` exists" + }, + "!has": { + "doc": "`[\"!has\", key]` `feature[key]` does not exist" + }, + "within": { + "doc": "`[\"within\", object]` feature geometry is within object geometry" + } + }, + "doc": "The filter operator." + }, + "geometry_type": { + "type": "enum", + "values": { + "Point": { + "doc": "Filter to point geometries." + }, + "LineString": { + "doc": "Filter to line geometries." + }, + "Polygon": { + "doc": "Filter to polygon geometries." + } + }, + "doc": "The geometry type for the filter to select." + }, + "function": { + "expression": { + "type": "expression", + "doc": "An expression." + }, + "stops": { + "type": "array", + "doc": "An array of stops.", + "value": "function_stop" + }, + "base": { + "type": "number", + "default": 1, + "minimum": 0, + "doc": "The exponential base of the interpolation curve. It controls the rate at which the result increases. Higher values make the result increase more towards the high end of the range. With `1` the stops are interpolated linearly." + }, + "property": { + "type": "string", + "doc": "The name of a feature property to use as the function input.", + "default": "$zoom" + }, + "type": { + "type": "enum", + "values": { + "identity": { + "doc": "Return the input value as the output value." + }, + "exponential": { + "doc": "Generate an output by interpolating between stops just less than and just greater than the function input." + }, + "interval": { + "doc": "Return the output value of the stop just less than the function input." + }, + "categorical": { + "doc": "Return the output value of the stop equal to the function input." + } + }, + "doc": "The interpolation strategy to use in function evaluation.", + "default": "exponential" + }, + "colorSpace": { + "type": "enum", + "values": { + "rgb": { + "doc": "Use the RGB color space to interpolate color values" + }, + "lab": { + "doc": "Use the LAB color space to interpolate color values." + }, + "hcl": { + "doc": "Use the HCL color space to interpolate color values, interpolating the Hue, Chroma, and Luminance channels individually." + } + }, + "doc": "The color space in which colors interpolated. Interpolating colors in perceptual color spaces like LAB and HCL tend to produce color ramps that look more consistent and produce colors that can be differentiated more easily than those interpolated in RGB space.", + "default": "rgb" + }, + "default": { + "type": "*", + "required": false, + "doc": "A value to serve as a fallback function result when a value isn't otherwise available. It is used in the following circumstances:\n* In categorical functions, when the feature value does not match any of the stop domain values.\n* In property and zoom-and-property functions, when a feature does not contain a value for the specified property.\n* In identity functions, when the feature value is not valid for the style property (for example, if the function is being used for a `circle-color` property but the feature property value is not a string or not a valid color).\n* In interval or exponential property and zoom-and-property functions, when the feature value is not numeric.\nIf no default is provided, the style property's default is used in these circumstances." + } + }, + "function_stop": { + "type": "array", + "minimum": 0, + "maximum": 24, + "value": [ + "number", + "color" + ], + "length": 2, + "doc": "Zoom level and value pair." + }, + "expression": { + "type": "array", + "value": "*", + "minimum": 1, + "doc": "An expression defines a function that can be used for data-driven style properties or feature filters." + }, + "expression_name": { + "doc": "", + "type": "enum", + "values": { + "let": { + "doc": "Binds expressions to named variables, which can then be referenced in the result expression using [\"var\", \"variable_name\"].", + "group": "Variable binding", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "var": { + "doc": "References variable bound using \"let\".", + "group": "Variable binding", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "literal": { + "doc": "Provides a literal array or object value.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "array": { + "doc": "Asserts that the input is an array (optionally with a specific item type and length). If, when the input expression is evaluated, it is not of the asserted type, then this assertion will cause the whole expression to be aborted.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "at": { + "doc": "Retrieves an item from an array.", + "group": "Lookup", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "in": { + "doc": "Determines whether an item exists in an array or a substring exists in a string.", + "group": "Lookup", + "sdk-support": { + "basic functionality": { + "js": "1.6.0", + "android": "9.1.0", + "ios": "5.8.0", + "macos": "0.15.0" + } + } + }, + "index-of": { + "doc": "Returns the first position at which an item can be found in an array or a substring can be found in a string, or `-1` if the input cannot be found. Accepts an optional index from where to begin the search.", + "group": "Lookup", + "sdk-support": { + "basic functionality": { + "js": "1.10.0" + } + } + }, + "slice": { + "doc": "Returns an item from an array or a substring from a string from a specified start index, or between a start index and an end index if set. The return value is inclusive of the start index but not of the end index.", + "group": "Lookup", + "sdk-support": { + "basic functionality": { + "js": "1.10.0" + } + } + }, + "case": { + "doc": "Selects the first output whose corresponding test condition evaluates to true, or the fallback value otherwise.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "match": { + "doc": "Selects the output whose label value matches the input value, or the fallback value if no match is found. The input can be any expression (e.g. `[\"get\", \"building_type\"]`). Each label must be either:\n - a single literal value; or\n - an array of literal values, whose values must be all strings or all numbers (e.g. `[100, 101]` or `[\"c\", \"b\"]`). The input matches if any of the values in the array matches, similar to the `\"in\"` operator.\nEach label must be unique. If the input type does not match the type of the labels, the result will be the fallback value.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "coalesce": { + "doc": "Evaluates each expression in turn until the first non-null value is obtained, and returns that value.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "step": { + "doc": "Produces discrete, stepped results by evaluating a piecewise-constant function defined by pairs of input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). Stop inputs must be numeric literals in strictly ascending order. Returns the output value of the stop just less than the input, or the first output if the input is less than the first stop.", + "group": "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + "js": "0.42.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "interpolate": { + "doc": "Produces continuous, smooth results by interpolating between pairs of input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). Stop inputs must be numeric literals in strictly ascending order. The output type must be `number`, `array`, or `color`.\n\nInterpolation types:\n- `[\"linear\"]`: Interpolates linearly between the pair of stops just less than and just greater than the input.\n- `[\"exponential\", base]`: Interpolates exponentially between the stops just less than and just greater than the input. `base` controls the rate at which the output increases: higher values make the output increase more towards the high end of the range. With values close to 1 the output increases linearly.\n- `[\"cubic-bezier\", x1, y1, x2, y2]`: Interpolates using the cubic bezier curve defined by the given control points.", + "group": "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + "js": "0.42.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "interpolate-hcl": { + "doc": "Produces continuous, smooth results by interpolating between pairs of input and output values (\"stops\"). Works like `interpolate`, but the output type must be `color`, and the interpolation is performed in the Hue-Chroma-Luminance color space.", + "group": "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + "js": "0.49.0" + } + } + }, + "interpolate-lab": { + "doc": "Produces continuous, smooth results by interpolating between pairs of input and output values (\"stops\"). Works like `interpolate`, but the output type must be `color`, and the interpolation is performed in the CIELAB color space.", + "group": "Ramps, scales, curves", + "sdk-support": { + "basic functionality": { + "js": "0.49.0" + } + } + }, + "ln2": { + "doc": "Returns mathematical constant ln(2).", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "pi": { + "doc": "Returns the mathematical constant pi.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "e": { + "doc": "Returns the mathematical constant e.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "typeof": { + "doc": "Returns a string describing the type of the given value.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "string": { + "doc": "Asserts that the input value is a string. If multiple values are provided, each one is evaluated in order until a string is obtained. If none of the inputs are strings, the expression is an error.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "number": { + "doc": "Asserts that the input value is a number. If multiple values are provided, each one is evaluated in order until a number is obtained. If none of the inputs are numbers, the expression is an error.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "boolean": { + "doc": "Asserts that the input value is a boolean. If multiple values are provided, each one is evaluated in order until a boolean is obtained. If none of the inputs are booleans, the expression is an error.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "object": { + "doc": "Asserts that the input value is an object. If multiple values are provided, each one is evaluated in order until an object is obtained. If none of the inputs are objects, the expression is an error.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "collator": { + "doc": "Returns a `collator` for use in locale-dependent comparison operations. The `case-sensitive` and `diacritic-sensitive` options default to `false`. The `locale` argument specifies the IETF language tag of the locale to use. If none is provided, the default locale is used. If the requested locale is not available, the `collator` will use a system-defined fallback locale. Use `resolved-locale` to test the results of locale fallback behavior.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + }, + "format": { + "doc": "Returns a `formatted` string for displaying mixed-format text in the `text-field` property. The input may contain a string literal or expression, including an [`'image'`](#types-image) expression. Strings may be followed by a style override object that supports the following properties:\n- `\"text-font\"`: Overrides the font stack specified by the root layout property.\n- `\"text-color\"`: Overrides the color specified by the root paint property.\n- `\"font-scale\"`: Applies a scaling factor on `text-size` as specified by the root layout property.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.48.0", + "android": "6.7.0", + "ios": "4.6.0", + "macos": "0.12.0" + }, + "text-font": { + "js": "0.48.0", + "android": "6.7.0", + "ios": "4.6.0", + "macos": "0.12.0" + }, + "font-scale": { + "js": "0.48.0", + "android": "6.7.0", + "ios": "4.6.0", + "macos": "0.12.0" + }, + "text-color": { + "js": "1.3.0", + "android": "7.3.0", + "ios": "4.10.0", + "macos": "0.14.0" + }, + "image": { + "js": "1.6.0", + "android": "8.6.0", + "ios": "5.7.0", + "macos": "0.15.0" + } + } + }, + "image": { + "doc": "Returns an `image` type for use in `icon-image`, `*-pattern` entries and as a section in the `format` expression. If set, the `image` argument will check that the requested image exists in the style and will return either the resolved image name or `null`, depending on whether or not the image is currently in the style. This validation process is synchronous and requires the image to have been added to the style before requesting it in the `image` argument.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "1.4.0", + "android": "8.6.0", + "ios": "5.7.0", + "macos": "0.15.0" + } + } + }, + "number-format": { + "doc": "Converts the input number into a string representation using the providing formatting rules. If set, the `locale` argument specifies the locale to use, as a BCP 47 language tag. If set, the `currency` argument specifies an ISO 4217 code to use for currency-style formatting. If set, the `min-fraction-digits` and `max-fraction-digits` arguments specify the minimum and maximum number of fractional digits to include.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.54.0" + } + } + }, + "to-string": { + "doc": "Converts the input value to a string. If the input is `null`, the result is `\"\"`. If the input is a boolean, the result is `\"true\"` or `\"false\"`. If the input is a number, it is converted to a string as specified by the [\"NumberToString\" algorithm](https://tc39.github.io/ecma262/#sec-tostring-applied-to-the-number-type) of the ECMAScript Language Specification. If the input is a color, it is converted to a string of the form `\"rgba(r,g,b,a)\"`, where `r`, `g`, and `b` are numerals ranging from 0 to 255, and `a` ranges from 0 to 1. Otherwise, the input is converted to a string in the format specified by the [`JSON.stringify`](https://tc39.github.io/ecma262/#sec-json.stringify) function of the ECMAScript Language Specification.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "to-number": { + "doc": "Converts the input value to a number, if possible. If the input is `null` or `false`, the result is 0. If the input is `true`, the result is 1. If the input is a string, it is converted to a number as specified by the [\"ToNumber Applied to the String Type\" algorithm](https://tc39.github.io/ecma262/#sec-tonumber-applied-to-the-string-type) of the ECMAScript Language Specification. If multiple values are provided, each one is evaluated in order until the first successful conversion is obtained. If none of the inputs can be converted, the expression is an error.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "to-boolean": { + "doc": "Converts the input value to a boolean. The result is `false` when then input is an empty string, 0, `false`, `null`, or `NaN`; otherwise it is `true`.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "to-rgba": { + "doc": "Returns a four-element array containing the input color's red, green, blue, and alpha components, in that order.", + "group": "Color", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "to-color": { + "doc": "Converts the input value to a color. If multiple values are provided, each one is evaluated in order until the first successful conversion is obtained. If none of the inputs can be converted, the expression is an error.", + "group": "Types", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "rgb": { + "doc": "Creates a color value from red, green, and blue components, which must range between 0 and 255, and an alpha component of 1. If any component is out of range, the expression is an error.", + "group": "Color", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "rgba": { + "doc": "Creates a color value from red, green, blue components, which must range between 0 and 255, and an alpha component which must range between 0 and 1. If any component is out of range, the expression is an error.", + "group": "Color", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "get": { + "doc": "Retrieves a property value from the current feature's properties, or from another object if a second argument is provided. Returns null if the requested property is missing.", + "group": "Lookup", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "has": { + "doc": "Tests for the presence of an property value in the current feature's properties, or from another object if a second argument is provided.", + "group": "Lookup", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "length": { + "doc": "Gets the length of an array or string.", + "group": "Lookup", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "properties": { + "doc": "Gets the feature properties object. Note that in some cases, it may be more efficient to use [\"get\", \"property_name\"] directly.", + "group": "Feature data", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "feature-state": { + "doc": "Retrieves a property value from the current feature's state. Returns null if the requested property is not present on the feature's state. A feature's state is not part of the GeoJSON or vector tile data, and must be set programmatically on each feature. Features are identified by their `id` attribute, which must be an integer or a string that can be cast to an integer. Note that [\"feature-state\"] can only be used with paint properties that support data-driven styling.", + "group": "Feature data", + "sdk-support": { + "basic functionality": { + "js": "0.46.0" + } + } + }, + "geometry-type": { + "doc": "Gets the feature's geometry type: `Point`, `MultiPoint`, `LineString`, `MultiLineString`, `Polygon`, `MultiPolygon`.", + "group": "Feature data", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "id": { + "doc": "Gets the feature's id, if it has one.", + "group": "Feature data", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "zoom": { + "doc": "Gets the current zoom level. Note that in style layout and paint properties, [\"zoom\"] may only appear as the input to a top-level \"step\" or \"interpolate\" expression.", + "group": "Zoom", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "heatmap-density": { + "doc": "Gets the kernel density estimation of a pixel in a heatmap layer, which is a relative measure of how many data points are crowded around a particular pixel. Can only be used in the `heatmap-color` property.", + "group": "Heatmap", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "line-progress": { + "doc": "Gets the progress along a gradient line. Can only be used in the `line-gradient` property.", + "group": "Feature data", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.6.0", + "macos": "0.12.0" + } + } + }, + "accumulated": { + "doc": "Gets the value of a cluster property accumulated so far. Can only be used in the `clusterProperties` option of a clustered GeoJSON source.", + "group": "Feature data", + "sdk-support": { + "basic functionality": { + "js": "0.53.0" + } + } + }, + "+": { + "doc": "Returns the sum of the inputs.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "*": { + "doc": "Returns the product of the inputs.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "-": { + "doc": "For two inputs, returns the result of subtracting the second input from the first. For a single input, returns the result of subtracting it from 0.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "/": { + "doc": "Returns the result of floating point division of the first input by the second.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "%": { + "doc": "Returns the remainder after integer division of the first input by the second.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "^": { + "doc": "Returns the result of raising the first input to the power specified by the second.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "sqrt": { + "doc": "Returns the square root of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.42.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "log10": { + "doc": "Returns the base-ten logarithm of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "ln": { + "doc": "Returns the natural logarithm of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "log2": { + "doc": "Returns the base-two logarithm of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "sin": { + "doc": "Returns the sine of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "cos": { + "doc": "Returns the cosine of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "tan": { + "doc": "Returns the tangent of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "asin": { + "doc": "Returns the arcsine of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "acos": { + "doc": "Returns the arccosine of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "atan": { + "doc": "Returns the arctangent of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "min": { + "doc": "Returns the minimum value of the inputs.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "max": { + "doc": "Returns the maximum value of the inputs.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "round": { + "doc": "Rounds the input to the nearest integer. Halfway values are rounded away from zero. For example, `[\"round\", -1.5]` evaluates to -2.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "abs": { + "doc": "Returns the absolute value of the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "ceil": { + "doc": "Returns the smallest integer that is greater than or equal to the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "floor": { + "doc": "Returns the largest integer that is less than or equal to the input.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "distance": { + "doc": "Returns the shortest distance in meters between the evaluated feature and the input geometry. The input value can be a valid GeoJSON of type `Point`, `MultiPoint`, `LineString`, `MultiLineString`, `Polygon`, `MultiPolygon`, `Feature`, or `FeatureCollection`. Distance values returned may vary in precision due to loss in precision from encoding geometries, particularly below zoom level 13.", + "group": "Math", + "sdk-support": { + "basic functionality": { + "android": "9.2.0", + "ios": "5.9.0", + "macos": "0.16.0" + } + } + }, + "==": { + "doc": "Returns `true` if the input values are equal, `false` otherwise. The comparison is strictly typed: values of different runtime types are always considered unequal. Cases where the types are known to be different at parse time are considered invalid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "collator": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + }, + "!=": { + "doc": "Returns `true` if the input values are not equal, `false` otherwise. The comparison is strictly typed: values of different runtime types are always considered unequal. Cases where the types are known to be different at parse time are considered invalid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "collator": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + }, + ">": { + "doc": "Returns `true` if the first input is strictly greater than the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "collator": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + }, + "<": { + "doc": "Returns `true` if the first input is strictly less than the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "collator": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + }, + ">=": { + "doc": "Returns `true` if the first input is greater than or equal to the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "collator": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + }, + "<=": { + "doc": "Returns `true` if the first input is less than or equal to the second, `false` otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional `collator` argument to control locale-dependent string comparisons.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "collator": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + }, + "all": { + "doc": "Returns `true` if all the inputs are `true`, `false` otherwise. The inputs are evaluated in order, and evaluation is short-circuiting: once an input expression evaluates to `false`, the result is `false` and no further input expressions are evaluated.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "any": { + "doc": "Returns `true` if any of the inputs are `true`, `false` otherwise. The inputs are evaluated in order, and evaluation is short-circuiting: once an input expression evaluates to `true`, the result is `true` and no further input expressions are evaluated.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "!": { + "doc": "Logical negation. Returns `true` if the input is `false`, and `false` if the input is `true`.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "within": { + "doc": "Returns `true` if the evaluated feature is fully contained inside a boundary of the input geometry, `false` otherwise. The input value can be a valid GeoJSON of type `Polygon`, `MultiPolygon`, `Feature`, or `FeatureCollection`. Supported features for evaluation:\n- `Point`: Returns `false` if a point is on the boundary or falls outside the boundary.\n- `LineString`: Returns `false` if any part of a line falls outside the boundary, the line intersects the boundary, or a line's endpoint is on the boundary.", + "group": "Decision", + "sdk-support": { + "basic functionality": { + "js": "1.9.0", + "android": "9.1.0", + "ios": "5.8.0", + "macos": "0.15.0" + } + } + }, + "is-supported-script": { + "doc": "Returns `true` if the input string is expected to render legibly. Returns `false` if the input string contains sections that cannot be rendered without potential loss of meaning (e.g. Indic scripts that require complex text shaping, or right-to-left scripts if the the `mapbox-gl-rtl-text` plugin is not in use in Mapbox GL JS).", + "group": "String", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.6.0" + } + } + }, + "upcase": { + "doc": "Returns the input string converted to uppercase. Follows the Unicode Default Case Conversion algorithm and the locale-insensitive case mappings in the Unicode Character Database.", + "group": "String", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "downcase": { + "doc": "Returns the input string converted to lowercase. Follows the Unicode Default Case Conversion algorithm and the locale-insensitive case mappings in the Unicode Character Database.", + "group": "String", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "concat": { + "doc": "Returns a `string` consisting of the concatenation of the inputs. Each input is converted to a string as if by `to-string`.", + "group": "String", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + } + }, + "resolved-locale": { + "doc": "Returns the IETF language tag of the locale being used by the provided `collator`. This can be used to determine the default system locale, or to determine if a requested locale was successfully loaded.", + "group": "String", + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + } + } + } + }, + "light": { + "anchor": { + "type": "enum", + "default": "viewport", + "values": { + "map": { + "doc": "The position of the light source is aligned to the rotation of the map." + }, + "viewport": { + "doc": "The position of the light source is aligned to the rotation of the viewport." + } + }, + "property-type": "data-constant", + "transition": false, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "doc": "Whether extruded geometries are lit relative to the map or viewport.", + "example": "map", + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + } + }, + "position": { + "type": "array", + "default": [ + 1.15, + 210, + 30 + ], + "length": 3, + "value": "number", + "property-type": "data-constant", + "transition": true, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "doc": "Position of the light source relative to lit (extruded) geometries, in [r radial coordinate, a azimuthal angle, p polar angle] where r indicates the distance from the center of the base of an object to its light, a indicates the position of the light relative to 0° (0° when `light.anchor` is set to `viewport` corresponds to the top of the viewport, or 0° when `light.anchor` is set to `map` corresponds to due north, and degrees proceed clockwise), and p indicates the height of the light (from 0°, directly above, to 180°, directly below).", + "example": [ + 1.5, + 90, + 80 + ], + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + } + }, + "color": { + "type": "color", + "property-type": "data-constant", + "default": "#ffffff", + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "transition": true, + "doc": "Color tint for lighting extruded geometries.", + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + } + }, + "intensity": { + "type": "number", + "property-type": "data-constant", + "default": 0.5, + "minimum": 0, + "maximum": 1, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "transition": true, + "doc": "Intensity of lighting (on a scale from 0 to 1). Higher numbers will present as more extreme contrast.", + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + } + } + }, + "paint": [ + "paint_fill", + "paint_line", + "paint_circle", + "paint_heatmap", + "paint_fill-extrusion", + "paint_symbol", + "paint_raster", + "paint_hillshade", + "paint_background" + ], + "paint_fill": { + "fill-antialias": { + "type": "boolean", + "default": true, + "doc": "Whether or not the fill should be antialiased.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-opacity": { + "type": "number", + "default": 1, + "minimum": 0, + "maximum": 1, + "doc": "The opacity of the entire fill layer. In contrast to the `fill-color`, this value will also affect the 1px stroke around the fill, if the stroke is used.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.21.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-color": { + "type": "color", + "default": "#000000", + "doc": "The color of the filled part of this layer. This color can be specified as `rgba` with an alpha component and the color's opacity will not affect the opacity of the 1px stroke, if it is used.", + "transition": true, + "requires": [ + { + "!": "fill-pattern" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.19.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-outline-color": { + "type": "color", + "doc": "The outline color of the fill. Matches the value of `fill-color` if unspecified.", + "transition": true, + "requires": [ + { + "!": "fill-pattern" + }, + { + "fill-antialias": true + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.19.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-translate": { + "type": "array", + "value": "number", + "length": 2, + "default": [ + 0, + 0 + ], + "transition": true, + "units": "pixels", + "doc": "The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-translate-anchor": { + "type": "enum", + "values": { + "map": { + "doc": "The fill is translated relative to the map." + }, + "viewport": { + "doc": "The fill is translated relative to the viewport." + } + }, + "doc": "Controls the frame of reference for `fill-translate`.", + "default": "map", + "requires": [ + "fill-translate" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-pattern": { + "type": "resolvedImage", + "transition": true, + "doc": "Name of image in sprite to use for drawing image fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.49.0", + "android": "6.5.0", + "macos": "0.11.0", + "ios": "4.4.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + } + }, + "paint_fill-extrusion": { + "fill-extrusion-opacity": { + "type": "number", + "default": 1, + "minimum": 0, + "maximum": 1, + "doc": "The opacity of the entire fill extrusion layer. This is rendered on a per-layer, not per-feature, basis, and data-driven styling is not available.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-color": { + "type": "color", + "default": "#000000", + "doc": "The base color of the extruded fill. The extrusion's surfaces will be shaded differently based on this color in combination with the root `light` settings. If this color is specified as `rgba` with an alpha component, the alpha component will be ignored; use `fill-extrusion-opacity` to set layer opacity.", + "transition": true, + "requires": [ + { + "!": "fill-extrusion-pattern" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + }, + "data-driven styling": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-translate": { + "type": "array", + "value": "number", + "length": 2, + "default": [ + 0, + 0 + ], + "transition": true, + "units": "pixels", + "doc": "The geometry's offset. Values are [x, y] where negatives indicate left and up (on the flat plane), respectively.", + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-translate-anchor": { + "type": "enum", + "values": { + "map": { + "doc": "The fill extrusion is translated relative to the map." + }, + "viewport": { + "doc": "The fill extrusion is translated relative to the viewport." + } + }, + "doc": "Controls the frame of reference for `fill-extrusion-translate`.", + "default": "map", + "requires": [ + "fill-extrusion-translate" + ], + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "fill-extrusion-pattern": { + "type": "resolvedImage", + "transition": true, + "doc": "Name of image in sprite to use for drawing images on extruded fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + }, + "data-driven styling": { + "js": "0.49.0", + "android": "6.5.0", + "macos": "0.11.0", + "ios": "4.4.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "fill-extrusion-height": { + "type": "number", + "default": 0, + "minimum": 0, + "units": "meters", + "doc": "The height with which to extrude this layer.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + }, + "data-driven styling": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-base": { + "type": "number", + "default": 0, + "minimum": 0, + "units": "meters", + "doc": "The height with which to extrude the base of this layer. Must be less than or equal to `fill-extrusion-height`.", + "transition": true, + "requires": [ + "fill-extrusion-height" + ], + "sdk-support": { + "basic functionality": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + }, + "data-driven styling": { + "js": "0.27.0", + "android": "5.1.0", + "ios": "3.6.0", + "macos": "0.5.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "fill-extrusion-vertical-gradient": { + "type": "boolean", + "default": true, + "doc": "Whether to apply a vertical gradient to the sides of a fill-extrusion layer. If true, sides will be shaded slightly darker farther down.", + "transition": false, + "sdk-support": { + "basic functionality": { + "js": "0.50.0", + "ios": "4.7.0", + "macos": "0.13.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }, + "paint_line": { + "line-opacity": { + "type": "number", + "doc": "The opacity at which the line will be drawn.", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-color": { + "type": "color", + "doc": "The color with which the line will be drawn.", + "default": "#000000", + "transition": true, + "requires": [ + { + "!": "line-pattern" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.23.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-translate": { + "type": "array", + "value": "number", + "length": 2, + "default": [ + 0, + 0 + ], + "transition": true, + "units": "pixels", + "doc": "The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-translate-anchor": { + "type": "enum", + "values": { + "map": { + "doc": "The line is translated relative to the map." + }, + "viewport": { + "doc": "The line is translated relative to the viewport." + } + }, + "doc": "Controls the frame of reference for `line-translate`.", + "default": "map", + "requires": [ + "line-translate" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "line-width": { + "type": "number", + "default": 1, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "Stroke thickness.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.39.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-gap-width": { + "type": "number", + "default": 0, + "minimum": 0, + "doc": "Draws a line casing outside of a line's actual path. Value indicates the width of the inner gap.", + "transition": true, + "units": "pixels", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-offset": { + "type": "number", + "default": 0, + "doc": "The line's offset. For linear features, a positive value offsets the line to the right, relative to the direction of the line, and a negative value to the left. For polygon features, a positive value results in an inset, and a negative value results in an outset.", + "transition": true, + "units": "pixels", + "sdk-support": { + "basic functionality": { + "js": "0.12.1", + "android": "3.0.0", + "ios": "3.1.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-blur": { + "type": "number", + "default": 0, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "Blur applied to the line, in pixels.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "line-dasharray": { + "type": "array", + "value": "number", + "doc": "Specifies the lengths of the alternating dashes and gaps that form the dash pattern. The lengths are later scaled by the line width. To convert a dash length to pixels, multiply the length by the current line width. Note that GeoJSON sources with `lineMetrics: true` specified won't render dashed lines to the expected scale. Also note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "minimum": 0, + "transition": true, + "units": "line widths", + "requires": [ + { + "!": "line-pattern" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": {} + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "line-pattern": { + "type": "resolvedImage", + "transition": true, + "doc": "Name of image in sprite to use for drawing image lines. For seamless patterns, image width must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.49.0", + "android": "6.5.0", + "macos": "0.11.0", + "ios": "4.4.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom", + "feature" + ] + }, + "property-type": "cross-faded-data-driven" + }, + "line-gradient": { + "type": "color", + "doc": "Defines a gradient with which to color a line feature. Can only be used with GeoJSON sources that specify `\"lineMetrics\": true`.", + "transition": false, + "requires": [ + { + "!": "line-dasharray" + }, + { + "!": "line-pattern" + }, + { + "source": "geojson", + "has": { + "lineMetrics": true + } + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.45.0", + "android": "6.5.0", + "ios": "4.4.0", + "macos": "0.11.0" + }, + "data-driven styling": {} + }, + "expression": { + "interpolated": true, + "parameters": [ + "line-progress" + ] + }, + "property-type": "color-ramp" + } + }, + "paint_circle": { + "circle-radius": { + "type": "number", + "default": 5, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "Circle radius.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.18.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-color": { + "type": "color", + "default": "#000000", + "doc": "The fill color of the circle.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.18.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-blur": { + "type": "number", + "default": 0, + "doc": "Amount to blur the circle. 1 blurs the circle such that only the centerpoint is full opacity.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.20.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-opacity": { + "type": "number", + "doc": "The opacity at which the circle will be drawn.", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.20.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-translate": { + "type": "array", + "value": "number", + "length": 2, + "default": [ + 0, + 0 + ], + "transition": true, + "units": "pixels", + "doc": "The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-translate-anchor": { + "type": "enum", + "values": { + "map": { + "doc": "The circle is translated relative to the map." + }, + "viewport": { + "doc": "The circle is translated relative to the viewport." + } + }, + "doc": "Controls the frame of reference for `circle-translate`.", + "default": "map", + "requires": [ + "circle-translate" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-scale": { + "type": "enum", + "values": { + "map": { + "doc": "Circles are scaled according to their apparent distance to the camera." + }, + "viewport": { + "doc": "Circles are not scaled." + } + }, + "default": "map", + "doc": "Controls the scaling behavior of the circle when the map is pitched.", + "sdk-support": { + "basic functionality": { + "js": "0.21.0", + "android": "4.2.0", + "ios": "3.4.0", + "macos": "0.2.1" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-pitch-alignment": { + "type": "enum", + "values": { + "map": { + "doc": "The circle is aligned to the plane of the map." + }, + "viewport": { + "doc": "The circle is aligned to the plane of the viewport." + } + }, + "default": "viewport", + "doc": "Orientation of circle when map is pitched.", + "sdk-support": { + "basic functionality": { + "js": "0.39.0", + "android": "5.2.0", + "ios": "3.7.0", + "macos": "0.6.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "circle-stroke-width": { + "type": "number", + "default": 0, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "The width of the circle's stroke. Strokes are placed outside of the `circle-radius`.", + "sdk-support": { + "basic functionality": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-color": { + "type": "color", + "default": "#000000", + "doc": "The stroke color of the circle.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "circle-stroke-opacity": { + "type": "number", + "doc": "The opacity of the circle's stroke.", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + }, + "data-driven styling": { + "js": "0.29.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + } + }, + "paint_heatmap": { + "heatmap-radius": { + "type": "number", + "default": 30, + "minimum": 1, + "transition": true, + "units": "pixels", + "doc": "Radius of influence of one heatmap point in pixels. Increasing the value makes the heatmap smoother, but less detailed.", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "data-driven styling": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-weight": { + "type": "number", + "default": 1, + "minimum": 0, + "transition": false, + "doc": "A measure of how much an individual point contributes to the heatmap. A value of 10 would be equivalent to having 10 points of weight 1 in the same spot. Especially useful when combined with clustering.", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "data-driven styling": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "heatmap-intensity": { + "type": "number", + "default": 1, + "minimum": 0, + "transition": true, + "doc": "Similar to `heatmap-weight` but controls the intensity of the heatmap globally. Primarily used for adjusting the heatmap based on zoom level.", + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "heatmap-color": { + "type": "color", + "default": [ + "interpolate", + [ + "linear" + ], + [ + "heatmap-density" + ], + 0, + "rgba(0, 0, 255, 0)", + 0.1, + "royalblue", + 0.3, + "cyan", + 0.5, + "lime", + 0.7, + "yellow", + 1, + "red" + ], + "doc": "Defines the color of each pixel based on its density value in a heatmap. Should be an expression that uses `[\"heatmap-density\"]` as input.", + "transition": false, + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + }, + "data-driven styling": {} + }, + "expression": { + "interpolated": true, + "parameters": [ + "heatmap-density" + ] + }, + "property-type": "color-ramp" + }, + "heatmap-opacity": { + "type": "number", + "doc": "The global opacity at which the heatmap layer will be drawn.", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.41.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }, + "paint_symbol": { + "icon-opacity": { + "doc": "The opacity at which the icon will be drawn.", + "type": "number", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-color": { + "type": "color", + "default": "#000000", + "transition": true, + "doc": "The color of the icon. This can only be used with sdf icons.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-color": { + "type": "color", + "default": "rgba(0, 0, 0, 0)", + "transition": true, + "doc": "The color of the icon's halo. Icon halos can only be used with SDF icons.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-width": { + "type": "number", + "default": 0, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "Distance of halo to the icon outline.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-halo-blur": { + "type": "number", + "default": 0, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "Fade out the halo towards the outside.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "icon-translate": { + "type": "array", + "value": "number", + "length": 2, + "default": [ + 0, + 0 + ], + "transition": true, + "units": "pixels", + "doc": "Distance that the icon's anchor is moved from its original placement. Positive values indicate right and down, while negative values indicate left and up.", + "requires": [ + "icon-image" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "icon-translate-anchor": { + "type": "enum", + "values": { + "map": { + "doc": "Icons are translated relative to the map." + }, + "viewport": { + "doc": "Icons are translated relative to the viewport." + } + }, + "doc": "Controls the frame of reference for `icon-translate`.", + "default": "map", + "requires": [ + "icon-image", + "icon-translate" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-opacity": { + "type": "number", + "doc": "The opacity at which the text will be drawn.", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-color": { + "type": "color", + "doc": "The color with which the text will be drawn.", + "default": "#000000", + "transition": true, + "overridable": true, + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-color": { + "type": "color", + "default": "rgba(0, 0, 0, 0)", + "transition": true, + "doc": "The color of the text's halo, which helps it stand out from backgrounds.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-width": { + "type": "number", + "default": 0, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "Distance of halo to the font outline. Max text halo width is 1/4 of the font-size.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-halo-blur": { + "type": "number", + "default": 0, + "minimum": 0, + "transition": true, + "units": "pixels", + "doc": "The halo's fadeout distance towards the outside.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": { + "js": "0.33.0", + "android": "5.0.0", + "ios": "3.5.0", + "macos": "0.4.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom", + "feature", + "feature-state" + ] + }, + "property-type": "data-driven" + }, + "text-translate": { + "type": "array", + "value": "number", + "length": 2, + "default": [ + 0, + 0 + ], + "transition": true, + "units": "pixels", + "doc": "Distance that the text's anchor is moved from its original placement. Positive values indicate right and down, while negative values indicate left and up.", + "requires": [ + "text-field" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "text-translate-anchor": { + "type": "enum", + "values": { + "map": { + "doc": "The text is translated relative to the map." + }, + "viewport": { + "doc": "The text is translated relative to the viewport." + } + }, + "doc": "Controls the frame of reference for `text-translate`.", + "default": "map", + "requires": [ + "text-field", + "text-translate" + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }, + "paint_raster": { + "raster-opacity": { + "type": "number", + "doc": "The opacity at which the image will be drawn.", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-hue-rotate": { + "type": "number", + "default": 0, + "period": 360, + "transition": true, + "units": "degrees", + "doc": "Rotates hues around the color wheel.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-min": { + "type": "number", + "doc": "Increase or reduce the brightness of the image. The value is the minimum brightness.", + "default": 0, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-brightness-max": { + "type": "number", + "doc": "Increase or reduce the brightness of the image. The value is the maximum brightness.", + "default": 1, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-saturation": { + "type": "number", + "doc": "Increase or reduce the saturation of the image.", + "default": 0, + "minimum": -1, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-contrast": { + "type": "number", + "doc": "Increase or reduce the contrast of the image.", + "default": 0, + "minimum": -1, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-resampling": { + "type": "enum", + "doc": "The resampling/interpolation method to use for overscaling, also known as texture magnification filter", + "values": { + "linear": { + "doc": "(Bi)linear filtering interpolates pixel values using the weighted average of the four closest original source pixels creating a smooth but blurry look when overscaled" + }, + "nearest": { + "doc": "Nearest neighbor filtering interpolates pixel values using the nearest original source pixel creating a sharp but pixelated look when overscaled" + } + }, + "default": "linear", + "sdk-support": { + "basic functionality": { + "js": "0.47.0", + "android": "6.3.0", + "ios": "4.2.0", + "macos": "0.9.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "raster-fade-duration": { + "type": "number", + "default": 300, + "minimum": 0, + "transition": false, + "units": "milliseconds", + "doc": "Fade duration when a new tile is added.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }, + "paint_hillshade": { + "hillshade-illumination-direction": { + "type": "number", + "default": 335, + "minimum": 0, + "maximum": 359, + "doc": "The direction of the light source used to generate the hillshading with 0 as the top of the viewport if `hillshade-illumination-anchor` is set to `viewport` and due north if `hillshade-illumination-anchor` is set to `map`.", + "transition": false, + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-illumination-anchor": { + "type": "enum", + "values": { + "map": { + "doc": "The hillshade illumination is relative to the north direction." + }, + "viewport": { + "doc": "The hillshade illumination is relative to the top of the viewport." + } + }, + "default": "viewport", + "doc": "Direction of light source when map is rotated.", + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-exaggeration": { + "type": "number", + "doc": "Intensity of the hillshade", + "default": 0.5, + "minimum": 0, + "maximum": 1, + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-shadow-color": { + "type": "color", + "default": "#000000", + "doc": "The shading color of areas that face away from the light source.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-highlight-color": { + "type": "color", + "default": "#FFFFFF", + "doc": "The shading color of areas that faces towards the light source.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "hillshade-accent-color": { + "type": "color", + "default": "#000000", + "doc": "The shading color used to accentuate rugged terrain like sharp cliffs and gorges.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.43.0", + "android": "6.0.0", + "ios": "4.0.0", + "macos": "0.7.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }, + "paint_background": { + "background-color": { + "type": "color", + "default": "#000000", + "doc": "The color with which the background will be drawn.", + "transition": true, + "requires": [ + { + "!": "background-pattern" + } + ], + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + }, + "background-pattern": { + "type": "resolvedImage", + "transition": true, + "doc": "Name of image in sprite to use for drawing an image background. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels.", + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + }, + "data-driven styling": {} + }, + "expression": { + "interpolated": false, + "parameters": [ + "zoom" + ] + }, + "property-type": "cross-faded" + }, + "background-opacity": { + "type": "number", + "default": 1, + "minimum": 0, + "maximum": 1, + "doc": "The opacity at which the background will be drawn.", + "transition": true, + "sdk-support": { + "basic functionality": { + "js": "0.10.0", + "android": "2.0.1", + "ios": "2.0.0", + "macos": "0.1.0" + } + }, + "expression": { + "interpolated": true, + "parameters": [ + "zoom" + ] + }, + "property-type": "data-constant" + } + }, + "transition": { + "duration": { + "type": "number", + "default": 300, + "minimum": 0, + "units": "milliseconds", + "doc": "Time allotted for transitions to complete." + }, + "delay": { + "type": "number", + "default": 0, + "minimum": 0, + "units": "milliseconds", + "doc": "Length of time before a transition begins." + } + }, + "property-type": { + "data-driven": { + "type": "property-type", + "doc": "Property is interpolable and can be represented using a property expression." + }, + "cross-faded": { + "type": "property-type", + "doc": "Property is non-interpolable; rather, its values will be cross-faded to smoothly transition between integer zooms." + }, + "cross-faded-data-driven": { + "type": "property-type", + "doc": "Property is non-interpolable; rather, its values will be cross-faded to smoothly transition between integer zooms. It can be represented using a property expression." + }, + "color-ramp": { + "type": "property-type", + "doc": "Property should be specified using a color ramp from which the output color can be sampled based on a property calculation." + }, + "data-constant": { + "type": "property-type", + "doc": "Property is interpolable but cannot be represented using a property expression." + }, + "constant": { + "type": "property-type", + "doc": "Property is constant across all zoom levels and property values." + } + }, + "promoteId": { + "*": { + "type": "string", + "doc": "A name of a feature property to use as ID for feature state." + } + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/rollup.config.js b/node_modules/mapbox-gl/src/style-spec/rollup.config.js new file mode 100644 index 0000000000000000000000000000000000000000..f0829ad896f27acbae70171d1b3c3d2e749f32a8 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/rollup.config.js @@ -0,0 +1,65 @@ +import path from 'path'; +import replace from 'rollup-plugin-replace'; +import buble from 'rollup-plugin-buble'; +import resolve from 'rollup-plugin-node-resolve'; +import commonjs from 'rollup-plugin-commonjs'; +import unassert from 'rollup-plugin-unassert'; +import json from 'rollup-plugin-json'; +import {flow} from '../../build/rollup_plugins'; + +// Build es modules? +const esm = 'esm' in process.env; + +const transforms = { + dangerousForOf: true, + modules: esm ? false : undefined +}; + +const ROOT_DIR = __dirname; + +const config = [{ + input: `${__dirname}/style-spec.js`, + output: { + name: 'mapboxGlStyleSpecification', + file: `${__dirname}/dist/${esm ? 'index.es.js' : 'index.js'}`, + format: esm ? 'esm' : 'umd', + sourcemap: true + }, + plugins: [ + { + name: 'dep-checker', + resolveId(source, importer) { + // Some users reference modules within style-spec package directly, instead of the bundle + // This means that files within the style-spec package should NOT import files from the parent mapbox-gl-js tree. + // This check will cause the build to fail on CI allowing these issues to be caught. + if (importer && !importer.includes('node_modules')) { + const resolvedPath = path.join(importer, source); + const fromRoot = path.relative(ROOT_DIR, resolvedPath); + if (fromRoot.length > 2 && fromRoot.slice(0, 2) === '..') { + throw new Error(`Module ${importer} imports ${source} from outside the style-spec package root directory.`); + } + } + + return null; + } + }, + // https://github.com/zaach/jison/issues/351 + replace({ + include: /\/jsonlint-lines-primitives\/lib\/jsonlint.js/, + delimiters: ['', ''], + values: { + '_token_stack:': '' + } + }), + flow(), + json(), + buble({transforms, objectAssign: "Object.assign"}), + unassert(), + resolve({ + browser: true, + preferBuiltins: false + }), + commonjs() + ] +}]; +export default config; diff --git a/node_modules/mapbox-gl/src/style-spec/style-spec.js b/node_modules/mapbox-gl/src/style-spec/style-spec.js new file mode 100644 index 0000000000000000000000000000000000000000..7bf178923533d9ff228c21f333b15e56dd0b9620 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/style-spec.js @@ -0,0 +1,124 @@ +// @flow + +type ExpressionType = 'data-driven' | 'cross-faded' | 'cross-faded-data-driven' | 'color-ramp' | 'data-constant' | 'constant'; +type ExpressionParameters = Array<'zoom' | 'feature' | 'feature-state' | 'heatmap-density' | 'line-progress'>; + +type ExpressionSpecification = { + interpolated: boolean, + parameters: ExpressionParameters +} + +export type StylePropertySpecification = { + type: 'number', + 'property-type': ExpressionType, + expression?: ExpressionSpecification, + transition: boolean, + default?: number +} | { + type: 'string', + 'property-type': ExpressionType, + expression?: ExpressionSpecification, + transition: boolean, + default?: string, + tokens?: boolean +} | { + type: 'boolean', + 'property-type': ExpressionType, + expression?: ExpressionSpecification, + transition: boolean, + default?: boolean +} | { + type: 'enum', + 'property-type': ExpressionType, + expression?: ExpressionSpecification, + values: {[_: string]: {}}, + transition: boolean, + default?: string +} | { + type: 'color', + 'property-type': ExpressionType, + expression?: ExpressionSpecification, + transition: boolean, + default?: string, + overridable: boolean +} | { + type: 'array', + value: 'number', + 'property-type': ExpressionType, + expression?: ExpressionSpecification, + length?: number, + transition: boolean, + default?: Array +} | { + type: 'array', + value: 'string', + 'property-type': ExpressionType, + expression?: ExpressionSpecification, + length?: number, + transition: boolean, + default?: Array +}; + +import v8 from './reference/v8.json'; +import latest from './reference/latest'; +import format from './format'; +import migrate from './migrate'; +import composite from './composite'; +import derefLayers from './deref'; +import diff from './diff'; +import ValidationError from './error/validation_error'; +import ParsingError from './error/parsing_error'; +import {StyleExpression, isExpression, createExpression, createPropertyExpression, normalizePropertyExpression, ZoomConstantExpression, ZoomDependentExpression, StylePropertyFunction} from './expression'; +import featureFilter, {isExpressionFilter} from './feature_filter'; + +import convertFilter from './feature_filter/convert'; +import Color from './util/color'; +import {createFunction, isFunction} from './function'; +import convertFunction from './function/convert'; +import {eachSource, eachLayer, eachProperty} from './visit'; + +import validate from './validate_style'; +import validateMapboxApiSupported from './validate_mapbox_api_supported'; + +const expression = { + StyleExpression, + isExpression, + isExpressionFilter, + createExpression, + createPropertyExpression, + normalizePropertyExpression, + ZoomConstantExpression, + ZoomDependentExpression, + StylePropertyFunction +}; + +const styleFunction = { + convertFunction, + createFunction, + isFunction +}; + +const visit = {eachSource, eachLayer, eachProperty}; + +export { + v8, + latest, + format, + migrate, + composite, + derefLayers, + diff, + ValidationError, + ParsingError, + expression, + featureFilter, + convertFilter, + Color, + styleFunction as function, + validate, + validateMapboxApiSupported, + visit +}; + +validate.parsed = validate; +validate.latest = validate; diff --git a/node_modules/mapbox-gl/src/style-spec/types.js b/node_modules/mapbox-gl/src/style-spec/types.js new file mode 100644 index 0000000000000000000000000000000000000000..34a380e1ba078952476f3a52308d8902d2131bae --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/types.js @@ -0,0 +1,432 @@ +// @flow +// Generated code; do not edit. Edit build/generate-flow-typed-style-spec.js instead. +/* eslint-disable */ + +export type ColorSpecification = string; + +export type FormattedSpecification = string; + +export type ResolvedImageSpecification = string; + +export type PromoteIdSpecification = {[_: string]: string} | string; + +export type FilterSpecification = + | ['has', string] + | ['!has', string] + | ['==', string, string | number | boolean] + | ['!=', string, string | number | boolean] + | ['>', string, string | number | boolean] + | ['>=', string, string | number | boolean] + | ['<', string, string | number | boolean] + | ['<=', string, string | number | boolean] + | Array; // Can't type in, !in, all, any, none -- https://github.com/facebook/flow/issues/2443 + +export type TransitionSpecification = { + duration?: number, + delay?: number +}; + +// Note: doesn't capture interpolatable vs. non-interpolatable types. + +export type CameraFunctionSpecification = + | {| type: 'exponential', stops: Array<[number, T]> |} + | {| type: 'interval', stops: Array<[number, T]> |}; + +export type SourceFunctionSpecification = + | {| type: 'exponential', stops: Array<[number, T]>, property: string, default?: T |} + | {| type: 'interval', stops: Array<[number, T]>, property: string, default?: T |} + | {| type: 'categorical', stops: Array<[string | number | boolean, T]>, property: string, default?: T |} + | {| type: 'identity', property: string, default?: T |}; + +export type CompositeFunctionSpecification = + | {| type: 'exponential', stops: Array<[{zoom: number, value: number}, T]>, property: string, default?: T |} + | {| type: 'interval', stops: Array<[{zoom: number, value: number}, T]>, property: string, default?: T |} + | {| type: 'categorical', stops: Array<[{zoom: number, value: string | number | boolean}, T]>, property: string, default?: T |}; + +export type ExpressionSpecification = Array; + +export type PropertyValueSpecification = + | T + | CameraFunctionSpecification + | ExpressionSpecification; + +export type DataDrivenPropertyValueSpecification = + | T + | CameraFunctionSpecification + | SourceFunctionSpecification + | CompositeFunctionSpecification + | ExpressionSpecification; + +export type StyleSpecification = {| + "version": 8, + "name"?: string, + "metadata"?: mixed, + "center"?: Array, + "zoom"?: number, + "bearing"?: number, + "pitch"?: number, + "light"?: LightSpecification, + "sources": {[_: string]: SourceSpecification}, + "sprite"?: string, + "glyphs"?: string, + "transition"?: TransitionSpecification, + "layers": Array +|} + +export type LightSpecification = {| + "anchor"?: PropertyValueSpecification<"map" | "viewport">, + "position"?: PropertyValueSpecification<[number, number, number]>, + "color"?: PropertyValueSpecification, + "intensity"?: PropertyValueSpecification +|} + +export type VectorSourceSpecification = { + "type": "vector", + "url"?: string, + "tiles"?: Array, + "bounds"?: [number, number, number, number], + "scheme"?: "xyz" | "tms", + "minzoom"?: number, + "maxzoom"?: number, + "attribution"?: string, + "promoteId"?: PromoteIdSpecification, + "volatile"?: boolean +} + +export type RasterSourceSpecification = { + "type": "raster", + "url"?: string, + "tiles"?: Array, + "bounds"?: [number, number, number, number], + "minzoom"?: number, + "maxzoom"?: number, + "tileSize"?: number, + "scheme"?: "xyz" | "tms", + "attribution"?: string, + "volatile"?: boolean +} + +export type RasterDEMSourceSpecification = { + "type": "raster-dem", + "url"?: string, + "tiles"?: Array, + "bounds"?: [number, number, number, number], + "minzoom"?: number, + "maxzoom"?: number, + "tileSize"?: number, + "attribution"?: string, + "encoding"?: "terrarium" | "mapbox", + "volatile"?: boolean +} + +export type GeoJSONSourceSpecification = {| + "type": "geojson", + "data"?: mixed, + "maxzoom"?: number, + "attribution"?: string, + "buffer"?: number, + "filter"?: mixed, + "tolerance"?: number, + "cluster"?: boolean, + "clusterRadius"?: number, + "clusterMaxZoom"?: number, + "clusterMinPoints"?: number, + "clusterProperties"?: mixed, + "lineMetrics"?: boolean, + "generateId"?: boolean, + "promoteId"?: PromoteIdSpecification +|} + +export type VideoSourceSpecification = {| + "type": "video", + "urls": Array, + "coordinates": [[number, number], [number, number], [number, number], [number, number]] +|} + +export type ImageSourceSpecification = {| + "type": "image", + "url": string, + "coordinates": [[number, number], [number, number], [number, number], [number, number]] +|} + +export type SourceSpecification = + | VectorSourceSpecification + | RasterSourceSpecification + | RasterDEMSourceSpecification + | GeoJSONSourceSpecification + | VideoSourceSpecification + | ImageSourceSpecification + +export type FillLayerSpecification = {| + "id": string, + "type": "fill", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "fill-sort-key"?: DataDrivenPropertyValueSpecification, + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "fill-antialias"?: PropertyValueSpecification, + "fill-opacity"?: DataDrivenPropertyValueSpecification, + "fill-color"?: DataDrivenPropertyValueSpecification, + "fill-outline-color"?: DataDrivenPropertyValueSpecification, + "fill-translate"?: PropertyValueSpecification<[number, number]>, + "fill-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, + "fill-pattern"?: DataDrivenPropertyValueSpecification + |} +|} + +export type LineLayerSpecification = {| + "id": string, + "type": "line", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "line-cap"?: PropertyValueSpecification<"butt" | "round" | "square">, + "line-join"?: DataDrivenPropertyValueSpecification<"bevel" | "round" | "miter">, + "line-miter-limit"?: PropertyValueSpecification, + "line-round-limit"?: PropertyValueSpecification, + "line-sort-key"?: DataDrivenPropertyValueSpecification, + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "line-opacity"?: DataDrivenPropertyValueSpecification, + "line-color"?: DataDrivenPropertyValueSpecification, + "line-translate"?: PropertyValueSpecification<[number, number]>, + "line-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, + "line-width"?: DataDrivenPropertyValueSpecification, + "line-gap-width"?: DataDrivenPropertyValueSpecification, + "line-offset"?: DataDrivenPropertyValueSpecification, + "line-blur"?: DataDrivenPropertyValueSpecification, + "line-dasharray"?: PropertyValueSpecification>, + "line-pattern"?: DataDrivenPropertyValueSpecification, + "line-gradient"?: ExpressionSpecification + |} +|} + +export type SymbolLayerSpecification = {| + "id": string, + "type": "symbol", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "symbol-placement"?: PropertyValueSpecification<"point" | "line" | "line-center">, + "symbol-spacing"?: PropertyValueSpecification, + "symbol-avoid-edges"?: PropertyValueSpecification, + "symbol-sort-key"?: DataDrivenPropertyValueSpecification, + "symbol-z-order"?: PropertyValueSpecification<"auto" | "viewport-y" | "source">, + "icon-allow-overlap"?: PropertyValueSpecification, + "icon-ignore-placement"?: PropertyValueSpecification, + "icon-optional"?: PropertyValueSpecification, + "icon-rotation-alignment"?: PropertyValueSpecification<"map" | "viewport" | "auto">, + "icon-size"?: DataDrivenPropertyValueSpecification, + "icon-text-fit"?: PropertyValueSpecification<"none" | "width" | "height" | "both">, + "icon-text-fit-padding"?: PropertyValueSpecification<[number, number, number, number]>, + "icon-image"?: DataDrivenPropertyValueSpecification, + "icon-rotate"?: DataDrivenPropertyValueSpecification, + "icon-padding"?: PropertyValueSpecification, + "icon-keep-upright"?: PropertyValueSpecification, + "icon-offset"?: DataDrivenPropertyValueSpecification<[number, number]>, + "icon-anchor"?: DataDrivenPropertyValueSpecification<"center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right">, + "icon-pitch-alignment"?: PropertyValueSpecification<"map" | "viewport" | "auto">, + "text-pitch-alignment"?: PropertyValueSpecification<"map" | "viewport" | "auto">, + "text-rotation-alignment"?: PropertyValueSpecification<"map" | "viewport" | "auto">, + "text-field"?: DataDrivenPropertyValueSpecification, + "text-font"?: DataDrivenPropertyValueSpecification>, + "text-size"?: DataDrivenPropertyValueSpecification, + "text-max-width"?: DataDrivenPropertyValueSpecification, + "text-line-height"?: PropertyValueSpecification, + "text-letter-spacing"?: DataDrivenPropertyValueSpecification, + "text-justify"?: DataDrivenPropertyValueSpecification<"auto" | "left" | "center" | "right">, + "text-radial-offset"?: DataDrivenPropertyValueSpecification, + "text-variable-anchor"?: PropertyValueSpecification>, + "text-anchor"?: DataDrivenPropertyValueSpecification<"center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right">, + "text-max-angle"?: PropertyValueSpecification, + "text-writing-mode"?: PropertyValueSpecification>, + "text-rotate"?: DataDrivenPropertyValueSpecification, + "text-padding"?: PropertyValueSpecification, + "text-keep-upright"?: PropertyValueSpecification, + "text-transform"?: DataDrivenPropertyValueSpecification<"none" | "uppercase" | "lowercase">, + "text-offset"?: DataDrivenPropertyValueSpecification<[number, number]>, + "text-allow-overlap"?: PropertyValueSpecification, + "text-ignore-placement"?: PropertyValueSpecification, + "text-optional"?: PropertyValueSpecification, + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "icon-opacity"?: DataDrivenPropertyValueSpecification, + "icon-color"?: DataDrivenPropertyValueSpecification, + "icon-halo-color"?: DataDrivenPropertyValueSpecification, + "icon-halo-width"?: DataDrivenPropertyValueSpecification, + "icon-halo-blur"?: DataDrivenPropertyValueSpecification, + "icon-translate"?: PropertyValueSpecification<[number, number]>, + "icon-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, + "text-opacity"?: DataDrivenPropertyValueSpecification, + "text-color"?: DataDrivenPropertyValueSpecification, + "text-halo-color"?: DataDrivenPropertyValueSpecification, + "text-halo-width"?: DataDrivenPropertyValueSpecification, + "text-halo-blur"?: DataDrivenPropertyValueSpecification, + "text-translate"?: PropertyValueSpecification<[number, number]>, + "text-translate-anchor"?: PropertyValueSpecification<"map" | "viewport"> + |} +|} + +export type CircleLayerSpecification = {| + "id": string, + "type": "circle", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "circle-sort-key"?: DataDrivenPropertyValueSpecification, + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "circle-radius"?: DataDrivenPropertyValueSpecification, + "circle-color"?: DataDrivenPropertyValueSpecification, + "circle-blur"?: DataDrivenPropertyValueSpecification, + "circle-opacity"?: DataDrivenPropertyValueSpecification, + "circle-translate"?: PropertyValueSpecification<[number, number]>, + "circle-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, + "circle-pitch-scale"?: PropertyValueSpecification<"map" | "viewport">, + "circle-pitch-alignment"?: PropertyValueSpecification<"map" | "viewport">, + "circle-stroke-width"?: DataDrivenPropertyValueSpecification, + "circle-stroke-color"?: DataDrivenPropertyValueSpecification, + "circle-stroke-opacity"?: DataDrivenPropertyValueSpecification + |} +|} + +export type HeatmapLayerSpecification = {| + "id": string, + "type": "heatmap", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "heatmap-radius"?: DataDrivenPropertyValueSpecification, + "heatmap-weight"?: DataDrivenPropertyValueSpecification, + "heatmap-intensity"?: PropertyValueSpecification, + "heatmap-color"?: ExpressionSpecification, + "heatmap-opacity"?: PropertyValueSpecification + |} +|} + +export type FillExtrusionLayerSpecification = {| + "id": string, + "type": "fill-extrusion", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "fill-extrusion-opacity"?: PropertyValueSpecification, + "fill-extrusion-color"?: DataDrivenPropertyValueSpecification, + "fill-extrusion-translate"?: PropertyValueSpecification<[number, number]>, + "fill-extrusion-translate-anchor"?: PropertyValueSpecification<"map" | "viewport">, + "fill-extrusion-pattern"?: DataDrivenPropertyValueSpecification, + "fill-extrusion-height"?: DataDrivenPropertyValueSpecification, + "fill-extrusion-base"?: DataDrivenPropertyValueSpecification, + "fill-extrusion-vertical-gradient"?: PropertyValueSpecification + |} +|} + +export type RasterLayerSpecification = {| + "id": string, + "type": "raster", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "raster-opacity"?: PropertyValueSpecification, + "raster-hue-rotate"?: PropertyValueSpecification, + "raster-brightness-min"?: PropertyValueSpecification, + "raster-brightness-max"?: PropertyValueSpecification, + "raster-saturation"?: PropertyValueSpecification, + "raster-contrast"?: PropertyValueSpecification, + "raster-resampling"?: PropertyValueSpecification<"linear" | "nearest">, + "raster-fade-duration"?: PropertyValueSpecification + |} +|} + +export type HillshadeLayerSpecification = {| + "id": string, + "type": "hillshade", + "metadata"?: mixed, + "source": string, + "source-layer"?: string, + "minzoom"?: number, + "maxzoom"?: number, + "filter"?: FilterSpecification, + "layout"?: {| + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "hillshade-illumination-direction"?: PropertyValueSpecification, + "hillshade-illumination-anchor"?: PropertyValueSpecification<"map" | "viewport">, + "hillshade-exaggeration"?: PropertyValueSpecification, + "hillshade-shadow-color"?: PropertyValueSpecification, + "hillshade-highlight-color"?: PropertyValueSpecification, + "hillshade-accent-color"?: PropertyValueSpecification + |} +|} + +export type BackgroundLayerSpecification = {| + "id": string, + "type": "background", + "metadata"?: mixed, + "minzoom"?: number, + "maxzoom"?: number, + "layout"?: {| + "visibility"?: "visible" | "none" + |}, + "paint"?: {| + "background-color"?: PropertyValueSpecification, + "background-pattern"?: PropertyValueSpecification, + "background-opacity"?: PropertyValueSpecification + |} +|} + +export type LayerSpecification = + | FillLayerSpecification + | LineLayerSpecification + | SymbolLayerSpecification + | CircleLayerSpecification + | HeatmapLayerSpecification + | FillExtrusionLayerSpecification + | RasterLayerSpecification + | HillshadeLayerSpecification + | BackgroundLayerSpecification; + diff --git a/node_modules/mapbox-gl/src/style-spec/util/color.js b/node_modules/mapbox-gl/src/style-spec/util/color.js new file mode 100644 index 0000000000000000000000000000000000000000..a8e59b74f053e123c2c2e209d213424e476deca0 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/util/color.js @@ -0,0 +1,95 @@ +// @flow + +import {parseCSSColor} from 'csscolorparser'; + +/** + * An RGBA color value. Create instances from color strings using the static + * method `Color.parse`. The constructor accepts RGB channel values in the range + * `[0, 1]`, premultiplied by A. + * + * @param {number} r The red channel. + * @param {number} g The green channel. + * @param {number} b The blue channel. + * @param {number} a The alpha channel. + * @private + */ +class Color { + r: number; + g: number; + b: number; + a: number; + + constructor(r: number, g: number, b: number, a: number = 1) { + this.r = r; + this.g = g; + this.b = b; + this.a = a; + } + + static black: Color; + static white: Color; + static transparent: Color; + static red: Color; + + /** + * Parses valid CSS color strings and returns a `Color` instance. + * @returns A `Color` instance, or `undefined` if the input is not a valid color string. + */ + static parse(input?: string | Color | null): Color | void { + if (!input) { + return undefined; + } + + if (input instanceof Color) { + return input; + } + + if (typeof input !== 'string') { + return undefined; + } + + const rgba = parseCSSColor(input); + if (!rgba) { + return undefined; + } + + return new Color( + rgba[0] / 255 * rgba[3], + rgba[1] / 255 * rgba[3], + rgba[2] / 255 * rgba[3], + rgba[3] + ); + } + + /** + * Returns an RGBA string representing the color value. + * + * @returns An RGBA string. + * @example + * var purple = new Color.parse('purple'); + * purple.toString; // = "rgba(128,0,128,1)" + * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)'); + * translucentGreen.toString(); // = "rgba(26,207,26,0.73)" + */ + toString(): string { + const [r, g, b, a] = this.toArray(); + return `rgba(${Math.round(r)},${Math.round(g)},${Math.round(b)},${a})`; + } + + toArray(): [number, number, number, number] { + const {r, g, b, a} = this; + return a === 0 ? [0, 0, 0, 0] : [ + r * 255 / a, + g * 255 / a, + b * 255 / a, + a + ]; + } +} + +Color.black = new Color(0, 0, 0, 1); +Color.white = new Color(1, 1, 1, 1); +Color.transparent = new Color(0, 0, 0, 0); +Color.red = new Color(1, 0, 0, 1); + +export default Color; diff --git a/node_modules/mapbox-gl/src/style-spec/util/color_spaces.js b/node_modules/mapbox-gl/src/style-spec/util/color_spaces.js new file mode 100644 index 0000000000000000000000000000000000000000..21ee75b0c69579c140c309b760e548de1a10ab52 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/util/color_spaces.js @@ -0,0 +1,139 @@ +// @flow + +import Color from './color'; + +import {number as interpolateNumber} from './interpolate'; + +type LABColor = { + l: number, + a: number, + b: number, + alpha: number +}; + +type HCLColor = { + h: number, + c: number, + l: number, + alpha: number +}; + +// Constants +const Xn = 0.950470, // D65 standard referent + Yn = 1, + Zn = 1.088830, + t0 = 4 / 29, + t1 = 6 / 29, + t2 = 3 * t1 * t1, + t3 = t1 * t1 * t1, + deg2rad = Math.PI / 180, + rad2deg = 180 / Math.PI; + +// Utilities +function xyz2lab(t: number) { + return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0; +} + +function lab2xyz(t: number) { + return t > t1 ? t * t * t : t2 * (t - t0); +} + +function xyz2rgb(x: number) { + return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); +} + +function rgb2xyz(x: number) { + x /= 255; + return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); +} + +// LAB +function rgbToLab(rgbColor: Color): LABColor { + const b = rgb2xyz(rgbColor.r), + a = rgb2xyz(rgbColor.g), + l = rgb2xyz(rgbColor.b), + x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn), + y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.0721750 * l) / Yn), + z = xyz2lab((0.0193339 * b + 0.1191920 * a + 0.9503041 * l) / Zn); + + return { + l: 116 * y - 16, + a: 500 * (x - y), + b: 200 * (y - z), + alpha: rgbColor.a + }; +} + +function labToRgb(labColor: LABColor): Color { + let y = (labColor.l + 16) / 116, + x = isNaN(labColor.a) ? y : y + labColor.a / 500, + z = isNaN(labColor.b) ? y : y - labColor.b / 200; + y = Yn * lab2xyz(y); + x = Xn * lab2xyz(x); + z = Zn * lab2xyz(z); + return new Color( + xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z), // D65 -> sRGB + xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z), + xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z), + labColor.alpha + ); +} + +function interpolateLab(from: LABColor, to: LABColor, t: number) { + return { + l: interpolateNumber(from.l, to.l, t), + a: interpolateNumber(from.a, to.a, t), + b: interpolateNumber(from.b, to.b, t), + alpha: interpolateNumber(from.alpha, to.alpha, t) + }; +} + +// HCL +function rgbToHcl(rgbColor: Color): HCLColor { + const {l, a, b} = rgbToLab(rgbColor); + const h = Math.atan2(b, a) * rad2deg; + return { + h: h < 0 ? h + 360 : h, + c: Math.sqrt(a * a + b * b), + l, + alpha: rgbColor.a + }; +} + +function hclToRgb(hclColor: HCLColor): Color { + const h = hclColor.h * deg2rad, + c = hclColor.c, + l = hclColor.l; + return labToRgb({ + l, + a: Math.cos(h) * c, + b: Math.sin(h) * c, + alpha: hclColor.alpha + }); +} + +function interpolateHue(a: number, b: number, t: number) { + const d = b - a; + return a + t * (d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d); +} + +function interpolateHcl(from: HCLColor, to: HCLColor, t: number) { + return { + h: interpolateHue(from.h, to.h, t), + c: interpolateNumber(from.c, to.c, t), + l: interpolateNumber(from.l, to.l, t), + alpha: interpolateNumber(from.alpha, to.alpha, t) + }; +} + +export const lab = { + forward: rgbToLab, + reverse: labToRgb, + interpolate: interpolateLab +}; + +export const hcl = { + forward: rgbToHcl, + reverse: hclToRgb, + interpolate: interpolateHcl +}; diff --git a/node_modules/mapbox-gl/src/style-spec/util/deep_equal.js b/node_modules/mapbox-gl/src/style-spec/util/deep_equal.js new file mode 100644 index 0000000000000000000000000000000000000000..773af912f59bb444a04c86f675494d1975655f03 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/util/deep_equal.js @@ -0,0 +1,28 @@ +// @flow + +/** + * Deeply compares two object literals. + * + * @private + */ +function deepEqual(a: ?mixed, b: ?mixed): boolean { + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + if (!deepEqual(a[i], b[i])) return false; + } + return true; + } + if (typeof a === 'object' && a !== null && b !== null) { + if (!(typeof b === 'object')) return false; + const keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) return false; + for (const key in a) { + if (!deepEqual(a[key], b[key])) return false; + } + return true; + } + return a === b; +} + +export default deepEqual; diff --git a/node_modules/mapbox-gl/src/style-spec/util/extend.js b/node_modules/mapbox-gl/src/style-spec/util/extend.js new file mode 100644 index 0000000000000000000000000000000000000000..076b6f278a47b49af73cfab5fc51b5ca0982735c --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/util/extend.js @@ -0,0 +1,10 @@ +// @flow + +export default function (output: any, ...inputs: Array) { + for (const input of inputs) { + for (const k in input) { + output[k] = input[k]; + } + } + return output; +} diff --git a/node_modules/mapbox-gl/src/style-spec/util/get_type.js b/node_modules/mapbox-gl/src/style-spec/util/get_type.js new file mode 100644 index 0000000000000000000000000000000000000000..18b03eb625ebc7aad027b948fd33e06883ddc918 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/util/get_type.js @@ -0,0 +1,17 @@ +// @flow + +export default function getType(val: mixed): string { + if (val instanceof Number) { + return 'number'; + } else if (val instanceof String) { + return 'string'; + } else if (val instanceof Boolean) { + return 'boolean'; + } else if (Array.isArray(val)) { + return 'array'; + } else if (val === null) { + return 'null'; + } else { + return typeof val; + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/util/interpolate.js b/node_modules/mapbox-gl/src/style-spec/util/interpolate.js new file mode 100644 index 0000000000000000000000000000000000000000..9cbed3caa1676915ee89caeebac6528f9ce8fc78 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/util/interpolate.js @@ -0,0 +1,22 @@ +// @flow + +import Color from './color'; + +export function number(a: number, b: number, t: number) { + return (a * (1 - t)) + (b * t); +} + +export function color(from: Color, to: Color, t: number) { + return new Color( + number(from.r, to.r, t), + number(from.g, to.g, t), + number(from.b, to.b, t), + number(from.a, to.a, t) + ); +} + +export function array(from: Array, to: Array, t: number): Array { + return from.map((d, i) => { + return number(d, to[i], t); + }); +} diff --git a/node_modules/mapbox-gl/src/style-spec/util/properties.js b/node_modules/mapbox-gl/src/style-spec/util/properties.js new file mode 100644 index 0000000000000000000000000000000000000000..dbb3ef914421e92f57151086b251c1bf3df94ed8 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/util/properties.js @@ -0,0 +1,15 @@ +// @flow + +import type {StylePropertySpecification} from '../style-spec'; + +export function supportsPropertyExpression(spec: StylePropertySpecification): boolean { + return spec['property-type'] === 'data-driven' || spec['property-type'] === 'cross-faded-data-driven'; +} + +export function supportsZoomExpression(spec: StylePropertySpecification): boolean { + return !!spec.expression && spec.expression.parameters.indexOf('zoom') > -1; +} + +export function supportsInterpolation(spec: StylePropertySpecification): boolean { + return !!spec.expression && spec.expression.interpolated; +} diff --git a/node_modules/mapbox-gl/src/style-spec/util/ref_properties.js b/node_modules/mapbox-gl/src/style-spec/util/ref_properties.js new file mode 100644 index 0000000000000000000000000000000000000000..c3cab034c469742b81dcde0cad5b8663c31430b3 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/util/ref_properties.js @@ -0,0 +1,2 @@ + +export default ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout']; diff --git a/node_modules/mapbox-gl/src/style-spec/util/result.js b/node_modules/mapbox-gl/src/style-spec/util/result.js new file mode 100644 index 0000000000000000000000000000000000000000..9d0d3a6c4f7cbbbc88882087e3e2daa25b7997f6 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/util/result.js @@ -0,0 +1,19 @@ +// @flow + +/** + * A type used for returning and propagating errors. The first element of the union + * represents success and contains a value, and the second represents an error and + * contains an error value. + * @private + */ +export type Result = + | {| result: 'success', value: T |} + | {| result: 'error', value: E |}; + +export function success(value: T): Result { + return {result: 'success', value}; +} + +export function error(value: E): Result { + return {result: 'error', value}; +} diff --git a/node_modules/mapbox-gl/src/style-spec/util/unbundle_jsonlint.js b/node_modules/mapbox-gl/src/style-spec/util/unbundle_jsonlint.js new file mode 100644 index 0000000000000000000000000000000000000000..72eb2d92645ea23e134889a1a981a16cb9595bcd --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/util/unbundle_jsonlint.js @@ -0,0 +1,24 @@ +// @flow + +// Turn jsonlint-lines-primitives objects into primitive objects +export function unbundle(value: mixed) { + if (value instanceof Number || value instanceof String || value instanceof Boolean) { + return value.valueOf(); + } else { + return value; + } +} + +export function deepUnbundle(value: mixed): mixed { + if (Array.isArray(value)) { + return value.map(deepUnbundle); + } else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) { + const unbundledValue: { [key: string]: mixed } = {}; + for (const key in value) { + unbundledValue[key] = deepUnbundle(value[key]); + } + return unbundledValue; + } + + return unbundle(value); +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/latest.js b/node_modules/mapbox-gl/src/style-spec/validate/latest.js new file mode 100644 index 0000000000000000000000000000000000000000..91db6e9eef8e78729711fef8a5920d44feaaa811 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/latest.js @@ -0,0 +1,11 @@ + +import validateStyle from '../validate_style.min'; + +/* + * Validate a style against the latest specification. This method is optimized + * to keep its bundle size small by refraining from requiring jslint or old + * style spec versions. + * @see validateStyleMin + * @deprecated This file exists for backwards compatibility and will be dropped in the next minor release. + */ +export default validateStyle; diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate.js b/node_modules/mapbox-gl/src/style-spec/validate/validate.js new file mode 100644 index 0000000000000000000000000000000000000000..2c2c8aaaa1ed0c11f870d1c54511d56f20703f8f --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate.js @@ -0,0 +1,75 @@ + +import extend from '../util/extend'; +import {unbundle, deepUnbundle} from '../util/unbundle_jsonlint'; +import {isExpression} from '../expression'; +import {isFunction} from '../function'; + +import validateFunction from './validate_function'; +import validateExpression from './validate_expression'; +import validateObject from './validate_object'; +import validateArray from './validate_array'; +import validateBoolean from './validate_boolean'; +import validateNumber from './validate_number'; +import validateColor from './validate_color'; +import validateConstants from './validate_constants'; +import validateEnum from './validate_enum'; +import validateFilter from './validate_filter'; +import validateLayer from './validate_layer'; +import validateSource from './validate_source'; +import validateLight from './validate_light'; +import validateString from './validate_string'; +import validateFormatted from './validate_formatted'; +import validateImage from './validate_image'; + +const VALIDATORS = { + '*'() { + return []; + }, + 'array': validateArray, + 'boolean': validateBoolean, + 'number': validateNumber, + 'color': validateColor, + 'constants': validateConstants, + 'enum': validateEnum, + 'filter': validateFilter, + 'function': validateFunction, + 'layer': validateLayer, + 'object': validateObject, + 'source': validateSource, + 'light': validateLight, + 'string': validateString, + 'formatted': validateFormatted, + 'resolvedImage': validateImage +}; + +// Main recursive validation function. Tracks: +// +// - key: string representing location of validation in style tree. Used only +// for more informative error reporting. +// - value: current value from style being evaluated. May be anything from a +// high level object that needs to be descended into deeper or a simple +// scalar value. +// - valueSpec: current spec being evaluated. Tracks value. +// - styleSpec: current full spec being evaluated. + +export default function validate(options) { + const value = options.value; + const valueSpec = options.valueSpec; + const styleSpec = options.styleSpec; + + if (valueSpec.expression && isFunction(unbundle(value))) { + return validateFunction(options); + + } else if (valueSpec.expression && isExpression(deepUnbundle(value))) { + return validateExpression(options); + + } else if (valueSpec.type && VALIDATORS[valueSpec.type]) { + return VALIDATORS[valueSpec.type](options); + + } else { + const valid = validateObject(extend({}, options, { + valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec + })); + return valid; + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_array.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_array.js new file mode 100644 index 0000000000000000000000000000000000000000..2f5638a61acfeb5e972f8362a8bcb450fbbaedee --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_array.js @@ -0,0 +1,52 @@ + +import getType from '../util/get_type'; +import validate from './validate'; +import ValidationError from '../error/validation_error'; + +export default function validateArray(options) { + const array = options.value; + const arraySpec = options.valueSpec; + const style = options.style; + const styleSpec = options.styleSpec; + const key = options.key; + const validateArrayElement = options.arrayElementValidator || validate; + + if (getType(array) !== 'array') { + return [new ValidationError(key, array, `array expected, ${getType(array)} found`)]; + } + + if (arraySpec.length && array.length !== arraySpec.length) { + return [new ValidationError(key, array, `array length ${arraySpec.length} expected, length ${array.length} found`)]; + } + + if (arraySpec['min-length'] && array.length < arraySpec['min-length']) { + return [new ValidationError(key, array, `array length at least ${arraySpec['min-length']} expected, length ${array.length} found`)]; + } + + let arrayElementSpec = { + "type": arraySpec.value, + "values": arraySpec.values + }; + + if (styleSpec.$version < 7) { + arrayElementSpec.function = arraySpec.function; + } + + if (getType(arraySpec.value) === 'object') { + arrayElementSpec = arraySpec.value; + } + + let errors = []; + for (let i = 0; i < array.length; i++) { + errors = errors.concat(validateArrayElement({ + array, + arrayIndex: i, + value: array[i], + valueSpec: arrayElementSpec, + style, + styleSpec, + key: `${key}[${i}]` + })); + } + return errors; +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_boolean.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_boolean.js new file mode 100644 index 0000000000000000000000000000000000000000..5412b23d24f41705d6dedcae40d13c433db614ee --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_boolean.js @@ -0,0 +1,15 @@ + +import getType from '../util/get_type'; +import ValidationError from '../error/validation_error'; + +export default function validateBoolean(options) { + const value = options.value; + const key = options.key; + const type = getType(value); + + if (type !== 'boolean') { + return [new ValidationError(key, value, `boolean expected, ${type} found`)]; + } + + return []; +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_color.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_color.js new file mode 100644 index 0000000000000000000000000000000000000000..f0e935aada5a4b01e7d7be860342b54893f28dd2 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_color.js @@ -0,0 +1,20 @@ + +import ValidationError from '../error/validation_error'; +import getType from '../util/get_type'; +import {parseCSSColor} from 'csscolorparser'; + +export default function validateColor(options) { + const key = options.key; + const value = options.value; + const type = getType(value); + + if (type !== 'string') { + return [new ValidationError(key, value, `color expected, ${type} found`)]; + } + + if (parseCSSColor(value) === null) { + return [new ValidationError(key, value, `color expected, "${value}" found`)]; + } + + return []; +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_constants.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_constants.js new file mode 100644 index 0000000000000000000000000000000000000000..7888bb32621027d9ed83c3e85411c3383a3c35ab --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_constants.js @@ -0,0 +1,13 @@ + +import ValidationError from '../error/validation_error'; + +export default function validateConstants(options) { + const key = options.key; + const constants = options.value; + + if (constants) { + return [new ValidationError(key, constants, 'constants have been deprecated as of v8')]; + } else { + return []; + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_enum.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_enum.js new file mode 100644 index 0000000000000000000000000000000000000000..655830c96ab5bd1cb1e5c3f841c417df50fc9adf --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_enum.js @@ -0,0 +1,21 @@ + +import ValidationError from '../error/validation_error'; +import {unbundle} from '../util/unbundle_jsonlint'; + +export default function validateEnum(options) { + const key = options.key; + const value = options.value; + const valueSpec = options.valueSpec; + const errors = []; + + if (Array.isArray(valueSpec.values)) { // <=v7 + if (valueSpec.values.indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, `expected one of [${valueSpec.values.join(', ')}], ${JSON.stringify(value)} found`)); + } + } else { // >=v8 + if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) { + errors.push(new ValidationError(key, value, `expected one of [${Object.keys(valueSpec.values).join(', ')}], ${JSON.stringify(value)} found`)); + } + } + return errors; +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_expression.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_expression.js new file mode 100644 index 0000000000000000000000000000000000000000..63a73f441c1f7e5b1762a4d121d9b2bf7687a8f7 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_expression.js @@ -0,0 +1,43 @@ +// @flow + +import ValidationError from '../error/validation_error'; + +import {createExpression, createPropertyExpression} from '../expression'; +import {deepUnbundle} from '../util/unbundle_jsonlint'; +import {isStateConstant, isGlobalPropertyConstant, isFeatureConstant} from '../expression/is_constant'; + +export default function validateExpression(options: any): Array { + const expression = (options.expressionContext === 'property' ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec); + if (expression.result === 'error') { + return expression.value.map((error) => { + return new ValidationError(`${options.key}${error.key}`, options.value, error.message); + }); + } + + const expressionObj = (expression.value: any).expression || (expression.value: any)._styleExpression.expression; + + if (options.expressionContext === 'property' && (options.propertyKey === 'text-font') && + !expressionObj.outputDefined()) { + return [new ValidationError(options.key, options.value, `Invalid data expression for "${options.propertyKey}". Output values must be contained as literals within the expression.`)]; + } + + if (options.expressionContext === 'property' && options.propertyType === 'layout' && + (!isStateConstant(expressionObj))) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with layout properties.')]; + } + + if (options.expressionContext === 'filter' && !isStateConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with filters.')]; + } + + if (options.expressionContext && options.expressionContext.indexOf('cluster') === 0) { + if (!isGlobalPropertyConstant(expressionObj, ['zoom', 'feature-state'])) { + return [new ValidationError(options.key, options.value, '"zoom" and "feature-state" expressions are not supported with cluster properties.')]; + } + if (options.expressionContext === 'cluster-initial' && !isFeatureConstant(expressionObj)) { + return [new ValidationError(options.key, options.value, 'Feature data expressions are not supported with initial expression part of cluster properties.')]; + } + } + + return []; +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_filter.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_filter.js new file mode 100644 index 0000000000000000000000000000000000000000..804b7baac38e9739309f1f9e9b4c3345abd112dd --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_filter.js @@ -0,0 +1,117 @@ + +import ValidationError from '../error/validation_error'; +import validateExpression from './validate_expression'; +import validateEnum from './validate_enum'; +import getType from '../util/get_type'; +import {unbundle, deepUnbundle} from '../util/unbundle_jsonlint'; +import extend from '../util/extend'; +import {isExpressionFilter} from '../feature_filter'; + +export default function validateFilter(options) { + if (isExpressionFilter(deepUnbundle(options.value))) { + return validateExpression(extend({}, options, { + expressionContext: 'filter', + valueSpec: {value: 'boolean'} + })); + } else { + return validateNonExpressionFilter(options); + } +} + +function validateNonExpressionFilter(options) { + const value = options.value; + const key = options.key; + + if (getType(value) !== 'array') { + return [new ValidationError(key, value, `array expected, ${getType(value)} found`)]; + } + + const styleSpec = options.styleSpec; + let type; + + let errors = []; + + if (value.length < 1) { + return [new ValidationError(key, value, 'filter array must have at least 1 element')]; + } + + errors = errors.concat(validateEnum({ + key: `${key}[0]`, + value: value[0], + valueSpec: styleSpec.filter_operator, + style: options.style, + styleSpec: options.styleSpec + })); + + switch (unbundle(value[0])) { + case '<': + case '<=': + case '>': + case '>=': + if (value.length >= 2 && unbundle(value[1]) === '$type') { + errors.push(new ValidationError(key, value, `"$type" cannot be use with operator "${value[0]}"`)); + } + /* falls through */ + case '==': + case '!=': + if (value.length !== 3) { + errors.push(new ValidationError(key, value, `filter array for operator "${value[0]}" must have 3 elements`)); + } + /* falls through */ + case 'in': + case '!in': + if (value.length >= 2) { + type = getType(value[1]); + if (type !== 'string') { + errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`)); + } + } + for (let i = 2; i < value.length; i++) { + type = getType(value[i]); + if (unbundle(value[1]) === '$type') { + errors = errors.concat(validateEnum({ + key: `${key}[${i}]`, + value: value[i], + valueSpec: styleSpec.geometry_type, + style: options.style, + styleSpec: options.styleSpec + })); + } else if (type !== 'string' && type !== 'number' && type !== 'boolean') { + errors.push(new ValidationError(`${key}[${i}]`, value[i], `string, number, or boolean expected, ${type} found`)); + } + } + break; + + case 'any': + case 'all': + case 'none': + for (let i = 1; i < value.length; i++) { + errors = errors.concat(validateNonExpressionFilter({ + key: `${key}[${i}]`, + value: value[i], + style: options.style, + styleSpec: options.styleSpec + })); + } + break; + + case 'has': + case '!has': + type = getType(value[1]); + if (value.length !== 2) { + errors.push(new ValidationError(key, value, `filter array for "${value[0]}" operator must have 2 elements`)); + } else if (type !== 'string') { + errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`)); + } + break; + case 'within': + type = getType(value[1]); + if (value.length !== 2) { + errors.push(new ValidationError(key, value, `filter array for "${value[0]}" operator must have 2 elements`)); + } else if (type !== 'object') { + errors.push(new ValidationError(`${key}[1]`, value[1], `object expected, ${type} found`)); + } + break; + } + return errors; +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_formatted.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_formatted.js new file mode 100644 index 0000000000000000000000000000000000000000..61ed402df3d39604299a50bd9c2d3b5990454a2d --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_formatted.js @@ -0,0 +1,11 @@ +// @flow +import validateExpression from './validate_expression'; +import validateString from './validate_string'; + +export default function validateFormatted(options: any) { + if (validateString(options).length === 0) { + return []; + } + + return validateExpression(options); +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_function.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_function.js new file mode 100644 index 0000000000000000000000000000000000000000..5c2fa42e6fff4b4eb53f510f726fc13867e31e5d --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_function.js @@ -0,0 +1,207 @@ + +import ValidationError from '../error/validation_error'; +import getType from '../util/get_type'; +import validate from './validate'; +import validateObject from './validate_object'; +import validateArray from './validate_array'; +import validateNumber from './validate_number'; +import {isExpression} from '../expression'; +import {unbundle, deepUnbundle} from '../util/unbundle_jsonlint'; +import { + supportsPropertyExpression, + supportsZoomExpression, + supportsInterpolation +} from '../util/properties'; + +export default function validateFunction(options) { + const functionValueSpec = options.valueSpec; + const functionType = unbundle(options.value.type); + let stopKeyType; + let stopDomainValues = {}; + let previousStopDomainValue; + let previousStopDomainZoom; + + const isZoomFunction = functionType !== 'categorical' && options.value.property === undefined; + const isPropertyFunction = !isZoomFunction; + const isZoomAndPropertyFunction = + getType(options.value.stops) === 'array' && + getType(options.value.stops[0]) === 'array' && + getType(options.value.stops[0][0]) === 'object'; + + const errors = validateObject({ + key: options.key, + value: options.value, + valueSpec: options.styleSpec.function, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + stops: validateFunctionStops, + default: validateFunctionDefault + } + }); + + if (functionType === 'identity' && isZoomFunction) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "property"')); + } + + if (functionType !== 'identity' && !options.value.stops) { + errors.push(new ValidationError(options.key, options.value, 'missing required property "stops"')); + } + + if (functionType === 'exponential' && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'exponential functions not supported')); + } + + if (options.styleSpec.$version >= 8) { + if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'property functions not supported')); + } else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) { + errors.push(new ValidationError(options.key, options.value, 'zoom functions not supported')); + } + } + + if ((functionType === 'categorical' || isZoomAndPropertyFunction) && options.value.property === undefined) { + errors.push(new ValidationError(options.key, options.value, '"property" property is required')); + } + + return errors; + + function validateFunctionStops(options) { + if (functionType === 'identity') { + return [new ValidationError(options.key, options.value, 'identity function may not have a "stops" property')]; + } + + let errors = []; + const value = options.value; + + errors = errors.concat(validateArray({ + key: options.key, + value, + valueSpec: options.valueSpec, + style: options.style, + styleSpec: options.styleSpec, + arrayElementValidator: validateFunctionStop + })); + + if (getType(value) === 'array' && value.length === 0) { + errors.push(new ValidationError(options.key, value, 'array must have at least one stop')); + } + + return errors; + } + + function validateFunctionStop(options) { + let errors = []; + const value = options.value; + const key = options.key; + + if (getType(value) !== 'array') { + return [new ValidationError(key, value, `array expected, ${getType(value)} found`)]; + } + + if (value.length !== 2) { + return [new ValidationError(key, value, `array length 2 expected, length ${value.length} found`)]; + } + + if (isZoomAndPropertyFunction) { + if (getType(value[0]) !== 'object') { + return [new ValidationError(key, value, `object expected, ${getType(value[0])} found`)]; + } + if (value[0].zoom === undefined) { + return [new ValidationError(key, value, 'object stop key must have zoom')]; + } + if (value[0].value === undefined) { + return [new ValidationError(key, value, 'object stop key must have value')]; + } + if (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) { + return [new ValidationError(key, value[0].zoom, 'stop zoom values must appear in ascending order')]; + } + if (unbundle(value[0].zoom) !== previousStopDomainZoom) { + previousStopDomainZoom = unbundle(value[0].zoom); + previousStopDomainValue = undefined; + stopDomainValues = {}; + } + errors = errors.concat(validateObject({ + key: `${key}[0]`, + value: value[0], + valueSpec: {zoom: {}}, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: {zoom: validateNumber, value: validateStopDomainValue} + })); + } else { + errors = errors.concat(validateStopDomainValue({ + key: `${key}[0]`, + value: value[0], + valueSpec: {}, + style: options.style, + styleSpec: options.styleSpec + }, value)); + } + + if (isExpression(deepUnbundle(value[1]))) { + return errors.concat([new ValidationError(`${key}[1]`, value[1], 'expressions are not allowed in function stops.')]); + } + + return errors.concat(validate({ + key: `${key}[1]`, + value: value[1], + valueSpec: functionValueSpec, + style: options.style, + styleSpec: options.styleSpec + })); + } + + function validateStopDomainValue(options, stop) { + const type = getType(options.value); + const value = unbundle(options.value); + + const reportValue = options.value !== null ? options.value : stop; + + if (!stopKeyType) { + stopKeyType = type; + } else if (type !== stopKeyType) { + return [new ValidationError(options.key, reportValue, `${type} stop domain type must match previous stop domain type ${stopKeyType}`)]; + } + + if (type !== 'number' && type !== 'string' && type !== 'boolean') { + return [new ValidationError(options.key, reportValue, 'stop domain value must be a number, string, or boolean')]; + } + + if (type !== 'number' && functionType !== 'categorical') { + let message = `number expected, ${type} found`; + if (supportsPropertyExpression(functionValueSpec) && functionType === undefined) { + message += '\nIf you intended to use a categorical function, specify `"type": "categorical"`.'; + } + return [new ValidationError(options.key, reportValue, message)]; + } + + if (functionType === 'categorical' && type === 'number' && (!isFinite(value) || Math.floor(value) !== value)) { + return [new ValidationError(options.key, reportValue, `integer expected, found ${value}`)]; + } + + if (functionType !== 'categorical' && type === 'number' && previousStopDomainValue !== undefined && value < previousStopDomainValue) { + return [new ValidationError(options.key, reportValue, 'stop domain values must appear in ascending order')]; + } else { + previousStopDomainValue = value; + } + + if (functionType === 'categorical' && value in stopDomainValues) { + return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')]; + } else { + stopDomainValues[value] = true; + } + + return []; + } + + function validateFunctionDefault(options) { + return validate({ + key: options.key, + value: options.value, + valueSpec: functionValueSpec, + style: options.style, + styleSpec: options.styleSpec + }); + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_glyphs_url.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_glyphs_url.js new file mode 100644 index 0000000000000000000000000000000000000000..84f74aadef159d147d18b374fbad7396a47976ca --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_glyphs_url.js @@ -0,0 +1,21 @@ + +import ValidationError from '../error/validation_error'; +import validateString from './validate_string'; + +export default function(options) { + const value = options.value; + const key = options.key; + + const errors = validateString(options); + if (errors.length) return errors; + + if (value.indexOf('{fontstack}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{fontstack}" token')); + } + + if (value.indexOf('{range}') === -1) { + errors.push(new ValidationError(key, value, '"glyphs" url must include a "{range}" token')); + } + + return errors; +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_image.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_image.js new file mode 100644 index 0000000000000000000000000000000000000000..b02763ffd92e8db0d2947398fae727ef316bbbe5 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_image.js @@ -0,0 +1,11 @@ +// @flow +import validateExpression from './validate_expression'; +import validateString from './validate_string'; + +export default function validateImage(options: any) { + if (validateString(options).length === 0) { + return []; + } + + return validateExpression(options); +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_layer.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..6cfc75e1f013a5f0ec71d87ef51edc6422995a0f --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_layer.js @@ -0,0 +1,134 @@ + +import ValidationError from '../error/validation_error'; +import {unbundle} from '../util/unbundle_jsonlint'; +import validateObject from './validate_object'; +import validateFilter from './validate_filter'; +import validatePaintProperty from './validate_paint_property'; +import validateLayoutProperty from './validate_layout_property'; +import validateSpec from './validate'; +import extend from '../util/extend'; + +export default function validateLayer(options) { + let errors = []; + + const layer = options.value; + const key = options.key; + const style = options.style; + const styleSpec = options.styleSpec; + + if (!layer.type && !layer.ref) { + errors.push(new ValidationError(key, layer, 'either "type" or "ref" is required')); + } + let type = unbundle(layer.type); + const ref = unbundle(layer.ref); + + if (layer.id) { + const layerId = unbundle(layer.id); + for (let i = 0; i < options.arrayIndex; i++) { + const otherLayer = style.layers[i]; + if (unbundle(otherLayer.id) === layerId) { + errors.push(new ValidationError(key, layer.id, `duplicate layer id "${layer.id}", previously used at line ${otherLayer.id.__line__}`)); + } + } + } + + if ('ref' in layer) { + ['type', 'source', 'source-layer', 'filter', 'layout'].forEach((p) => { + if (p in layer) { + errors.push(new ValidationError(key, layer[p], `"${p}" is prohibited for ref layers`)); + } + }); + + let parent; + + style.layers.forEach((layer) => { + if (unbundle(layer.id) === ref) parent = layer; + }); + + if (!parent) { + errors.push(new ValidationError(key, layer.ref, `ref layer "${ref}" not found`)); + } else if (parent.ref) { + errors.push(new ValidationError(key, layer.ref, 'ref cannot reference another ref layer')); + } else { + type = unbundle(parent.type); + } + } else if (type !== 'background') { + if (!layer.source) { + errors.push(new ValidationError(key, layer, 'missing required property "source"')); + } else { + const source = style.sources && style.sources[layer.source]; + const sourceType = source && unbundle(source.type); + if (!source) { + errors.push(new ValidationError(key, layer.source, `source "${layer.source}" not found`)); + } else if (sourceType === 'vector' && type === 'raster') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a raster source`)); + } else if (sourceType === 'raster' && type !== 'raster') { + errors.push(new ValidationError(key, layer.source, `layer "${layer.id}" requires a vector source`)); + } else if (sourceType === 'vector' && !layer['source-layer']) { + errors.push(new ValidationError(key, layer, `layer "${layer.id}" must specify a "source-layer"`)); + } else if (sourceType === 'raster-dem' && type !== 'hillshade') { + errors.push(new ValidationError(key, layer.source, 'raster-dem source can only be used with layer type \'hillshade\'.')); + } else if (type === 'line' && layer.paint && layer.paint['line-gradient'] && + (sourceType !== 'geojson' || !source.lineMetrics)) { + errors.push(new ValidationError(key, layer, `layer "${layer.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)); + } + } + } + + errors = errors.concat(validateObject({ + key, + value: layer, + valueSpec: styleSpec.layer, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + '*'() { + return []; + }, + // We don't want to enforce the spec's `"requires": true` for backward compatibility with refs; + // the actual requirement is validated above. See https://github.com/mapbox/mapbox-gl-js/issues/5772. + type() { + return validateSpec({ + key: `${key}.type`, + value: layer.type, + valueSpec: styleSpec.layer.type, + style: options.style, + styleSpec: options.styleSpec, + object: layer, + objectKey: 'type' + }); + }, + filter: validateFilter, + layout(options) { + return validateObject({ + layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + '*'(options) { + return validateLayoutProperty(extend({layerType: type}, options)); + } + } + }); + }, + paint(options) { + return validateObject({ + layer, + key: options.key, + value: options.value, + style: options.style, + styleSpec: options.styleSpec, + objectElementValidators: { + '*'(options) { + return validatePaintProperty(extend({layerType: type}, options)); + } + } + }); + } + } + })); + + return errors; +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_layout_property.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_layout_property.js new file mode 100644 index 0000000000000000000000000000000000000000..da4151a0b4d46d193fa567279487a63bfa09fb4d --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_layout_property.js @@ -0,0 +1,6 @@ + +import validateProperty from './validate_property'; + +export default function validateLayoutProperty(options) { + return validateProperty(options, 'layout'); +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_light.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_light.js new file mode 100644 index 0000000000000000000000000000000000000000..4b3c364c32cbd57b4989d5c50aed0cb8f0eca580 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_light.js @@ -0,0 +1,47 @@ + +import ValidationError from '../error/validation_error'; +import getType from '../util/get_type'; +import validate from './validate'; + +export default function validateLight(options) { + const light = options.value; + const styleSpec = options.styleSpec; + const lightSpec = styleSpec.light; + const style = options.style; + + let errors = []; + + const rootType = getType(light); + if (light === undefined) { + return errors; + } else if (rootType !== 'object') { + errors = errors.concat([new ValidationError('light', light, `object expected, ${rootType} found`)]); + return errors; + } + + for (const key in light) { + const transitionMatch = key.match(/^(.*)-transition$/); + + if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) { + errors = errors.concat(validate({ + key, + value: light[key], + valueSpec: styleSpec.transition, + style, + styleSpec + })); + } else if (lightSpec[key]) { + errors = errors.concat(validate({ + key, + value: light[key], + valueSpec: lightSpec[key], + style, + styleSpec + })); + } else { + errors = errors.concat([new ValidationError(key, light[key], `unknown property "${key}"`)]); + } + } + + return errors; +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_number.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_number.js new file mode 100644 index 0000000000000000000000000000000000000000..1db12f0364db9f173e4599dc27f67e3c0f957ebe --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_number.js @@ -0,0 +1,29 @@ + +import getType from '../util/get_type'; +import ValidationError from '../error/validation_error'; + +export default function validateNumber(options) { + const key = options.key; + const value = options.value; + const valueSpec = options.valueSpec; + let type = getType(value); + + // eslint-disable-next-line no-self-compare + if (type === 'number' && value !== value) { + type = 'NaN'; + } + + if (type !== 'number') { + return [new ValidationError(key, value, `number expected, ${type} found`)]; + } + + if ('minimum' in valueSpec && value < valueSpec.minimum) { + return [new ValidationError(key, value, `${value} is less than the minimum value ${valueSpec.minimum}`)]; + } + + if ('maximum' in valueSpec && value > valueSpec.maximum) { + return [new ValidationError(key, value, `${value} is greater than the maximum value ${valueSpec.maximum}`)]; + } + + return []; +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_object.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_object.js new file mode 100644 index 0000000000000000000000000000000000000000..3f36e459e1301662c7bc80a3bde3628e0c451990 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_object.js @@ -0,0 +1,61 @@ + +import ValidationError from '../error/validation_error'; +import getType from '../util/get_type'; +import validateSpec from './validate'; + +export default function validateObject(options) { + const key = options.key; + const object = options.value; + const elementSpecs = options.valueSpec || {}; + const elementValidators = options.objectElementValidators || {}; + const style = options.style; + const styleSpec = options.styleSpec; + let errors = []; + + const type = getType(object); + if (type !== 'object') { + return [new ValidationError(key, object, `object expected, ${type} found`)]; + } + + for (const objectKey in object) { + const elementSpecKey = objectKey.split('.')[0]; // treat 'paint.*' as 'paint' + const elementSpec = elementSpecs[elementSpecKey] || elementSpecs['*']; + + let validateElement; + if (elementValidators[elementSpecKey]) { + validateElement = elementValidators[elementSpecKey]; + } else if (elementSpecs[elementSpecKey]) { + validateElement = validateSpec; + } else if (elementValidators['*']) { + validateElement = elementValidators['*']; + } else if (elementSpecs['*']) { + validateElement = validateSpec; + } else { + errors.push(new ValidationError(key, object[objectKey], `unknown property "${objectKey}"`)); + continue; + } + + errors = errors.concat(validateElement({ + key: (key ? `${key}.` : key) + objectKey, + value: object[objectKey], + valueSpec: elementSpec, + style, + styleSpec, + object, + objectKey + }, object)); + } + + for (const elementSpecKey in elementSpecs) { + // Don't check `required` when there's a custom validator for that property. + if (elementValidators[elementSpecKey]) { + continue; + } + + if (elementSpecs[elementSpecKey].required && elementSpecs[elementSpecKey]['default'] === undefined && object[elementSpecKey] === undefined) { + errors.push(new ValidationError(key, object, `missing required property "${elementSpecKey}"`)); + } + } + + return errors; +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_paint_property.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_paint_property.js new file mode 100644 index 0000000000000000000000000000000000000000..bafe9bbca060aa73e08d6498166ba0ebf637c811 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_paint_property.js @@ -0,0 +1,6 @@ + +import validateProperty from './validate_property'; + +export default function validatePaintProperty(options) { + return validateProperty(options, 'paint'); +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_property.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_property.js new file mode 100644 index 0000000000000000000000000000000000000000..c2e922bfbe9b065ccbf5dda728d0c8a35d299bc6 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_property.js @@ -0,0 +1,64 @@ + +import validate from './validate'; +import ValidationError from '../error/validation_error'; +import getType from '../util/get_type'; +import {isFunction} from '../function'; +import {unbundle, deepUnbundle} from '../util/unbundle_jsonlint'; +import {supportsPropertyExpression} from '../util/properties'; + +export default function validateProperty(options, propertyType) { + const key = options.key; + const style = options.style; + const styleSpec = options.styleSpec; + const value = options.value; + const propertyKey = options.objectKey; + const layerSpec = styleSpec[`${propertyType}_${options.layerType}`]; + + if (!layerSpec) return []; + + const transitionMatch = propertyKey.match(/^(.*)-transition$/); + if (propertyType === 'paint' && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) { + return validate({ + key, + value, + valueSpec: styleSpec.transition, + style, + styleSpec + }); + } + + const valueSpec = options.valueSpec || layerSpec[propertyKey]; + if (!valueSpec) { + return [new ValidationError(key, value, `unknown property "${propertyKey}"`)]; + } + + let tokenMatch; + if (getType(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) { + return [new ValidationError( + key, value, + `"${propertyKey}" does not support interpolation syntax\n` + + `Use an identity property function instead: \`{ "type": "identity", "property": ${JSON.stringify(tokenMatch[1])} }\`.`)]; + } + + const errors = []; + + if (options.layerType === 'symbol') { + if (propertyKey === 'text-field' && style && !style.glyphs) { + errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property')); + } + if (propertyKey === 'text-font' && isFunction(deepUnbundle(value)) && unbundle(value.type) === 'identity') { + errors.push(new ValidationError(key, value, '"text-font" does not support identity functions')); + } + } + + return errors.concat(validate({ + key: options.key, + value, + valueSpec, + style, + styleSpec, + expressionContext: 'property', + propertyType, + propertyKey + })); +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_source.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_source.js new file mode 100644 index 0000000000000000000000000000000000000000..820557d1487dc34bd540f676b1b4bac7da089071 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_source.js @@ -0,0 +1,111 @@ + +import ValidationError from '../error/validation_error'; +import {unbundle} from '../util/unbundle_jsonlint'; +import validateObject from './validate_object'; +import validateEnum from './validate_enum'; +import validateExpression from './validate_expression'; +import validateString from './validate_string'; +import getType from '../util/get_type'; + +const objectElementValidators = { + promoteId: validatePromoteId +}; + +export default function validateSource(options) { + const value = options.value; + const key = options.key; + const styleSpec = options.styleSpec; + const style = options.style; + + if (!value.type) { + return [new ValidationError(key, value, '"type" is required')]; + } + + const type = unbundle(value.type); + let errors; + + switch (type) { + case 'vector': + case 'raster': + case 'raster-dem': + errors = validateObject({ + key, + value, + valueSpec: styleSpec[`source_${type.replace('-', '_')}`], + style: options.style, + styleSpec, + objectElementValidators + }); + return errors; + + case 'geojson': + errors = validateObject({ + key, + value, + valueSpec: styleSpec.source_geojson, + style, + styleSpec, + objectElementValidators + }); + if (value.cluster) { + for (const prop in value.clusterProperties) { + const [operator, mapExpr] = value.clusterProperties[prop]; + const reduceExpr = typeof operator === 'string' ? [operator, ['accumulated'], ['get', prop]] : operator; + + errors.push(...validateExpression({ + key: `${key}.${prop}.map`, + value: mapExpr, + expressionContext: 'cluster-map' + })); + errors.push(...validateExpression({ + key: `${key}.${prop}.reduce`, + value: reduceExpr, + expressionContext: 'cluster-reduce' + })); + } + } + return errors; + + case 'video': + return validateObject({ + key, + value, + valueSpec: styleSpec.source_video, + style, + styleSpec + }); + + case 'image': + return validateObject({ + key, + value, + valueSpec: styleSpec.source_image, + style, + styleSpec + }); + + case 'canvas': + return [new ValidationError(key, null, `Please use runtime APIs to add canvas sources, rather than including them in stylesheets.`, 'source.canvas')]; + + default: + return validateEnum({ + key: `${key}.type`, + value: value.type, + valueSpec: {values: ['vector', 'raster', 'raster-dem', 'geojson', 'video', 'image']}, + style, + styleSpec + }); + } +} + +function validatePromoteId({key, value}) { + if (getType(value) === 'string') { + return validateString({key, value}); + } else { + const errors = []; + for (const prop in value) { + errors.push(...validateString({key: `${key}.${prop}`, value: value[prop]})); + } + return errors; + } +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate/validate_string.js b/node_modules/mapbox-gl/src/style-spec/validate/validate_string.js new file mode 100644 index 0000000000000000000000000000000000000000..c3353fdc5dcb8a1010cd09ef9ed38682169c5938 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate/validate_string.js @@ -0,0 +1,15 @@ + +import getType from '../util/get_type'; +import ValidationError from '../error/validation_error'; + +export default function validateString(options) { + const value = options.value; + const key = options.key; + const type = getType(value); + + if (type !== 'string') { + return [new ValidationError(key, value, `string expected, ${type} found`)]; + } + + return []; +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate_mapbox_api_supported.js b/node_modules/mapbox-gl/src/style-spec/validate_mapbox_api_supported.js new file mode 100644 index 0000000000000000000000000000000000000000..e51a99e812dee1a3f524c25539051f5e4af71279 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate_mapbox_api_supported.js @@ -0,0 +1,171 @@ +// @flow + +import validateStyle from './validate_style.min'; +import {v8} from './style-spec'; +import readStyle from './read_style'; +import ValidationError from './error/validation_error'; +import getType from './util/get_type'; + +const SUPPORTED_SPEC_VERSION = 8; +const MAX_SOURCES_IN_STYLE = 15; + +function isValid(value: ?string, regex: RegExp): boolean { + if (!value || getType(value) !== 'string') return true; + return !!value.match(regex); +} + +function getSourceCount(source: Object): number { + if (source.url) { + return source.url.split(',').length; + } else { + return 0; + } +} + +function getAllowedKeyErrors(obj: Object, keys: Array<*>, path: ?string): Array { + const allowed = new Set(keys); + const errors = []; + Object.keys(obj).forEach(k => { + if (!allowed.has(k)) { + const prop = path ? `${path}.${k}` : null; + errors.push(new ValidationError(prop, obj[k], `Unsupported property "${k}"`)); + } + }); + return errors; +} + +function getSourceErrors(source: Object, i: number): Array { + const errors = []; + + /* + * Inlined sources are not supported by the Mapbox Styles API, so only + * "type", "url", and "tileSize" properties are valid + */ + const sourceKeys = ['type', 'url', 'tileSize']; + errors.push(...getAllowedKeyErrors(source, sourceKeys, 'source')); + + /* + * "source" is required. Valid examples: + * mapbox://mapbox.abcd1234 + * mapbox://penny.abcd1234 + * mapbox://mapbox.abcd1234,penny.abcd1234 + */ + const sourceUrlPattern = /^mapbox:\/\/([^/]*)$/; + if (!isValid(source.url, sourceUrlPattern)) { + errors.push(new ValidationError(`sources[${i}]`, source.url, 'Source url must be a valid Mapbox tileset url')); + } + + return errors; +} + +function getSourcesErrors(sources: Object): Array { + const errors = []; + let count = 0; + + Object.keys(sources).forEach((s: string, i: number) => { + const sourceErrors = getSourceErrors(sources[s], i); + + // If source has errors, skip counting + if (!sourceErrors.length) { + count = count + getSourceCount(sources[s]); + } + + errors.push(...sourceErrors); + }); + + if (count > MAX_SOURCES_IN_STYLE) { + errors.push(new ValidationError('sources', null, `Styles must contain ${MAX_SOURCES_IN_STYLE} or fewer sources`)); + } + + return errors; +} + +function getRootErrors(style: Object, specKeys: Array): Array { + const errors = []; + + /* + * The following keys are optional but fully managed by the Mapbox Styles + * API. Values on stylesheet on POST or PATCH will be ignored: "owner", + * "id", "cacheControl", "draft", "created", "modified" + * + * The following keys are optional. The Mapbox Styles API respects value on + * stylesheet on PATCH, but ignores the value on POST: "visibility" + */ + const optionalRootProperties = [ + 'owner', + 'id', + 'cacheControl', + 'draft', + 'created', + 'modified', + 'visibility' + ]; + + const allowedKeyErrors = getAllowedKeyErrors(style, [...specKeys, ...optionalRootProperties]); + errors.push(...allowedKeyErrors); + + if (style.version > SUPPORTED_SPEC_VERSION || style.version < SUPPORTED_SPEC_VERSION) { + errors.push(new ValidationError('version', style.version, `Style version must be ${SUPPORTED_SPEC_VERSION}`)); + } + + /* + * "glyphs" is optional. If present, valid examples: + * mapbox://fonts/penny/{fontstack}/{range}.pbf + * mapbox://fonts/mapbox/{fontstack}/{range}.pbf + */ + const glyphUrlPattern = /^mapbox:\/\/fonts\/([^/]*)\/{fontstack}\/{range}.pbf$/; + if (!isValid(style.glyphs, glyphUrlPattern)) { + errors.push(new ValidationError('glyphs', style.glyphs, 'Styles must reference glyphs hosted by Mapbox')); + } + + /* + * "sprite" is optional. If present, valid examples: + * mapbox://sprites/penny/abcd1234 + * mapbox://sprites/mapbox/abcd1234/draft + * mapbox://sprites/cyrus/abcd1234/abcd1234 + */ + const spriteUrlPattern = /^mapbox:\/\/sprites\/([^/]*)\/([^/]*)\/?([^/]*)?$/; + if (!isValid(style.sprite, spriteUrlPattern)) { + errors.push(new ValidationError('sprite', style.sprite, 'Styles must reference sprites hosted by Mapbox')); + } + + /* + * "visibility" is optional. If present, valid examples: + * "private" + * "public" + */ + const visibilityPattern = /^(public|private)$/; + if (!isValid(style.visibility, visibilityPattern)) { + errors.push(new ValidationError('visibility', style.visibility, 'Style visibility must be public or private')); + } + + return errors; +} + +/** + * Validate a Mapbox GL style against the style specification and check for + * compatibility with the Mapbox Styles API. + * + * @param {Object} style The style to be validated. + * @returns {Array} + * @example + * var validateMapboxApiSupported = require('mapbox-gl-style-spec/lib/validate_style_mapbox_api_supported.js'); + * var errors = validateMapboxApiSupported(style); + */ +export default function validateMapboxApiSupported(style: Object): Array { + let s = style; + try { + s = readStyle(s); + } catch (e) { + return [e]; + } + + let errors = validateStyle(s, v8) + .concat(getRootErrors(s, Object.keys(v8.$root))); + + if (s.sources) { + errors = errors.concat(getSourcesErrors(s.sources)); + } + + return errors; +} diff --git a/node_modules/mapbox-gl/src/style-spec/validate_style.js b/node_modules/mapbox-gl/src/style-spec/validate_style.js new file mode 100644 index 0000000000000000000000000000000000000000..d5d9f0578de203ff7e4df3b3455e7977ae089538 --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate_style.js @@ -0,0 +1,39 @@ + +import validateStyleMin from './validate_style.min'; +import {v8} from './style-spec'; +import readStyle from './read_style'; + +/** + * Validate a Mapbox GL style against the style specification. + * + * @private + * @alias validate + * @param {Object|String|Buffer} style The style to be validated. If a `String` + * or `Buffer` is provided, the returned errors will contain line numbers. + * @param {Object} [styleSpec] The style specification to validate against. + * If omitted, the spec version is inferred from the stylesheet. + * @returns {Array} + * @example + * var validate = require('mapbox-gl-style-spec').validate; + * var style = fs.readFileSync('./style.json', 'utf8'); + * var errors = validate(style); + */ + +export default function validateStyle(style, styleSpec = v8) { + let s = style; + + try { + s = readStyle(s); + } catch (e) { + return [e]; + } + + return validateStyleMin(s, styleSpec); +} + +export const source = validateStyleMin.source; +export const light = validateStyleMin.light; +export const layer = validateStyleMin.layer; +export const filter = validateStyleMin.filter; +export const paintProperty = validateStyleMin.paintProperty; +export const layoutProperty = validateStyleMin.layoutProperty; diff --git a/node_modules/mapbox-gl/src/style-spec/validate_style.min.js b/node_modules/mapbox-gl/src/style-spec/validate_style.min.js new file mode 100644 index 0000000000000000000000000000000000000000..b3166e800ea9b8f296adecc3c37779d40dc4cc6a --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/validate_style.min.js @@ -0,0 +1,78 @@ + +import validateConstants from './validate/validate_constants'; +import validate from './validate/validate'; +import latestStyleSpec from './reference/latest'; +import validateGlyphsURL from './validate/validate_glyphs_url'; + +import validateSource from './validate/validate_source'; +import validateLight from './validate/validate_light'; +import validateLayer from './validate/validate_layer'; +import validateFilter from './validate/validate_filter'; +import validatePaintProperty from './validate/validate_paint_property'; +import validateLayoutProperty from './validate/validate_layout_property'; + +/** + * Validate a Mapbox GL style against the style specification. This entrypoint, + * `mapbox-gl-style-spec/lib/validate_style.min`, is designed to produce as + * small a browserify bundle as possible by omitting unnecessary functionality + * and legacy style specifications. + * + * @private + * @param {Object} style The style to be validated. + * @param {Object} [styleSpec] The style specification to validate against. + * If omitted, the latest style spec is used. + * @returns {Array} + * @example + * var validate = require('mapbox-gl-style-spec/lib/validate_style.min'); + * var errors = validate(style); + */ +function validateStyleMin(style, styleSpec = latestStyleSpec) { + + let errors = []; + + errors = errors.concat(validate({ + key: '', + value: style, + valueSpec: styleSpec.$root, + styleSpec, + style, + objectElementValidators: { + glyphs: validateGlyphsURL, + '*'() { + return []; + } + } + })); + + if (style.constants) { + errors = errors.concat(validateConstants({ + key: 'constants', + value: style.constants, + style, + styleSpec + })); + } + + return sortErrors(errors); +} + +validateStyleMin.source = wrapCleanErrors(validateSource); +validateStyleMin.light = wrapCleanErrors(validateLight); +validateStyleMin.layer = wrapCleanErrors(validateLayer); +validateStyleMin.filter = wrapCleanErrors(validateFilter); +validateStyleMin.paintProperty = wrapCleanErrors(validatePaintProperty); +validateStyleMin.layoutProperty = wrapCleanErrors(validateLayoutProperty); + +function sortErrors(errors) { + return [].concat(errors).sort((a, b) => { + return a.line - b.line; + }); +} + +function wrapCleanErrors(inner) { + return function(...args) { + return sortErrors(inner.apply(this, args)); + }; +} + +export default validateStyleMin; diff --git a/node_modules/mapbox-gl/src/style-spec/visit.js b/node_modules/mapbox-gl/src/style-spec/visit.js new file mode 100644 index 0000000000000000000000000000000000000000..2911c1f03624e5abee4846714ef877d5d293024e --- /dev/null +++ b/node_modules/mapbox-gl/src/style-spec/visit.js @@ -0,0 +1,77 @@ +// @flow + +import Reference from './reference/v8.json'; +import type {StylePropertySpecification} from './style-spec'; +import type { + StyleSpecification, + SourceSpecification, + LayerSpecification, + PropertyValueSpecification, + DataDrivenPropertyValueSpecification +} from './types'; + +function getPropertyReference(propertyName): StylePropertySpecification { + for (let i = 0; i < Reference.layout.length; i++) { + for (const key in Reference[Reference.layout[i]]) { + if (key === propertyName) return (Reference[Reference.layout[i]][key]: any); + } + } + for (let i = 0; i < Reference.paint.length; i++) { + for (const key in Reference[Reference.paint[i]]) { + if (key === propertyName) return (Reference[Reference.paint[i]][key]: any); + } + } + + return (null: any); +} + +export function eachSource(style: StyleSpecification, callback: (_: SourceSpecification) => void) { + for (const k in style.sources) { + callback(style.sources[k]); + } +} + +export function eachLayer(style: StyleSpecification, callback: (_: LayerSpecification) => void) { + for (const layer of style.layers) { + callback(layer); + } +} + +type PropertyCallback = ({ + path: [string, 'paint' | 'layout', string], // [layerid, paint/layout, property key] + key: string, + value: PropertyValueSpecification | DataDrivenPropertyValueSpecification, + reference: StylePropertySpecification, + set: (PropertyValueSpecification | DataDrivenPropertyValueSpecification) => void +}) => void; + +export function eachProperty( + style: StyleSpecification, + options: {paint?: boolean, layout?: boolean}, + callback: PropertyCallback +) { + function inner(layer, propertyType: 'paint' | 'layout') { + const properties = (layer[propertyType]: any); + if (!properties) return; + Object.keys(properties).forEach((key) => { + callback({ + path: [layer.id, propertyType, key], + key, + value: properties[key], + reference: getPropertyReference(key), + set(x) { + properties[key] = x; + } + }); + }); + } + + eachLayer(style, (layer) => { + if (options.paint) { + inner(layer, 'paint'); + } + if (options.layout) { + inner(layer, 'layout'); + } + }); +} diff --git a/node_modules/mapbox-gl/src/style/create_style_layer.js b/node_modules/mapbox-gl/src/style/create_style_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..aae084e6e8d39e586d807ba9511799c1d247e7e8 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/create_style_layer.js @@ -0,0 +1,36 @@ +// @flow + +import circle from './style_layer/circle_style_layer'; +import heatmap from './style_layer/heatmap_style_layer'; +import hillshade from './style_layer/hillshade_style_layer'; +import fill from './style_layer/fill_style_layer'; +import fillExtrusion from './style_layer/fill_extrusion_style_layer'; +import line from './style_layer/line_style_layer'; +import symbol from './style_layer/symbol_style_layer'; +import background from './style_layer/background_style_layer'; +import raster from './style_layer/raster_style_layer'; +import CustomStyleLayer from './style_layer/custom_style_layer'; +import type {CustomLayerInterface} from './style_layer/custom_style_layer'; + +import type {LayerSpecification} from '../style-spec/types'; + +const subclasses = { + circle, + heatmap, + hillshade, + fill, + 'fill-extrusion': fillExtrusion, + line, + symbol, + background, + raster +}; + +export default function createStyleLayer(layer: LayerSpecification | CustomLayerInterface) { + if (layer.type === 'custom') { + return new CustomStyleLayer(layer); + } else { + return new subclasses[layer.type](layer); + } +} + diff --git a/node_modules/mapbox-gl/src/style/evaluation_parameters.js b/node_modules/mapbox-gl/src/style/evaluation_parameters.js new file mode 100644 index 0000000000000000000000000000000000000000..a0bdc3930eb5a70c760e693f957d1478b7adcefe --- /dev/null +++ b/node_modules/mapbox-gl/src/style/evaluation_parameters.js @@ -0,0 +1,62 @@ +// @flow + +import ZoomHistory from './zoom_history'; +import {isStringInSupportedScript} from '../util/script_detection'; +import {plugin as rtlTextPlugin} from '../source/rtl_text_plugin'; + +import type {TransitionSpecification} from '../style-spec/types'; + +export type CrossfadeParameters = { + fromScale: number, + toScale: number, + t: number +}; + +class EvaluationParameters { + zoom: number; + now: number; + fadeDuration: number; + zoomHistory: ZoomHistory; + transition: TransitionSpecification; + + // "options" may also be another EvaluationParameters to copy, see CrossFadedProperty.possiblyEvaluate + constructor(zoom: number, options?: *) { + this.zoom = zoom; + + if (options) { + this.now = options.now; + this.fadeDuration = options.fadeDuration; + this.zoomHistory = options.zoomHistory; + this.transition = options.transition; + } else { + this.now = 0; + this.fadeDuration = 0; + this.zoomHistory = new ZoomHistory(); + this.transition = {}; + } + } + + isSupportedScript(str: string): boolean { + return isStringInSupportedScript(str, rtlTextPlugin.isLoaded()); + } + + crossFadingFactor() { + if (this.fadeDuration === 0) { + return 1; + } else { + return Math.min((this.now - this.zoomHistory.lastIntegerZoomTime) / this.fadeDuration, 1); + } + } + + getCrossfadeParameters(): CrossfadeParameters { + const z = this.zoom; + const fraction = z - Math.floor(z); + const t = this.crossFadingFactor(); + + return z > this.zoomHistory.lastIntegerZoom ? + {fromScale: 2, toScale: 1, t: fraction + (1 - fraction) * t} : + {fromScale: 0.5, toScale: 1, t: 1 - (1 - t) * fraction}; + } +} + +export default EvaluationParameters; diff --git a/node_modules/mapbox-gl/src/style/format_section_override.js b/node_modules/mapbox-gl/src/style/format_section_override.js new file mode 100644 index 0000000000000000000000000000000000000000..fd69be19ee1a229c88a757ed02cf2a67d53c09a8 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/format_section_override.js @@ -0,0 +1,56 @@ +// @flow + +import assert from 'assert'; +import type {Expression} from '../style-spec/expression/expression'; +import type EvaluationContext from '../style-spec/expression/evaluation_context'; +import type {Type} from '../style-spec/expression/types'; +import type {ZoomConstantExpression} from '../style-spec/expression'; +import {NullType} from '../style-spec/expression/types'; +import {PossiblyEvaluatedPropertyValue} from './properties'; +import {register} from '../util/web_worker_transfer'; + +// This is an internal expression class. It is only used in GL JS and +// has GL JS dependencies which can break the standalone style-spec module +export default class FormatSectionOverride implements Expression { + type: Type; + defaultValue: PossiblyEvaluatedPropertyValue; + + constructor(defaultValue: PossiblyEvaluatedPropertyValue) { + assert(defaultValue.property.overrides !== undefined); + this.type = defaultValue.property.overrides ? defaultValue.property.overrides.runtimeType : NullType; + this.defaultValue = defaultValue; + } + + evaluate(ctx: EvaluationContext) { + if (ctx.formattedSection) { + const overrides = this.defaultValue.property.overrides; + if (overrides && overrides.hasOverride(ctx.formattedSection)) { + return overrides.getOverride(ctx.formattedSection); + } + } + + if (ctx.feature && ctx.featureState) { + return this.defaultValue.evaluate(ctx.feature, ctx.featureState); + } + + return this.defaultValue.property.specification.default; + } + + eachChild(fn: (_: Expression) => void) { + if (!this.defaultValue.isConstant()) { + const expr: ZoomConstantExpression<'source'> = ((this.defaultValue.value): any); + fn(expr._styleExpression.expression); + } + } + + // Cannot be statically evaluated, as the output depends on the evaluation context. + outputDefined() { + return false; + } + + serialize() { + return null; + } +} + +register('FormatSectionOverride', FormatSectionOverride, {omit: ['defaultValue']}); diff --git a/node_modules/mapbox-gl/src/style/light.js b/node_modules/mapbox-gl/src/style/light.js new file mode 100644 index 0000000000000000000000000000000000000000..99c24d0d2320abd876227b89c070dcafad3524b6 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/light.js @@ -0,0 +1,130 @@ +// @flow + +import styleSpec from '../style-spec/reference/latest'; + +import {endsWith, extend, sphericalToCartesian} from '../util/util'; +import {Evented} from '../util/evented'; +import { + validateStyle, + validateLight, + emitValidationErrors +} from './validate_style'; +import Color from '../style-spec/util/color'; +import {number as interpolate} from '../style-spec/util/interpolate'; + +import type {StylePropertySpecification} from '../style-spec/style-spec'; +import type EvaluationParameters from './evaluation_parameters'; +import type {StyleSetterOptions} from '../style/style'; +import {Properties, Transitionable, Transitioning, PossiblyEvaluated, DataConstantProperty} from './properties'; + +import type { + Property, + PropertyValue, + TransitionParameters +} from './properties'; + +import type {LightSpecification} from '../style-spec/types'; + +type LightPosition = { + x: number, + y: number, + z: number +}; + +class LightPositionProperty implements Property<[number, number, number], LightPosition> { + specification: StylePropertySpecification; + + constructor() { + this.specification = styleSpec.light.position; + } + + possiblyEvaluate(value: PropertyValue<[number, number, number], LightPosition>, parameters: EvaluationParameters): LightPosition { + return sphericalToCartesian(value.expression.evaluate(parameters)); + } + + interpolate(a: LightPosition, b: LightPosition, t: number): LightPosition { + return { + x: interpolate(a.x, b.x, t), + y: interpolate(a.y, b.y, t), + z: interpolate(a.z, b.z, t), + }; + } +} + +type Props = {| + "anchor": DataConstantProperty<"map" | "viewport">, + "position": LightPositionProperty, + "color": DataConstantProperty, + "intensity": DataConstantProperty, +|}; + +const properties: Properties = new Properties({ + "anchor": new DataConstantProperty(styleSpec.light.anchor), + "position": new LightPositionProperty(), + "color": new DataConstantProperty(styleSpec.light.color), + "intensity": new DataConstantProperty(styleSpec.light.intensity), +}); + +const TRANSITION_SUFFIX = '-transition'; + +/* + * Represents the light used to light extruded features. + */ +class Light extends Evented { + _transitionable: Transitionable; + _transitioning: Transitioning; + properties: PossiblyEvaluated; + + constructor(lightOptions?: LightSpecification) { + super(); + this._transitionable = new Transitionable(properties); + this.setLight(lightOptions); + this._transitioning = this._transitionable.untransitioned(); + } + + getLight() { + return this._transitionable.serialize(); + } + + setLight(light?: LightSpecification, options: StyleSetterOptions = {}) { + if (this._validate(validateLight, light, options)) { + return; + } + + for (const name in light) { + const value = light[name]; + if (endsWith(name, TRANSITION_SUFFIX)) { + this._transitionable.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), value); + } else { + this._transitionable.setValue(name, value); + } + } + } + + updateTransitions(parameters: TransitionParameters) { + this._transitioning = this._transitionable.transitioned(parameters, this._transitioning); + } + + hasTransition() { + return this._transitioning.hasTransition(); + } + + recalculate(parameters: EvaluationParameters) { + this.properties = this._transitioning.possiblyEvaluate(parameters); + } + + _validate(validate: Function, value: mixed, options?: {validate?: boolean}) { + if (options && options.validate === false) { + return false; + } + + return emitValidationErrors(this, validate.call(validateStyle, extend({ + value, + // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407 + style: {glyphs: true, sprite: true}, + styleSpec + }))); + } +} + +export default Light; diff --git a/node_modules/mapbox-gl/src/style/load_glyph_range.js b/node_modules/mapbox-gl/src/style/load_glyph_range.js new file mode 100644 index 0000000000000000000000000000000000000000..d57efd6f0290c272b9a5d072d79ff4d0005b2e89 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/load_glyph_range.js @@ -0,0 +1,38 @@ +// @flow + +import {getArrayBuffer, ResourceType} from '../util/ajax'; + +import parseGlyphPBF from './parse_glyph_pbf'; + +import type {StyleGlyph} from './style_glyph'; +import type {RequestManager} from '../util/mapbox'; +import type {Callback} from '../types/callback'; + +export default function (fontstack: string, + range: number, + urlTemplate: string, + requestManager: RequestManager, + callback: Callback<{[_: number]: StyleGlyph | null}>) { + const begin = range * 256; + const end = begin + 255; + + const request = requestManager.transformRequest( + requestManager.normalizeGlyphsURL(urlTemplate) + .replace('{fontstack}', fontstack) + .replace('{range}', `${begin}-${end}`), + ResourceType.Glyphs); + + getArrayBuffer(request, (err: ?Error, data: ?ArrayBuffer) => { + if (err) { + callback(err); + } else if (data) { + const glyphs = {}; + + for (const glyph of parseGlyphPBF(data)) { + glyphs[glyph.id] = glyph; + } + + callback(null, glyphs); + } + }); +} diff --git a/node_modules/mapbox-gl/src/style/load_sprite.js b/node_modules/mapbox-gl/src/style/load_sprite.js new file mode 100644 index 0000000000000000000000000000000000000000..2f166ca0c0b46652b6c6fc518d040b757a398edf --- /dev/null +++ b/node_modules/mapbox-gl/src/style/load_sprite.js @@ -0,0 +1,67 @@ +// @flow + +import {getJSON, getImage, ResourceType} from '../util/ajax'; + +import browser from '../util/browser'; +import {RGBAImage} from '../util/image'; + +import type {StyleImage} from './style_image'; +import type {RequestManager} from '../util/mapbox'; +import type {Callback} from '../types/callback'; +import type {Cancelable} from '../types/cancelable'; + +export default function(baseURL: string, + requestManager: RequestManager, + callback: Callback<{[_: string]: StyleImage}>): Cancelable { + let json: any, image, error; + const format = browser.devicePixelRatio > 1 ? '@2x' : ''; + + let jsonRequest = getJSON(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, '.json'), ResourceType.SpriteJSON), (err: ?Error, data: ?Object) => { + jsonRequest = null; + if (!error) { + error = err; + json = data; + maybeComplete(); + } + }); + + let imageRequest = getImage(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, '.png'), ResourceType.SpriteImage), (err, img) => { + imageRequest = null; + if (!error) { + error = err; + image = img; + maybeComplete(); + } + }); + + function maybeComplete() { + if (error) { + callback(error); + } else if (json && image) { + const imageData = browser.getImageData(image); + const result = {}; + + for (const id in json) { + const {width, height, x, y, sdf, pixelRatio, stretchX, stretchY, content} = json[id]; + const data = new RGBAImage({width, height}); + RGBAImage.copy(imageData, data, {x, y}, {x: 0, y: 0}, {width, height}); + result[id] = {data, pixelRatio, sdf, stretchX, stretchY, content}; + } + + callback(null, result); + } + } + + return { + cancel() { + if (jsonRequest) { + jsonRequest.cancel(); + jsonRequest = null; + } + if (imageRequest) { + imageRequest.cancel(); + imageRequest = null; + } + } + }; +} diff --git a/node_modules/mapbox-gl/src/style/parse_glyph_pbf.js b/node_modules/mapbox-gl/src/style/parse_glyph_pbf.js new file mode 100644 index 0000000000000000000000000000000000000000..c5536d721e1e5573ea8dbdd20c07d5c3efaee624 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/parse_glyph_pbf.js @@ -0,0 +1,44 @@ +// @flow + +import {AlphaImage} from '../util/image'; + +import Protobuf from 'pbf'; +const border = 3; + +import type {StyleGlyph} from './style_glyph'; + +function readFontstacks(tag: number, glyphs: Array, pbf: Protobuf) { + if (tag === 1) { + pbf.readMessage(readFontstack, glyphs); + } +} + +function readFontstack(tag: number, glyphs: Array, pbf: Protobuf) { + if (tag === 3) { + const {id, bitmap, width, height, left, top, advance} = pbf.readMessage(readGlyph, {}); + glyphs.push({ + id, + bitmap: new AlphaImage({ + width: width + 2 * border, + height: height + 2 * border + }, bitmap), + metrics: {width, height, left, top, advance} + }); + } +} + +function readGlyph(tag: number, glyph: Object, pbf: Protobuf) { + if (tag === 1) glyph.id = pbf.readVarint(); + else if (tag === 2) glyph.bitmap = pbf.readBytes(); + else if (tag === 3) glyph.width = pbf.readVarint(); + else if (tag === 4) glyph.height = pbf.readVarint(); + else if (tag === 5) glyph.left = pbf.readSVarint(); + else if (tag === 6) glyph.top = pbf.readSVarint(); + else if (tag === 7) glyph.advance = pbf.readVarint(); +} + +export default function (data: ArrayBuffer | Uint8Array): Array { + return new Protobuf(data).readFields(readFontstacks, []); +} + +export const GLYPH_PBF_BORDER = border; diff --git a/node_modules/mapbox-gl/src/style/pauseable_placement.js b/node_modules/mapbox-gl/src/style/pauseable_placement.js new file mode 100644 index 0000000000000000000000000000000000000000..d443ad6aea5698649456a8055f03853b73894d95 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/pauseable_placement.js @@ -0,0 +1,132 @@ +// @flow + +import browser from '../util/browser'; + +import {Placement} from '../symbol/placement'; + +import type Transform from '../geo/transform'; +import type StyleLayer from './style_layer'; +import type SymbolStyleLayer from './style_layer/symbol_style_layer'; +import type Tile from '../source/tile'; +import type {BucketPart} from '../symbol/placement'; + +class LayerPlacement { + _sortAcrossTiles: boolean; + _currentTileIndex: number; + _currentPartIndex: number; + _seenCrossTileIDs: { [string | number]: boolean }; + _bucketParts: Array; + + constructor(styleLayer: SymbolStyleLayer) { + this._sortAcrossTiles = styleLayer.layout.get('symbol-z-order') !== 'viewport-y' && + styleLayer.layout.get('symbol-sort-key').constantOr(1) !== undefined; + + this._currentTileIndex = 0; + this._currentPartIndex = 0; + this._seenCrossTileIDs = {}; + this._bucketParts = []; + } + + continuePlacement(tiles: Array, placement: Placement, showCollisionBoxes: boolean, styleLayer: StyleLayer, shouldPausePlacement: () => boolean) { + + const bucketParts = this._bucketParts; + + while (this._currentTileIndex < tiles.length) { + const tile = tiles[this._currentTileIndex]; + placement.getBucketParts(bucketParts, styleLayer, tile, this._sortAcrossTiles); + + this._currentTileIndex++; + if (shouldPausePlacement()) { + return true; + } + } + + if (this._sortAcrossTiles) { + this._sortAcrossTiles = false; + bucketParts.sort((a, b) => ((a.sortKey: any): number) - ((b.sortKey: any): number)); + } + + while (this._currentPartIndex < bucketParts.length) { + const bucketPart = bucketParts[this._currentPartIndex]; + placement.placeLayerBucketPart(bucketPart, this._seenCrossTileIDs, showCollisionBoxes); + + this._currentPartIndex++; + if (shouldPausePlacement()) { + return true; + } + } + return false; + } +} + +class PauseablePlacement { + placement: Placement; + _done: boolean; + _currentPlacementIndex: number; + _forceFullPlacement: boolean; + _showCollisionBoxes: boolean; + _inProgressLayer: ?LayerPlacement; + + constructor(transform: Transform, order: Array, + forceFullPlacement: boolean, + showCollisionBoxes: boolean, + fadeDuration: number, + crossSourceCollisions: boolean, + prevPlacement?: Placement) { + + this.placement = new Placement(transform, fadeDuration, crossSourceCollisions, prevPlacement); + this._currentPlacementIndex = order.length - 1; + this._forceFullPlacement = forceFullPlacement; + this._showCollisionBoxes = showCollisionBoxes; + this._done = false; + } + + isDone(): boolean { + return this._done; + } + + continuePlacement(order: Array, layers: {[_: string]: StyleLayer}, layerTiles: {[_: string]: Array}) { + const startTime = browser.now(); + + const shouldPausePlacement = () => { + const elapsedTime = browser.now() - startTime; + return this._forceFullPlacement ? false : elapsedTime > 2; + }; + + while (this._currentPlacementIndex >= 0) { + const layerId = order[this._currentPlacementIndex]; + const layer = layers[layerId]; + const placementZoom = this.placement.collisionIndex.transform.zoom; + if (layer.type === 'symbol' && + (!layer.minzoom || layer.minzoom <= placementZoom) && + (!layer.maxzoom || layer.maxzoom > placementZoom)) { + + if (!this._inProgressLayer) { + this._inProgressLayer = new LayerPlacement(((layer: any): SymbolStyleLayer)); + } + + const pausePlacement = this._inProgressLayer.continuePlacement(layerTiles[layer.source], this.placement, this._showCollisionBoxes, layer, shouldPausePlacement); + + if (pausePlacement) { + // We didn't finish placing all layers within 2ms, + // but we can keep rendering with a partial placement + // We'll resume here on the next frame + return; + } + + delete this._inProgressLayer; + } + + this._currentPlacementIndex--; + } + + this._done = true; + } + + commit(now: number) { + this.placement.commit(now); + return this.placement; + } +} + +export default PauseablePlacement; diff --git a/node_modules/mapbox-gl/src/style/properties.js b/node_modules/mapbox-gl/src/style/properties.js new file mode 100644 index 0000000000000000000000000000000000000000..57829f85bdf350c6a45cb20019423bb2edf05477 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/properties.js @@ -0,0 +1,753 @@ +// @flow + +import assert from 'assert'; +import {clone, extend, easeCubicInOut} from '../util/util'; +import * as interpolate from '../style-spec/util/interpolate'; +import {normalizePropertyExpression} from '../style-spec/expression'; +import Color from '../style-spec/util/color'; +import {register} from '../util/web_worker_transfer'; +import EvaluationParameters from './evaluation_parameters'; + +import type {CanonicalTileID} from '../source/tile_id'; +import type {StylePropertySpecification} from '../style-spec/style-spec'; +import type { + TransitionSpecification, + PropertyValueSpecification +} from '../style-spec/types'; + +import type { + Feature, + FeatureState, + StylePropertyExpression, + SourceExpression, + CompositeExpression +} from '../style-spec/expression'; + +type TimePoint = number; + +export type CrossFaded = { + to: T, + from: T +}; + +/** + * Implements a number of classes that define state and behavior for paint and layout properties, most + * importantly their respective evaluation chains: + * + * Transitionable paint property value + * → Transitioning paint property value + * → Possibly evaluated paint property value + * → Fully evaluated paint property value + * + * Layout property value + * → Possibly evaluated layout property value + * → Fully evaluated layout property value + * + * @module + * @private + */ + +/** + * Implementations of the `Property` interface: + * + * * Hold metadata about a property that's independent of any specific value: stuff like the type of the value, + * the default value, etc. This comes from the style specification JSON. + * * Define behavior that needs to be polymorphic across different properties: "possibly evaluating" + * an input value (see below), and interpolating between two possibly-evaluted values. + * + * The type `T` is the fully-evaluated value type (e.g. `number`, `string`, `Color`). + * The type `R` is the intermediate "possibly evaluated" value type. See below. + * + * There are two main implementations of the interface -- one for properties that allow data-driven values, + * and one for properties that don't. There are a few "special case" implementations as well: one for properties + * which cross-fade between two values rather than interpolating, one for `heatmap-color` and `line-gradient`, + * and one for `light-position`. + * + * @private + */ +export interface Property { + specification: StylePropertySpecification; + possiblyEvaluate(value: PropertyValue, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): R; + interpolate(a: R, b: R, t: number): R; +} + +/** + * `PropertyValue` represents the value part of a property key-value unit. It's used to represent both + * paint and layout property values, and regardless of whether or not their property supports data-driven + * expressions. + * + * `PropertyValue` stores the raw input value as seen in a style or a runtime styling API call, i.e. one of the + * following: + * + * * A constant value of the type appropriate for the property + * * A function which produces a value of that type (but functions are quasi-deprecated in favor of expressions) + * * An expression which produces a value of that type + * * "undefined"/"not present", in which case the property is assumed to take on its default value. + * + * In addition to storing the original input value, `PropertyValue` also stores a normalized representation, + * effectively treating functions as if they are expressions, and constant or default values as if they are + * (constant) expressions. + * + * @private + */ +export class PropertyValue { + property: Property; + value: PropertyValueSpecification | void; + expression: StylePropertyExpression; + + constructor(property: Property, value: PropertyValueSpecification | void) { + this.property = property; + this.value = value; + this.expression = normalizePropertyExpression(value === undefined ? property.specification.default : value, property.specification); + } + + isDataDriven(): boolean { + return this.expression.kind === 'source' || this.expression.kind === 'composite'; + } + + possiblyEvaluate(parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): R { + return this.property.possiblyEvaluate(this, parameters, canonical, availableImages); + } +} + +// ------- Transitionable ------- + +export type TransitionParameters = { + now: TimePoint, + transition: TransitionSpecification +}; + +/** + * Paint properties are _transitionable_: they can change in a fluid manner, interpolating or cross-fading between + * old and new value. The duration of the transition, and the delay before it begins, is configurable. + * + * `TransitionablePropertyValue` is a compositional class that stores both the property value and that transition + * configuration. + * + * A `TransitionablePropertyValue` can calculate the next step in the evaluation chain for paint property values: + * `TransitioningPropertyValue`. + * + * @private + */ +class TransitionablePropertyValue { + property: Property; + value: PropertyValue; + transition: TransitionSpecification | void; + + constructor(property: Property) { + this.property = property; + this.value = new PropertyValue(property, undefined); + } + + transitioned(parameters: TransitionParameters, + prior: TransitioningPropertyValue): TransitioningPropertyValue { + return new TransitioningPropertyValue(this.property, this.value, prior, // eslint-disable-line no-use-before-define + extend({}, parameters.transition, this.transition), parameters.now); + } + + untransitioned(): TransitioningPropertyValue { + return new TransitioningPropertyValue(this.property, this.value, null, {}, 0); // eslint-disable-line no-use-before-define + } +} + +/** + * A helper type: given an object type `Properties` whose values are each of type `Property`, it calculates + * an object type with the same keys and values of type `TransitionablePropertyValue`. + * + * @private + */ +type TransitionablePropertyValues + = $Exact<$ObjMap(p: Property) => TransitionablePropertyValue>> + +/** + * `Transitionable` stores a map of all (property name, `TransitionablePropertyValue`) pairs for paint properties of a + * given layer type. It can calculate the `TransitioningPropertyValue`s for all of them at once, producing a + * `Transitioning` instance for the same set of properties. + * + * @private + */ +export class Transitionable { + _properties: Properties; + _values: TransitionablePropertyValues; + + constructor(properties: Properties) { + this._properties = properties; + this._values = (Object.create(properties.defaultTransitionablePropertyValues): any); + } + + getValue(name: S): PropertyValueSpecification | void { + return clone(this._values[name].value.value); + } + + setValue(name: S, value: PropertyValueSpecification | void) { + if (!this._values.hasOwnProperty(name)) { + this._values[name] = new TransitionablePropertyValue(this._values[name].property); + } + // Note that we do not _remove_ an own property in the case where a value is being reset + // to the default: the transition might still be non-default. + this._values[name].value = new PropertyValue(this._values[name].property, value === null ? undefined : clone(value)); + } + + getTransition(name: S): TransitionSpecification | void { + return clone(this._values[name].transition); + } + + setTransition(name: S, value: TransitionSpecification | void) { + if (!this._values.hasOwnProperty(name)) { + this._values[name] = new TransitionablePropertyValue(this._values[name].property); + } + this._values[name].transition = clone(value) || undefined; + } + + serialize() { + const result: any = {}; + for (const property of Object.keys(this._values)) { + const value = this.getValue(property); + if (value !== undefined) { + result[property] = value; + } + + const transition = this.getTransition(property); + if (transition !== undefined) { + result[`${property}-transition`] = transition; + } + } + return result; + } + + transitioned(parameters: TransitionParameters, prior: Transitioning): Transitioning { + const result = new Transitioning(this._properties); // eslint-disable-line no-use-before-define + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].transitioned(parameters, prior._values[property]); + } + return result; + } + + untransitioned(): Transitioning { + const result = new Transitioning(this._properties); // eslint-disable-line no-use-before-define + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].untransitioned(); + } + return result; + } +} + +// ------- Transitioning ------- + +/** + * `TransitioningPropertyValue` implements the first of two intermediate steps in the evaluation chain of a paint + * property value. In this step, transitions between old and new values are handled: as long as the transition is in + * progress, `TransitioningPropertyValue` maintains a reference to the prior value, and interpolates between it and + * the new value based on the current time and the configured transition duration and delay. The product is the next + * step in the evaluation chain: the "possibly evaluated" result type `R`. See below for more on this concept. + * + * @private + */ +class TransitioningPropertyValue { + property: Property; + value: PropertyValue; + prior: ?TransitioningPropertyValue; + begin: TimePoint; + end: TimePoint; + + constructor(property: Property, + value: PropertyValue, + prior: ?TransitioningPropertyValue, + transition: TransitionSpecification, + now: TimePoint) { + this.property = property; + this.value = value; + this.begin = now + transition.delay || 0; + this.end = this.begin + transition.duration || 0; + if (property.specification.transition && (transition.delay || transition.duration)) { + this.prior = prior; + } + } + + possiblyEvaluate(parameters: EvaluationParameters, canonical: CanonicalTileID, availableImages: Array): R { + const now = parameters.now || 0; + const finalValue = this.value.possiblyEvaluate(parameters, canonical, availableImages); + const prior = this.prior; + if (!prior) { + // No prior value. + return finalValue; + } else if (now > this.end) { + // Transition from prior value is now complete. + this.prior = null; + return finalValue; + } else if (this.value.isDataDriven()) { + // Transitions to data-driven properties are not supported. + // We snap immediately to the data-driven value so that, when we perform layout, + // we see the data-driven function and can use it to populate vertex buffers. + this.prior = null; + return finalValue; + } else if (now < this.begin) { + // Transition hasn't started yet. + return prior.possiblyEvaluate(parameters, canonical, availableImages); + } else { + // Interpolate between recursively-calculated prior value and final. + const t = (now - this.begin) / (this.end - this.begin); + return this.property.interpolate(prior.possiblyEvaluate(parameters, canonical, availableImages), finalValue, easeCubicInOut(t)); + } + } +} + +/** + * A helper type: given an object type `Properties` whose values are each of type `Property`, it calculates + * an object type with the same keys and values of type `TransitioningPropertyValue`. + * + * @private + */ +type TransitioningPropertyValues + = $Exact<$ObjMap(p: Property) => TransitioningPropertyValue>> + +/** + * `Transitioning` stores a map of all (property name, `TransitioningPropertyValue`) pairs for paint properties of a + * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a + * `PossiblyEvaluated` instance for the same set of properties. + * + * @private + */ +export class Transitioning { + _properties: Properties; + _values: TransitioningPropertyValues; + + constructor(properties: Properties) { + this._properties = properties; + this._values = (Object.create(properties.defaultTransitioningPropertyValues): any); + } + + possiblyEvaluate(parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): PossiblyEvaluated { + const result = new PossiblyEvaluated(this._properties); // eslint-disable-line no-use-before-define + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages); + } + return result; + } + + hasTransition() { + for (const property of Object.keys(this._values)) { + if (this._values[property].prior) { + return true; + } + } + return false; + } +} + +// ------- Layout ------- + +/** + * A helper type: given an object type `Properties` whose values are each of type `Property`, it calculates + * an object type with the same keys and values of type `PropertyValue`. + * + * @private + */ +type PropertyValues + = $Exact<$ObjMap(p: Property) => PropertyValue>> + +/** + * Because layout properties are not transitionable, they have a simpler representation and evaluation chain than + * paint properties: `PropertyValue`s are possibly evaluated, producing possibly evaluated values, which are then + * fully evaluated. + * + * `Layout` stores a map of all (property name, `PropertyValue`) pairs for layout properties of a + * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a + * `PossiblyEvaluated` instance for the same set of properties. + * + * @private + */ +export class Layout { + _properties: Properties; + _values: PropertyValues; + + constructor(properties: Properties) { + this._properties = properties; + this._values = (Object.create(properties.defaultPropertyValues): any); + } + + getValue(name: S) { + return clone(this._values[name].value); + } + + setValue(name: S, value: *) { + this._values[name] = new PropertyValue(this._values[name].property, value === null ? undefined : clone(value)); + } + + serialize() { + const result: any = {}; + for (const property of Object.keys(this._values)) { + const value = this.getValue(property); + if (value !== undefined) { + result[property] = value; + } + } + return result; + } + + possiblyEvaluate(parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): PossiblyEvaluated { + const result = new PossiblyEvaluated(this._properties); // eslint-disable-line no-use-before-define + for (const property of Object.keys(this._values)) { + result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages); + } + return result; + } +} + +// ------- PossiblyEvaluated ------- + +/** + * "Possibly evaluated value" is an intermediate stage in the evaluation chain for both paint and layout property + * values. The purpose of this stage is to optimize away unnecessary recalculations for data-driven properties. Code + * which uses data-driven property values must assume that the value is dependent on feature data, and request that it + * be evaluated for each feature. But when that property value is in fact a constant or camera function, the calculation + * will not actually depend on the feature, and we can benefit from returning the prior result of having done the + * evaluation once, ahead of time, in an intermediate step whose inputs are just the value and "global" parameters + * such as current zoom level. + * + * `PossiblyEvaluatedValue` represents the three possible outcomes of this step: if the input value was a constant or + * camera expression, then the "possibly evaluated" result is a constant value. Otherwise, the input value was either + * a source or composite expression, and we must defer final evaluation until supplied a feature. We separate + * the source and composite cases because they are handled differently when generating GL attributes, buffers, and + * uniforms. + * + * Note that `PossiblyEvaluatedValue` (and `PossiblyEvaluatedPropertyValue`, below) are _not_ used for properties that + * do not allow data-driven values. For such properties, we know that the "possibly evaluated" result is always a constant + * scalar value. See below. + * + * @private + */ +type PossiblyEvaluatedValue = + | {kind: 'constant', value: T} + | SourceExpression + | CompositeExpression; + +/** + * `PossiblyEvaluatedPropertyValue` is used for data-driven paint and layout property values. It holds a + * `PossiblyEvaluatedValue` and the `GlobalProperties` that were used to generate it. You're not allowed to supply + * a different set of `GlobalProperties` when performing the final evaluation because they would be ignored in the + * case where the input value was a constant or camera function. + * + * @private + */ +export class PossiblyEvaluatedPropertyValue { + property: DataDrivenProperty; + value: PossiblyEvaluatedValue; + parameters: EvaluationParameters; + + constructor(property: DataDrivenProperty, value: PossiblyEvaluatedValue, parameters: EvaluationParameters) { + this.property = property; + this.value = value; + this.parameters = parameters; + } + + isConstant(): boolean { + return this.value.kind === 'constant'; + } + + constantOr(value: T): T { + if (this.value.kind === 'constant') { + return this.value.value; + } else { + return value; + } + } + + evaluate(feature: Feature, featureState: FeatureState, canonical?: CanonicalTileID, availableImages?: Array): T { + return this.property.evaluate(this.value, this.parameters, feature, featureState, canonical, availableImages); + } +} + +/** + * A helper type: given an object type `Properties` whose values are each of type `Property`, it calculates + * an object type with the same keys, and values of type `R`. + * + * For properties that don't allow data-driven values, `R` is a scalar type such as `number`, `string`, or `Color`. + * For data-driven properties, it is `PossiblyEvaluatedPropertyValue`. Critically, the type definitions are set up + * in a way that allows flow to know which of these two cases applies for any given property name, and if you attempt + * to use a `PossiblyEvaluatedPropertyValue` as if it was a scalar, or vice versa, you will get a type error. (However, + * there's at least one case in which flow fails to produce a type error that you should be aware of: in a context such + * as `layer.paint.get('foo-opacity') === 0`, if `foo-opacity` is data-driven, than the left-hand side is of type + * `PossiblyEvaluatedPropertyValue`, but flow will not complain about comparing this to a number using `===`. + * See https://github.com/facebook/flow/issues/2359.) + * + * There's also a third, special case possiblity for `R`: for cross-faded properties, it's `?CrossFaded`. + * + * @private + */ +type PossiblyEvaluatedPropertyValues + = $Exact<$ObjMap(p: Property) => R>> + +/** + * `PossiblyEvaluated` stores a map of all (property name, `R`) pairs for paint or layout properties of a + * given layer type. + * @private + */ +export class PossiblyEvaluated { + _properties: Properties; + _values: PossiblyEvaluatedPropertyValues; + + constructor(properties: Properties) { + this._properties = properties; + this._values = (Object.create(properties.defaultPossiblyEvaluatedValues): any); + } + + get(name: S): $ElementType, S> { + return this._values[name]; + } +} + +/** + * An implementation of `Property` for properties that do not permit data-driven (source or composite) expressions. + * This restriction allows us to declare statically that the result of possibly evaluating this kind of property + * is in fact always the scalar type `T`, and can be used without further evaluating the value on a per-feature basis. + * + * @private + */ +export class DataConstantProperty implements Property { + specification: StylePropertySpecification; + + constructor(specification: StylePropertySpecification) { + this.specification = specification; + } + + possiblyEvaluate(value: PropertyValue, parameters: EvaluationParameters): T { + assert(!value.isDataDriven()); + return value.expression.evaluate(parameters); + } + + interpolate(a: T, b: T, t: number): T { + const interp: ?(a: T, b: T, t: number) => T = (interpolate: any)[this.specification.type]; + if (interp) { + return interp(a, b, t); + } else { + return a; + } + } +} + +/** + * An implementation of `Property` for properties that permit data-driven (source or composite) expressions. + * The result of possibly evaluating this kind of property is `PossiblyEvaluatedPropertyValue`; obtaining + * a scalar value `T` requires further evaluation on a per-feature basis. + * + * @private + */ +export class DataDrivenProperty implements Property> { + specification: StylePropertySpecification; + overrides: ?Object; + + constructor(specification: StylePropertySpecification, overrides?: Object) { + this.specification = specification; + this.overrides = overrides; + } + + possiblyEvaluate(value: PropertyValue>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): PossiblyEvaluatedPropertyValue { + if (value.expression.kind === 'constant' || value.expression.kind === 'camera') { + return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: value.expression.evaluate(parameters, (null: any), {}, canonical, availableImages)}, parameters); + } else { + return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters); + } + } + + interpolate(a: PossiblyEvaluatedPropertyValue, + b: PossiblyEvaluatedPropertyValue, + t: number): PossiblyEvaluatedPropertyValue { + // If either possibly-evaluated value is non-constant, give up: we aren't able to interpolate data-driven values. + if (a.value.kind !== 'constant' || b.value.kind !== 'constant') { + return a; + } + + // Special case hack solely for fill-outline-color. The undefined value is subsequently handled in + // FillStyleLayer#recalculate, which sets fill-outline-color to the fill-color value if the former + // is a PossiblyEvaluatedPropertyValue containing a constant undefined value. In addition to the + // return value here, the other source of a PossiblyEvaluatedPropertyValue containing a constant + // undefined value is the "default value" for fill-outline-color held in + // `Properties#defaultPossiblyEvaluatedValues`, which serves as the prototype of + // `PossiblyEvaluated#_values`. + if (a.value.value === undefined || b.value.value === undefined) { + return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: (undefined: any)}, a.parameters); + } + + const interp: ?(a: T, b: T, t: number) => T = (interpolate: any)[this.specification.type]; + if (interp) { + return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: interp(a.value.value, b.value.value, t)}, a.parameters); + } else { + return a; + } + } + + evaluate(value: PossiblyEvaluatedValue, parameters: EvaluationParameters, feature: Feature, featureState: FeatureState, canonical?: CanonicalTileID, availableImages?: Array): T { + if (value.kind === 'constant') { + return value.value; + } else { + return value.evaluate(parameters, feature, featureState, canonical, availableImages); + } + } +} + +/** + * An implementation of `Property` for data driven `line-pattern` which are transitioned by cross-fading + * rather than interpolation. + * + * @private + */ + +export class CrossFadedDataDrivenProperty extends DataDrivenProperty> { + + possiblyEvaluate(value: PropertyValue, PossiblyEvaluatedPropertyValue>>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): PossiblyEvaluatedPropertyValue> { + if (value.value === undefined) { + return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: undefined}, parameters); + } else if (value.expression.kind === 'constant') { + const evaluatedValue = value.expression.evaluate(parameters, (null: any), {}, canonical, availableImages); + const isImageExpression = value.property.specification.type === 'resolvedImage'; + const constantValue = isImageExpression && typeof evaluatedValue !== 'string' ? evaluatedValue.name : evaluatedValue; + const constant = this._calculate(constantValue, constantValue, constantValue, parameters); + return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: constant}, parameters); + } else if (value.expression.kind === 'camera') { + const cameraVal = this._calculate( + value.expression.evaluate({zoom: parameters.zoom - 1.0}), + value.expression.evaluate({zoom: parameters.zoom}), + value.expression.evaluate({zoom: parameters.zoom + 1.0}), + parameters); + return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: cameraVal}, parameters); + } else { + // source or composite expression + return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters); + } + } + + evaluate(value: PossiblyEvaluatedValue>, globals: EvaluationParameters, feature: Feature, featureState: FeatureState, canonical?: CanonicalTileID, availableImages?: Array): ?CrossFaded { + if (value.kind === 'source') { + const constant = value.evaluate(globals, feature, featureState, canonical, availableImages); + return this._calculate(constant, constant, constant, globals); + } else if (value.kind === 'composite') { + return this._calculate( + value.evaluate({zoom: Math.floor(globals.zoom) - 1.0}, feature, featureState), + value.evaluate({zoom: Math.floor(globals.zoom)}, feature, featureState), + value.evaluate({zoom: Math.floor(globals.zoom) + 1.0}, feature, featureState), + globals); + } else { + return value.value; + } + } + + _calculate(min: T, mid: T, max: T, parameters: EvaluationParameters): CrossFaded { + const z = parameters.zoom; + return z > parameters.zoomHistory.lastIntegerZoom ? {from: min, to: mid} : {from: max, to: mid}; + } + + interpolate(a: PossiblyEvaluatedPropertyValue>): PossiblyEvaluatedPropertyValue> { + return a; + } +} +/** + * An implementation of `Property` for `*-pattern` and `line-dasharray`, which are transitioned by cross-fading + * rather than interpolation. + * + * @private + */ +export class CrossFadedProperty implements Property> { + specification: StylePropertySpecification; + + constructor(specification: StylePropertySpecification) { + this.specification = specification; + } + + possiblyEvaluate(value: PropertyValue>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): ?CrossFaded { + if (value.value === undefined) { + return undefined; + } else if (value.expression.kind === 'constant') { + const constant = value.expression.evaluate(parameters, (null: any), {}, canonical, availableImages); + return this._calculate(constant, constant, constant, parameters); + } else { + assert(!value.isDataDriven()); + return this._calculate( + value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom - 1.0), parameters)), + value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom), parameters)), + value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom + 1.0), parameters)), + parameters); + } + } + + _calculate(min: T, mid: T, max: T, parameters: EvaluationParameters): ?CrossFaded { + const z = parameters.zoom; + return z > parameters.zoomHistory.lastIntegerZoom ? {from: min, to: mid} : {from: max, to: mid}; + } + + interpolate(a: ?CrossFaded): ?CrossFaded { + return a; + } +} + +/** + * An implementation of `Property` for `heatmap-color` and `line-gradient`. Interpolation is a no-op, and + * evaluation returns a boolean value in order to indicate its presence, but the real + * evaluation happens in StyleLayer classes. + * + * @private + */ + +export class ColorRampProperty implements Property { + specification: StylePropertySpecification; + + constructor(specification: StylePropertySpecification) { + this.specification = specification; + } + + possiblyEvaluate(value: PropertyValue, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): boolean { + return !!value.expression.evaluate(parameters, (null: any), {}, canonical, availableImages); + } + + interpolate(): boolean { return false; } +} + +/** + * `Properties` holds objects containing default values for the layout or paint property set of a given + * layer type. These objects are immutable, and they are used as the prototypes for the `_values` members of + * `Transitionable`, `Transitioning`, `Layout`, and `PossiblyEvaluated`. This allows these classes to avoid + * doing work in the common case where a property has no explicit value set and should be considered to take + * on the default value: using `for (const property of Object.keys(this._values))`, they can iterate over + * only the _own_ properties of `_values`, skipping repeated calculation of transitions and possible/final + * evaluations for defaults, the result of which will always be the same. + * + * @private + */ +export class Properties { + properties: Props; + defaultPropertyValues: PropertyValues; + defaultTransitionablePropertyValues: TransitionablePropertyValues; + defaultTransitioningPropertyValues: TransitioningPropertyValues; + defaultPossiblyEvaluatedValues: PossiblyEvaluatedPropertyValues; + overridableProperties: Array; + + constructor(properties: Props) { + this.properties = properties; + this.defaultPropertyValues = ({}: any); + this.defaultTransitionablePropertyValues = ({}: any); + this.defaultTransitioningPropertyValues = ({}: any); + this.defaultPossiblyEvaluatedValues = ({}: any); + this.overridableProperties = ([]: any); + + for (const property in properties) { + const prop = properties[property]; + if (prop.specification.overridable) { + this.overridableProperties.push(property); + } + const defaultPropertyValue = this.defaultPropertyValues[property] = + new PropertyValue(prop, undefined); + const defaultTransitionablePropertyValue = this.defaultTransitionablePropertyValues[property] = + new TransitionablePropertyValue(prop); + this.defaultTransitioningPropertyValues[property] = + defaultTransitionablePropertyValue.untransitioned(); + this.defaultPossiblyEvaluatedValues[property] = + defaultPropertyValue.possiblyEvaluate(({}: any)); + } + } +} + +register('DataDrivenProperty', DataDrivenProperty); +register('DataConstantProperty', DataConstantProperty); +register('CrossFadedDataDrivenProperty', CrossFadedDataDrivenProperty); +register('CrossFadedProperty', CrossFadedProperty); +register('ColorRampProperty', ColorRampProperty); diff --git a/node_modules/mapbox-gl/src/style/query_utils.js b/node_modules/mapbox-gl/src/style/query_utils.js new file mode 100644 index 0000000000000000000000000000000000000000..dc0f6754a86dc4fde25771054adebab5d986c427 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/query_utils.js @@ -0,0 +1,43 @@ +// @flow + +import Point from '@mapbox/point-geometry'; + +import type {PossiblyEvaluatedPropertyValue} from "./properties"; +import type StyleLayer from '../style/style_layer'; +import type CircleBucket from '../data/bucket/circle_bucket'; +import type LineBucket from '../data/bucket/line_bucket'; + +export function getMaximumPaintValue(property: string, layer: StyleLayer, bucket: CircleBucket<*> | LineBucket): number { + const value = ((layer.paint: any).get(property): PossiblyEvaluatedPropertyValue).value; + if (value.kind === 'constant') { + return value.value; + } else { + return bucket.programConfigurations.get(layer.id).getMaxValue(property); + } +} + +export function translateDistance(translate: [number, number]) { + return Math.sqrt(translate[0] * translate[0] + translate[1] * translate[1]); +} + +export function translate(queryGeometry: Array, + translate: [number, number], + translateAnchor: 'viewport' | 'map', + bearing: number, + pixelsToTileUnits: number) { + if (!translate[0] && !translate[1]) { + return queryGeometry; + } + const pt = Point.convert(translate)._mult(pixelsToTileUnits); + + if (translateAnchor === "viewport") { + pt._rotate(-bearing); + } + + const translated = []; + for (let i = 0; i < queryGeometry.length; i++) { + const point = queryGeometry[i]; + translated.push(point.sub(pt)); + } + return translated; +} diff --git a/node_modules/mapbox-gl/src/style/style.js b/node_modules/mapbox-gl/src/style/style.js new file mode 100644 index 0000000000000000000000000000000000000000..70523941871c63f2d3a904106a0f73e8c5aa90ed --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style.js @@ -0,0 +1,1374 @@ +// @flow + +import assert from 'assert'; + +import {Event, ErrorEvent, Evented} from '../util/evented'; +import StyleLayer from './style_layer'; +import createStyleLayer from './create_style_layer'; +import loadSprite from './load_sprite'; +import ImageManager from '../render/image_manager'; +import GlyphManager from '../render/glyph_manager'; +import Light from './light'; +import LineAtlas from '../render/line_atlas'; +import {pick, clone, extend, deepEqual, filterObject, mapObject} from '../util/util'; +import {getJSON, getReferrer, makeRequest, ResourceType} from '../util/ajax'; +import {isMapboxURL} from '../util/mapbox'; +import browser from '../util/browser'; +import Dispatcher from '../util/dispatcher'; +import {validateStyle, emitValidationErrors as _emitValidationErrors} from './validate_style'; +import { + getType as getSourceType, + setType as setSourceType, + type SourceClass +} from '../source/source'; +import {queryRenderedFeatures, queryRenderedSymbols, querySourceFeatures} from '../source/query_features'; +import SourceCache from '../source/source_cache'; +import GeoJSONSource from '../source/geojson_source'; +import styleSpec from '../style-spec/reference/latest'; +import getWorkerPool from '../util/global_worker_pool'; +import deref from '../style-spec/deref'; +import emptyStyle from '../style-spec/empty'; +import diffStyles, {operations as diffOperations} from '../style-spec/diff'; +import { + registerForPluginStateChange, + evented as rtlTextPluginEvented, + triggerPluginCompletionEvent +} from '../source/rtl_text_plugin'; +import PauseablePlacement from './pauseable_placement'; +import ZoomHistory from './zoom_history'; +import CrossTileSymbolIndex from '../symbol/cross_tile_symbol_index'; +import {validateCustomStyleLayer} from './style_layer/custom_style_layer'; + +// We're skipping validation errors with the `source.canvas` identifier in order +// to continue to allow canvas sources to be added at runtime/updated in +// smart setStyle (see https://github.com/mapbox/mapbox-gl-js/pull/6424): +const emitValidationErrors = (evented: Evented, errors: ?$ReadOnlyArray<{message: string, identifier?: string}>) => + _emitValidationErrors(evented, errors && errors.filter(error => error.identifier !== 'source.canvas')); + +import type Map from '../ui/map'; +import type Transform from '../geo/transform'; +import type {StyleImage} from './style_image'; +import type {StyleGlyph} from './style_glyph'; +import type {Callback} from '../types/callback'; +import type EvaluationParameters from './evaluation_parameters'; +import type {Placement} from '../symbol/placement'; +import type {Cancelable} from '../types/cancelable'; +import type {RequestParameters, ResponseCallback} from '../util/ajax'; +import type {GeoJSON} from '@mapbox/geojson-types'; +import type { + LayerSpecification, + FilterSpecification, + StyleSpecification, + LightSpecification, + SourceSpecification +} from '../style-spec/types'; +import type {CustomLayerInterface} from './style_layer/custom_style_layer'; +import type {Validator} from './validate_style'; +import type {OverscaledTileID} from '../source/tile_id'; + +const supportedDiffOperations = pick(diffOperations, [ + 'addLayer', + 'removeLayer', + 'setPaintProperty', + 'setLayoutProperty', + 'setFilter', + 'addSource', + 'removeSource', + 'setLayerZoomRange', + 'setLight', + 'setTransition', + 'setGeoJSONSourceData' + // 'setGlyphs', + // 'setSprite', +]); + +const ignoredDiffOperations = pick(diffOperations, [ + 'setCenter', + 'setZoom', + 'setBearing', + 'setPitch' +]); + +const empty = emptyStyle(); + +export type StyleOptions = { + validate?: boolean, + localIdeographFontFamily?: string +}; + +export type StyleSetterOptions = { + validate?: boolean +}; +/** + * @private + */ +class Style extends Evented { + map: Map; + stylesheet: StyleSpecification; + dispatcher: Dispatcher; + imageManager: ImageManager; + glyphManager: GlyphManager; + lineAtlas: LineAtlas; + light: Light; + + _request: ?Cancelable; + _spriteRequest: ?Cancelable; + _layers: {[_: string]: StyleLayer}; + _serializedLayers: {[_: string]: Object}; + _order: Array; + sourceCaches: {[_: string]: SourceCache}; + zoomHistory: ZoomHistory; + _loaded: boolean; + _rtlTextPluginCallback: Function; + _changed: boolean; + _updatedSources: {[_: string]: 'clear' | 'reload'}; + _updatedLayers: {[_: string]: true}; + _removedLayers: {[_: string]: StyleLayer}; + _changedImages: {[_: string]: true}; + _updatedPaintProps: {[layer: string]: true}; + _layerOrderChanged: boolean; + _availableImages: Array; + + crossTileSymbolIndex: CrossTileSymbolIndex; + pauseablePlacement: PauseablePlacement; + placement: Placement; + z: number; + + // exposed to allow stubbing by unit tests + static getSourceType: typeof getSourceType; + static setSourceType: typeof setSourceType; + static registerForPluginStateChange: typeof registerForPluginStateChange; + + constructor(map: Map, options: StyleOptions = {}) { + super(); + + this.map = map; + this.dispatcher = new Dispatcher(getWorkerPool(), this); + this.imageManager = new ImageManager(); + this.imageManager.setEventedParent(this); + this.glyphManager = new GlyphManager(map._requestManager, options.localIdeographFontFamily); + this.lineAtlas = new LineAtlas(256, 512); + this.crossTileSymbolIndex = new CrossTileSymbolIndex(); + + this._layers = {}; + this._serializedLayers = {}; + this._order = []; + this.sourceCaches = {}; + this.zoomHistory = new ZoomHistory(); + this._loaded = false; + this._availableImages = []; + + this._resetUpdates(); + + this.dispatcher.broadcast('setReferrer', getReferrer()); + + const self = this; + this._rtlTextPluginCallback = Style.registerForPluginStateChange((event) => { + const state = { + pluginStatus: event.pluginStatus, + pluginURL: event.pluginURL + }; + self.dispatcher.broadcast('syncRTLPluginState', state, (err, results) => { + triggerPluginCompletionEvent(err); + if (results) { + const allComplete = results.every((elem) => elem); + if (allComplete) { + for (const id in self.sourceCaches) { + self.sourceCaches[id].reload(); // Should be a no-op if the plugin loads before any tiles load + } + } + } + + }); + }); + + this.on('data', (event) => { + if (event.dataType !== 'source' || event.sourceDataType !== 'metadata') { + return; + } + + const sourceCache = this.sourceCaches[event.sourceId]; + if (!sourceCache) { + return; + } + + const source = sourceCache.getSource(); + if (!source || !source.vectorLayerIds) { + return; + } + + for (const layerId in this._layers) { + const layer = this._layers[layerId]; + if (layer.source === source.id) { + this._validateLayer(layer); + } + } + }); + } + + loadURL(url: string, options: { + validate?: boolean, + accessToken?: string + } = {}) { + this.fire(new Event('dataloading', {dataType: 'style'})); + + const validate = typeof options.validate === 'boolean' ? + options.validate : !isMapboxURL(url); + + url = this.map._requestManager.normalizeStyleURL(url, options.accessToken); + const request = this.map._requestManager.transformRequest(url, ResourceType.Style); + this._request = getJSON(request, (error: ?Error, json: ?Object) => { + this._request = null; + if (error) { + this.fire(new ErrorEvent(error)); + } else if (json) { + this._load(json, validate); + } + }); + } + + loadJSON(json: StyleSpecification, options: StyleSetterOptions = {}) { + this.fire(new Event('dataloading', {dataType: 'style'})); + + this._request = browser.frame(() => { + this._request = null; + this._load(json, options.validate !== false); + }); + } + + loadEmpty() { + this.fire(new Event('dataloading', {dataType: 'style'})); + this._load(empty, false); + } + + _load(json: StyleSpecification, validate: boolean) { + if (validate && emitValidationErrors(this, validateStyle(json))) { + return; + } + + this._loaded = true; + this.stylesheet = json; + + for (const id in json.sources) { + this.addSource(id, json.sources[id], {validate: false}); + } + + if (json.sprite) { + this._loadSprite(json.sprite); + } else { + this.imageManager.setLoaded(true); + } + + this.glyphManager.setURL(json.glyphs); + + const layers = deref(this.stylesheet.layers); + + this._order = layers.map((layer) => layer.id); + + this._layers = {}; + this._serializedLayers = {}; + for (let layer of layers) { + layer = createStyleLayer(layer); + layer.setEventedParent(this, {layer: {id: layer.id}}); + this._layers[layer.id] = layer; + this._serializedLayers[layer.id] = layer.serialize(); + } + this.dispatcher.broadcast('setLayers', this._serializeLayers(this._order)); + + this.light = new Light(this.stylesheet.light); + + this.fire(new Event('data', {dataType: 'style'})); + this.fire(new Event('style.load')); + } + + _loadSprite(url: string) { + this._spriteRequest = loadSprite(url, this.map._requestManager, (err, images) => { + this._spriteRequest = null; + if (err) { + this.fire(new ErrorEvent(err)); + } else if (images) { + for (const id in images) { + this.imageManager.addImage(id, images[id]); + } + } + + this.imageManager.setLoaded(true); + this._availableImages = this.imageManager.listImages(); + this.dispatcher.broadcast('setImages', this._availableImages); + this.fire(new Event('data', {dataType: 'style'})); + }); + } + + _validateLayer(layer: StyleLayer) { + const sourceCache = this.sourceCaches[layer.source]; + if (!sourceCache) { + return; + } + + const sourceLayer = layer.sourceLayer; + if (!sourceLayer) { + return; + } + + const source = sourceCache.getSource(); + if (source.type === 'geojson' || (source.vectorLayerIds && source.vectorLayerIds.indexOf(sourceLayer) === -1)) { + this.fire(new ErrorEvent(new Error( + `Source layer "${sourceLayer}" ` + + `does not exist on source "${source.id}" ` + + `as specified by style layer "${layer.id}"` + ))); + } + } + + loaded() { + if (!this._loaded) + return false; + + if (Object.keys(this._updatedSources).length) + return false; + + for (const id in this.sourceCaches) + if (!this.sourceCaches[id].loaded()) + return false; + + if (!this.imageManager.isLoaded()) + return false; + + return true; + } + + _serializeLayers(ids: Array): Array { + const serializedLayers = []; + for (const id of ids) { + const layer = this._layers[id]; + if (layer.type !== 'custom') { + serializedLayers.push(layer.serialize()); + } + } + return serializedLayers; + } + + hasTransitions() { + if (this.light && this.light.hasTransition()) { + return true; + } + + for (const id in this.sourceCaches) { + if (this.sourceCaches[id].hasTransition()) { + return true; + } + } + + for (const id in this._layers) { + if (this._layers[id].hasTransition()) { + return true; + } + } + + return false; + } + + _checkLoaded() { + if (!this._loaded) { + throw new Error('Style is not done loading'); + } + } + + /** + * Apply queued style updates in a batch and recalculate zoom-dependent paint properties. + * @private + */ + update(parameters: EvaluationParameters) { + if (!this._loaded) { + return; + } + + const changed = this._changed; + if (this._changed) { + const updatedIds = Object.keys(this._updatedLayers); + const removedIds = Object.keys(this._removedLayers); + + if (updatedIds.length || removedIds.length) { + this._updateWorkerLayers(updatedIds, removedIds); + } + for (const id in this._updatedSources) { + const action = this._updatedSources[id]; + assert(action === 'reload' || action === 'clear'); + if (action === 'reload') { + this._reloadSource(id); + } else if (action === 'clear') { + this._clearSource(id); + } + } + + this._updateTilesForChangedImages(); + + for (const id in this._updatedPaintProps) { + this._layers[id].updateTransitions(parameters); + } + + this.light.updateTransitions(parameters); + + this._resetUpdates(); + } + + const sourcesUsedBefore = {}; + + for (const sourceId in this.sourceCaches) { + const sourceCache = this.sourceCaches[sourceId]; + sourcesUsedBefore[sourceId] = sourceCache.used; + sourceCache.used = false; + } + + for (const layerId of this._order) { + const layer = this._layers[layerId]; + + layer.recalculate(parameters, this._availableImages); + if (!layer.isHidden(parameters.zoom) && layer.source) { + this.sourceCaches[layer.source].used = true; + } + } + + for (const sourceId in sourcesUsedBefore) { + const sourceCache = this.sourceCaches[sourceId]; + if (sourcesUsedBefore[sourceId] !== sourceCache.used) { + sourceCache.fire(new Event('data', {sourceDataType: 'visibility', dataType:'source', sourceId})); + } + } + + this.light.recalculate(parameters); + this.z = parameters.zoom; + + if (changed) { + this.fire(new Event('data', {dataType: 'style'})); + } + + } + + /* + * Apply any queued image changes. + */ + _updateTilesForChangedImages() { + const changedImages = Object.keys(this._changedImages); + if (changedImages.length) { + for (const name in this.sourceCaches) { + this.sourceCaches[name].reloadTilesForDependencies(['icons', 'patterns'], changedImages); + } + this._changedImages = {}; + } + } + + _updateWorkerLayers(updatedIds: Array, removedIds: Array) { + this.dispatcher.broadcast('updateLayers', { + layers: this._serializeLayers(updatedIds), + removedIds + }); + } + + _resetUpdates() { + this._changed = false; + + this._updatedLayers = {}; + this._removedLayers = {}; + + this._updatedSources = {}; + this._updatedPaintProps = {}; + + this._changedImages = {}; + } + + /** + * Update this style's state to match the given style JSON, performing only + * the necessary mutations. + * + * May throw an Error ('Unimplemented: METHOD') if the mapbox-gl-style-spec + * diff algorithm produces an operation that is not supported. + * + * @returns {boolean} true if any changes were made; false otherwise + * @private + */ + setState(nextState: StyleSpecification) { + this._checkLoaded(); + + if (emitValidationErrors(this, validateStyle(nextState))) return false; + + nextState = clone(nextState); + nextState.layers = deref(nextState.layers); + + const changes = diffStyles(this.serialize(), nextState) + .filter(op => !(op.command in ignoredDiffOperations)); + + if (changes.length === 0) { + return false; + } + + const unimplementedOps = changes.filter(op => !(op.command in supportedDiffOperations)); + if (unimplementedOps.length > 0) { + throw new Error(`Unimplemented: ${unimplementedOps.map(op => op.command).join(', ')}.`); + } + + changes.forEach((op) => { + if (op.command === 'setTransition') { + // `transition` is always read directly off of + // `this.stylesheet`, which we update below + return; + } + (this: any)[op.command].apply(this, op.args); + }); + + this.stylesheet = nextState; + + return true; + } + + addImage(id: string, image: StyleImage) { + if (this.getImage(id)) { + return this.fire(new ErrorEvent(new Error('An image with this name already exists.'))); + } + this.imageManager.addImage(id, image); + this._afterImageUpdated(id); + } + + updateImage(id: string, image: StyleImage) { + this.imageManager.updateImage(id, image); + } + + getImage(id: string): ?StyleImage { + return this.imageManager.getImage(id); + } + + removeImage(id: string) { + if (!this.getImage(id)) { + return this.fire(new ErrorEvent(new Error('No image with this name exists.'))); + } + this.imageManager.removeImage(id); + this._afterImageUpdated(id); + } + + _afterImageUpdated(id: string) { + this._availableImages = this.imageManager.listImages(); + this._changedImages[id] = true; + this._changed = true; + this.dispatcher.broadcast('setImages', this._availableImages); + this.fire(new Event('data', {dataType: 'style'})); + } + + listImages() { + this._checkLoaded(); + + return this.imageManager.listImages(); + } + + addSource(id: string, source: SourceSpecification, options: StyleSetterOptions = {}) { + this._checkLoaded(); + + if (this.sourceCaches[id] !== undefined) { + throw new Error('There is already a source with this ID'); + } + + if (!source.type) { + throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(source).join(', ')}.`); + } + + const builtIns = ['vector', 'raster', 'geojson', 'video', 'image']; + const shouldValidate = builtIns.indexOf(source.type) >= 0; + if (shouldValidate && this._validate(validateStyle.source, `sources.${id}`, source, null, options)) return; + + if (this.map && this.map._collectResourceTiming) (source: any).collectResourceTiming = true; + const sourceCache = this.sourceCaches[id] = new SourceCache(id, source, this.dispatcher); + sourceCache.style = this; + sourceCache.setEventedParent(this, () => ({ + isSourceLoaded: this.loaded(), + source: sourceCache.serialize(), + sourceId: id + })); + + sourceCache.onAdd(this.map); + this._changed = true; + } + + /** + * Remove a source from this stylesheet, given its id. + * @param {string} id id of the source to remove + * @throws {Error} if no source is found with the given ID + * @returns {Map} The {@link Map} object. + */ + removeSource(id: string) { + this._checkLoaded(); + + if (this.sourceCaches[id] === undefined) { + throw new Error('There is no source with this ID'); + } + for (const layerId in this._layers) { + if (this._layers[layerId].source === id) { + return this.fire(new ErrorEvent(new Error(`Source "${id}" cannot be removed while layer "${layerId}" is using it.`))); + } + } + + const sourceCache = this.sourceCaches[id]; + delete this.sourceCaches[id]; + delete this._updatedSources[id]; + sourceCache.fire(new Event('data', {sourceDataType: 'metadata', dataType:'source', sourceId: id})); + sourceCache.setEventedParent(null); + sourceCache.clearTiles(); + + if (sourceCache.onRemove) sourceCache.onRemove(this.map); + this._changed = true; + } + + /** + * Set the data of a GeoJSON source, given its id. + * @param {string} id id of the source + * @param {GeoJSON|string} data GeoJSON source + */ + setGeoJSONSourceData(id: string, data: GeoJSON | string) { + this._checkLoaded(); + + assert(this.sourceCaches[id] !== undefined, 'There is no source with this ID'); + const geojsonSource: GeoJSONSource = (this.sourceCaches[id].getSource(): any); + assert(geojsonSource.type === 'geojson'); + + geojsonSource.setData(data); + this._changed = true; + } + + /** + * Get a source by id. + * @param {string} id id of the desired source + * @returns {Object} source + */ + getSource(id: string): Object { + return this.sourceCaches[id] && this.sourceCaches[id].getSource(); + } + + /** + * Add a layer to the map style. The layer will be inserted before the layer with + * ID `before`, or appended if `before` is omitted. + * @param {Object | CustomLayerInterface} layerObject The style layer to add. + * @param {string} [before] ID of an existing layer to insert before + * @param {Object} options Style setter options. + * @returns {Map} The {@link Map} object. + */ + addLayer(layerObject: LayerSpecification | CustomLayerInterface, before?: string, options: StyleSetterOptions = {}) { + this._checkLoaded(); + + const id = layerObject.id; + + if (this.getLayer(id)) { + this.fire(new ErrorEvent(new Error(`Layer with id "${id}" already exists on this map`))); + return; + } + + let layer; + if (layerObject.type === 'custom') { + + if (emitValidationErrors(this, validateCustomStyleLayer(layerObject))) return; + + layer = createStyleLayer(layerObject); + + } else { + if (typeof layerObject.source === 'object') { + this.addSource(id, layerObject.source); + layerObject = clone(layerObject); + layerObject = (extend(layerObject, {source: id}): any); + } + + // this layer is not in the style.layers array, so we pass an impossible array index + if (this._validate(validateStyle.layer, + `layers.${id}`, layerObject, {arrayIndex: -1}, options)) return; + + layer = createStyleLayer(layerObject); + this._validateLayer(layer); + + layer.setEventedParent(this, {layer: {id}}); + this._serializedLayers[layer.id] = layer.serialize(); + } + + const index = before ? this._order.indexOf(before) : this._order.length; + if (before && index === -1) { + this.fire(new ErrorEvent(new Error(`Layer with id "${before}" does not exist on this map.`))); + return; + } + + this._order.splice(index, 0, id); + this._layerOrderChanged = true; + + this._layers[id] = layer; + + if (this._removedLayers[id] && layer.source && layer.type !== 'custom') { + // If, in the current batch, we have already removed this layer + // and we are now re-adding it with a different `type`, then we + // need to clear (rather than just reload) the underyling source's + // tiles. Otherwise, tiles marked 'reloading' will have buckets / + // buffers that are set up for the _previous_ version of this + // layer, causing, e.g.: + // https://github.com/mapbox/mapbox-gl-js/issues/3633 + const removed = this._removedLayers[id]; + delete this._removedLayers[id]; + if (removed.type !== layer.type) { + this._updatedSources[layer.source] = 'clear'; + } else { + this._updatedSources[layer.source] = 'reload'; + this.sourceCaches[layer.source].pause(); + } + } + this._updateLayer(layer); + + if (layer.onAdd) { + layer.onAdd(this.map); + } + } + + /** + * Moves a layer to a different z-position. The layer will be inserted before the layer with + * ID `before`, or appended if `before` is omitted. + * @param {string} id ID of the layer to move + * @param {string} [before] ID of an existing layer to insert before + */ + moveLayer(id: string, before?: string) { + this._checkLoaded(); + this._changed = true; + + const layer = this._layers[id]; + if (!layer) { + this.fire(new ErrorEvent(new Error(`The layer '${id}' does not exist in the map's style and cannot be moved.`))); + return; + } + + if (id === before) { + return; + } + + const index = this._order.indexOf(id); + this._order.splice(index, 1); + + const newIndex = before ? this._order.indexOf(before) : this._order.length; + if (before && newIndex === -1) { + this.fire(new ErrorEvent(new Error(`Layer with id "${before}" does not exist on this map.`))); + return; + } + this._order.splice(newIndex, 0, id); + + this._layerOrderChanged = true; + } + + /** + * Remove the layer with the given id from the style. + * + * If no such layer exists, an `error` event is fired. + * + * @param {string} id id of the layer to remove + * @fires error + */ + removeLayer(id: string) { + this._checkLoaded(); + + const layer = this._layers[id]; + if (!layer) { + this.fire(new ErrorEvent(new Error(`The layer '${id}' does not exist in the map's style and cannot be removed.`))); + return; + } + + layer.setEventedParent(null); + + const index = this._order.indexOf(id); + this._order.splice(index, 1); + + this._layerOrderChanged = true; + this._changed = true; + this._removedLayers[id] = layer; + delete this._layers[id]; + delete this._serializedLayers[id]; + delete this._updatedLayers[id]; + delete this._updatedPaintProps[id]; + + if (layer.onRemove) { + layer.onRemove(this.map); + } + } + + /** + * Return the style layer object with the given `id`. + * + * @param {string} id - id of the desired layer + * @returns {?Object} a layer, if one with the given `id` exists + */ + getLayer(id: string): Object { + return this._layers[id]; + } + + /** + * checks if a specific layer is present within the style. + * + * @param {string} id - id of the desired layer + * @returns {boolean} a boolean specifying if the given layer is present + */ + hasLayer(id: string): boolean { + return id in this._layers; + } + + setLayerZoomRange(layerId: string, minzoom: ?number, maxzoom: ?number) { + this._checkLoaded(); + + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot have zoom extent.`))); + return; + } + + if (layer.minzoom === minzoom && layer.maxzoom === maxzoom) return; + + if (minzoom != null) { + layer.minzoom = minzoom; + } + if (maxzoom != null) { + layer.maxzoom = maxzoom; + } + this._updateLayer(layer); + } + + setFilter(layerId: string, filter: ?FilterSpecification, options: StyleSetterOptions = {}) { + this._checkLoaded(); + + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be filtered.`))); + return; + } + + if (deepEqual(layer.filter, filter)) { + return; + } + + if (filter === null || filter === undefined) { + layer.filter = undefined; + this._updateLayer(layer); + return; + } + + if (this._validate(validateStyle.filter, `layers.${layer.id}.filter`, filter, null, options)) { + return; + } + + layer.filter = clone(filter); + this._updateLayer(layer); + } + + /** + * Get a layer's filter object + * @param {string} layer the layer to inspect + * @returns {*} the layer's filter, if any + */ + getFilter(layer: string) { + return clone(this.getLayer(layer).filter); + } + + setLayoutProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) { + this._checkLoaded(); + + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be styled.`))); + return; + } + + if (deepEqual(layer.getLayoutProperty(name), value)) return; + + layer.setLayoutProperty(name, value, options); + this._updateLayer(layer); + } + + /** + * Get a layout property's value from a given layer + * @param {string} layerId the layer to inspect + * @param {string} name the name of the layout property + * @returns {*} the property value + */ + getLayoutProperty(layerId: string, name: string) { + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style.`))); + return; + } + + return layer.getLayoutProperty(name); + } + + setPaintProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) { + this._checkLoaded(); + + const layer = this.getLayer(layerId); + if (!layer) { + this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be styled.`))); + return; + } + + if (deepEqual(layer.getPaintProperty(name), value)) return; + + const requiresRelayout = layer.setPaintProperty(name, value, options); + if (requiresRelayout) { + this._updateLayer(layer); + } + + this._changed = true; + this._updatedPaintProps[layerId] = true; + } + + getPaintProperty(layer: string, name: string) { + return this.getLayer(layer).getPaintProperty(name); + } + + setFeatureState(target: { source: string; sourceLayer?: string; id: string | number; }, state: Object) { + this._checkLoaded(); + const sourceId = target.source; + const sourceLayer = target.sourceLayer; + const sourceCache = this.sourceCaches[sourceId]; + + if (sourceCache === undefined) { + this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`))); + return; + } + const sourceType = sourceCache.getSource().type; + if (sourceType === 'geojson' && sourceLayer) { + this.fire(new ErrorEvent(new Error(`GeoJSON sources cannot have a sourceLayer parameter.`))); + return; + } + if (sourceType === 'vector' && !sourceLayer) { + this.fire(new ErrorEvent(new Error(`The sourceLayer parameter must be provided for vector source types.`))); + return; + } + if (target.id === undefined) { + this.fire(new ErrorEvent(new Error(`The feature id parameter must be provided.`))); + } + + sourceCache.setFeatureState(sourceLayer, target.id, state); + } + + removeFeatureState(target: { source: string; sourceLayer?: string; id?: string | number; }, key?: string) { + this._checkLoaded(); + const sourceId = target.source; + const sourceCache = this.sourceCaches[sourceId]; + + if (sourceCache === undefined) { + this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`))); + return; + } + + const sourceType = sourceCache.getSource().type; + const sourceLayer = sourceType === 'vector' ? target.sourceLayer : undefined; + + if (sourceType === 'vector' && !sourceLayer) { + this.fire(new ErrorEvent(new Error(`The sourceLayer parameter must be provided for vector source types.`))); + return; + } + + if (key && (typeof target.id !== 'string' && typeof target.id !== 'number')) { + this.fire(new ErrorEvent(new Error(`A feature id is required to remove its specific state property.`))); + return; + } + + sourceCache.removeFeatureState(sourceLayer, target.id, key); + } + + getFeatureState(target: { source: string; sourceLayer?: string; id: string | number; }) { + this._checkLoaded(); + const sourceId = target.source; + const sourceLayer = target.sourceLayer; + const sourceCache = this.sourceCaches[sourceId]; + + if (sourceCache === undefined) { + this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`))); + return; + } + const sourceType = sourceCache.getSource().type; + if (sourceType === 'vector' && !sourceLayer) { + this.fire(new ErrorEvent(new Error(`The sourceLayer parameter must be provided for vector source types.`))); + return; + } + if (target.id === undefined) { + this.fire(new ErrorEvent(new Error(`The feature id parameter must be provided.`))); + } + + return sourceCache.getFeatureState(sourceLayer, target.id); + } + + getTransition() { + return extend({duration: 300, delay: 0}, this.stylesheet && this.stylesheet.transition); + } + + serialize() { + return filterObject({ + version: this.stylesheet.version, + name: this.stylesheet.name, + metadata: this.stylesheet.metadata, + light: this.stylesheet.light, + center: this.stylesheet.center, + zoom: this.stylesheet.zoom, + bearing: this.stylesheet.bearing, + pitch: this.stylesheet.pitch, + sprite: this.stylesheet.sprite, + glyphs: this.stylesheet.glyphs, + transition: this.stylesheet.transition, + sources: mapObject(this.sourceCaches, (source) => source.serialize()), + layers: this._serializeLayers(this._order) + }, (value) => { return value !== undefined; }); + } + + _updateLayer(layer: StyleLayer) { + this._updatedLayers[layer.id] = true; + if (layer.source && !this._updatedSources[layer.source] && + //Skip for raster layers (https://github.com/mapbox/mapbox-gl-js/issues/7865) + this.sourceCaches[layer.source].getSource().type !== 'raster') { + this._updatedSources[layer.source] = 'reload'; + this.sourceCaches[layer.source].pause(); + } + this._changed = true; + } + + _flattenAndSortRenderedFeatures(sourceResults: Array) { + // Feature order is complicated. + // The order between features in two 2D layers is always determined by layer order. + // The order between features in two 3D layers is always determined by depth. + // The order between a feature in a 2D layer and a 3D layer is tricky: + // Most often layer order determines the feature order in this case. If + // a line layer is above a extrusion layer the line feature will be rendered + // above the extrusion. If the line layer is below the extrusion layer, + // it will be rendered below it. + // + // There is a weird case though. + // You have layers in this order: extrusion_layer_a, line_layer, extrusion_layer_b + // Each layer has a feature that overlaps the other features. + // The feature in extrusion_layer_a is closer than the feature in extrusion_layer_b so it is rendered above. + // The feature in line_layer is rendered above extrusion_layer_a. + // This means that that the line_layer feature is above the extrusion_layer_b feature despite + // it being in an earlier layer. + + const isLayer3D = layerId => this._layers[layerId].type === 'fill-extrusion'; + + const layerIndex = {}; + const features3D = []; + for (let l = this._order.length - 1; l >= 0; l--) { + const layerId = this._order[l]; + if (isLayer3D(layerId)) { + layerIndex[layerId] = l; + for (const sourceResult of sourceResults) { + const layerFeatures = sourceResult[layerId]; + if (layerFeatures) { + for (const featureWrapper of layerFeatures) { + features3D.push(featureWrapper); + } + } + } + } + } + + features3D.sort((a, b) => { + return b.intersectionZ - a.intersectionZ; + }); + + const features = []; + for (let l = this._order.length - 1; l >= 0; l--) { + const layerId = this._order[l]; + + if (isLayer3D(layerId)) { + // add all 3D features that are in or above the current layer + for (let i = features3D.length - 1; i >= 0; i--) { + const topmost3D = features3D[i].feature; + if (layerIndex[topmost3D.layer.id] < l) break; + features.push(topmost3D); + features3D.pop(); + } + } else { + for (const sourceResult of sourceResults) { + const layerFeatures = sourceResult[layerId]; + if (layerFeatures) { + for (const featureWrapper of layerFeatures) { + features.push(featureWrapper.feature); + } + } + } + } + } + + return features; + } + + queryRenderedFeatures(queryGeometry: any, params: any, transform: Transform) { + if (params && params.filter) { + this._validate(validateStyle.filter, 'queryRenderedFeatures.filter', params.filter, null, params); + } + + const includedSources = {}; + if (params && params.layers) { + if (!Array.isArray(params.layers)) { + this.fire(new ErrorEvent(new Error('parameters.layers must be an Array.'))); + return []; + } + for (const layerId of params.layers) { + const layer = this._layers[layerId]; + if (!layer) { + // this layer is not in the style.layers array + this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be queried for features.`))); + return []; + } + includedSources[layer.source] = true; + } + } + + const sourceResults = []; + + params.availableImages = this._availableImages; + + for (const id in this.sourceCaches) { + if (params.layers && !includedSources[id]) continue; + sourceResults.push( + queryRenderedFeatures( + this.sourceCaches[id], + this._layers, + this._serializedLayers, + queryGeometry, + params, + transform) + ); + } + + if (this.placement) { + // If a placement has run, query against its CollisionIndex + // for symbol results, and treat it as an extra source to merge + sourceResults.push( + queryRenderedSymbols( + this._layers, + this._serializedLayers, + this.sourceCaches, + queryGeometry, + params, + this.placement.collisionIndex, + this.placement.retainedQueryData) + ); + } + + return this._flattenAndSortRenderedFeatures(sourceResults); + } + + querySourceFeatures(sourceID: string, params: ?{sourceLayer: ?string, filter: ?Array, validate?: boolean}) { + if (params && params.filter) { + this._validate(validateStyle.filter, 'querySourceFeatures.filter', params.filter, null, params); + } + const sourceCache = this.sourceCaches[sourceID]; + return sourceCache ? querySourceFeatures(sourceCache, params) : []; + } + + addSourceType(name: string, SourceType: SourceClass, callback: Callback) { + if (Style.getSourceType(name)) { + return callback(new Error(`A source type called "${name}" already exists.`)); + } + + Style.setSourceType(name, SourceType); + + if (!SourceType.workerSourceURL) { + return callback(null, null); + } + + this.dispatcher.broadcast('loadWorkerSource', { + name, + url: SourceType.workerSourceURL + }, callback); + } + + getLight() { + return this.light.getLight(); + } + + setLight(lightOptions: LightSpecification, options: StyleSetterOptions = {}) { + this._checkLoaded(); + + const light = this.light.getLight(); + let _update = false; + for (const key in lightOptions) { + if (!deepEqual(lightOptions[key], light[key])) { + _update = true; + break; + } + } + if (!_update) return; + + const parameters = { + now: browser.now(), + transition: extend({ + duration: 300, + delay: 0 + }, this.stylesheet.transition) + }; + + this.light.setLight(lightOptions, options); + this.light.updateTransitions(parameters); + } + + _validate(validate: Validator, key: string, value: any, props: any, options: { validate?: boolean } = {}) { + if (options && options.validate === false) { + return false; + } + return emitValidationErrors(this, validate.call(validateStyle, extend({ + key, + style: this.serialize(), + value, + styleSpec + }, props))); + } + + _remove() { + if (this._request) { + this._request.cancel(); + this._request = null; + } + if (this._spriteRequest) { + this._spriteRequest.cancel(); + this._spriteRequest = null; + } + rtlTextPluginEvented.off('pluginStateChange', this._rtlTextPluginCallback); + for (const layerId in this._layers) { + const layer: StyleLayer = this._layers[layerId]; + layer.setEventedParent(null); + } + for (const id in this.sourceCaches) { + this.sourceCaches[id].clearTiles(); + this.sourceCaches[id].setEventedParent(null); + } + this.imageManager.setEventedParent(null); + this.setEventedParent(null); + this.dispatcher.remove(); + } + + _clearSource(id: string) { + this.sourceCaches[id].clearTiles(); + } + + _reloadSource(id: string) { + this.sourceCaches[id].resume(); + this.sourceCaches[id].reload(); + } + + _updateSources(transform: Transform) { + for (const id in this.sourceCaches) { + this.sourceCaches[id].update(transform); + } + } + + _generateCollisionBoxes() { + for (const id in this.sourceCaches) { + this._reloadSource(id); + } + } + + _updatePlacement(transform: Transform, showCollisionBoxes: boolean, fadeDuration: number, crossSourceCollisions: boolean, forceFullPlacement: boolean = false) { + let symbolBucketsChanged = false; + let placementCommitted = false; + + const layerTiles = {}; + + for (const layerID of this._order) { + const styleLayer = this._layers[layerID]; + if (styleLayer.type !== 'symbol') continue; + + if (!layerTiles[styleLayer.source]) { + const sourceCache = this.sourceCaches[styleLayer.source]; + layerTiles[styleLayer.source] = sourceCache.getRenderableIds(true) + .map((id) => sourceCache.getTileByID(id)) + .sort((a, b) => (b.tileID.overscaledZ - a.tileID.overscaledZ) || (a.tileID.isLessThan(b.tileID) ? -1 : 1)); + } + + const layerBucketsChanged = this.crossTileSymbolIndex.addLayer(styleLayer, layerTiles[styleLayer.source], transform.center.lng); + symbolBucketsChanged = symbolBucketsChanged || layerBucketsChanged; + } + this.crossTileSymbolIndex.pruneUnusedLayers(this._order); + + // Anything that changes our "in progress" layer and tile indices requires us + // to start over. When we start over, we do a full placement instead of incremental + // to prevent starvation. + // We need to restart placement to keep layer indices in sync. + // Also force full placement when fadeDuration === 0 to ensure that newly loaded + // tiles will fully display symbols in their first frame + forceFullPlacement = forceFullPlacement || this._layerOrderChanged || fadeDuration === 0; + + if (forceFullPlacement || !this.pauseablePlacement || (this.pauseablePlacement.isDone() && !this.placement.stillRecent(browser.now(), transform.zoom))) { + this.pauseablePlacement = new PauseablePlacement(transform, this._order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, this.placement); + this._layerOrderChanged = false; + } + + if (this.pauseablePlacement.isDone()) { + // the last placement finished running, but the next one hasn’t + // started yet because of the `stillRecent` check immediately + // above, so mark it stale to ensure that we request another + // render frame + this.placement.setStale(); + } else { + this.pauseablePlacement.continuePlacement(this._order, this._layers, layerTiles); + + if (this.pauseablePlacement.isDone()) { + this.placement = this.pauseablePlacement.commit(browser.now()); + placementCommitted = true; + } + + if (symbolBucketsChanged) { + // since the placement gets split over multiple frames it is possible + // these buckets were processed before they were changed and so the + // placement is already stale while it is in progress + this.pauseablePlacement.placement.setStale(); + } + } + + if (placementCommitted || symbolBucketsChanged) { + for (const layerID of this._order) { + const styleLayer = this._layers[layerID]; + if (styleLayer.type !== 'symbol') continue; + this.placement.updateLayerOpacities(styleLayer, layerTiles[styleLayer.source]); + } + } + + // needsRender is false when we have just finished a placement that didn't change the visibility of any symbols + const needsRerender = !this.pauseablePlacement.isDone() || this.placement.hasTransitions(browser.now()); + return needsRerender; + } + + _releaseSymbolFadeTiles() { + for (const id in this.sourceCaches) { + this.sourceCaches[id].releaseSymbolFadeTiles(); + } + } + + // Callbacks from web workers + + getImages(mapId: string, params: {icons: Array, source: string, tileID: OverscaledTileID, type: string}, callback: Callback<{[_: string]: StyleImage}>) { + + this.imageManager.getImages(params.icons, callback); + + // Apply queued image changes before setting the tile's dependencies so that the tile + // is not reloaded unecessarily. Without this forced update the reload could happen in cases + // like this one: + // - icons contains "my-image" + // - imageManager.getImages(...) triggers `onstyleimagemissing` + // - the user adds "my-image" within the callback + // - addImage adds "my-image" to this._changedImages + // - the next frame triggers a reload of this tile even though it already has the latest version + this._updateTilesForChangedImages(); + + const sourceCache = this.sourceCaches[params.source]; + if (sourceCache) { + sourceCache.setDependencies(params.tileID.key, params.type, params.icons); + } + } + + getGlyphs(mapId: string, params: {stacks: {[_: string]: Array}}, callback: Callback<{[_: string]: {[_: number]: ?StyleGlyph}}>) { + this.glyphManager.getGlyphs(params.stacks, callback); + } + + getResource(mapId: string, params: RequestParameters, callback: ResponseCallback): Cancelable { + return makeRequest(params, callback); + } +} + +Style.getSourceType = getSourceType; +Style.setSourceType = setSourceType; +Style.registerForPluginStateChange = registerForPluginStateChange; + +export default Style; diff --git a/node_modules/mapbox-gl/src/style/style_glyph.js b/node_modules/mapbox-gl/src/style/style_glyph.js new file mode 100644 index 0000000000000000000000000000000000000000..009bf125796b9bb170c5de07cb6966d6ea30e11b --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_glyph.js @@ -0,0 +1,17 @@ +// @flow + +import type {AlphaImage} from '../util/image'; + +export type GlyphMetrics = { + width: number, + height: number, + left: number, + top: number, + advance: number +}; + +export type StyleGlyph = { + id: number, + bitmap: AlphaImage, + metrics: GlyphMetrics +}; diff --git a/node_modules/mapbox-gl/src/style/style_image.js b/node_modules/mapbox-gl/src/style/style_image.js new file mode 100644 index 0000000000000000000000000000000000000000..6c327fa6f4295137b2af14954ff1cbfe1a66111b --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_image.js @@ -0,0 +1,137 @@ +// @flow + +import {RGBAImage} from '../util/image'; + +import type Map from '../ui/map'; + +export type StyleImageData = { + data: RGBAImage, + version: number, + hasRenderCallback?: boolean, + userImage?: StyleImageInterface +}; + +export type StyleImageMetadata = { + pixelRatio: number, + sdf: boolean, + stretchX?: Array<[number, number]>, + stretchY?: Array<[number, number]>, + content?: [number, number, number, number] +}; + +export type StyleImage = StyleImageData & StyleImageMetadata; + +export type StyleImageInterface = { + width: number, + height: number, + data: Uint8Array | Uint8ClampedArray, + render?: () => boolean, + onAdd?: (map: Map, id: string) => void, + onRemove?: () => void +}; + +export function renderStyleImage(image: StyleImage) { + const {userImage} = image; + if (userImage && userImage.render) { + const updated = userImage.render(); + if (updated) { + image.data.replace(new Uint8Array(userImage.data.buffer)); + return true; + } + } + return false; +} + +/** + * Interface for dynamically generated style images. This is a specification for + * implementers to model: it is not an exported method or class. + * + * Images implementing this interface can be redrawn for every frame. They can be used to animate + * icons and patterns or make them respond to user input. Style images can implement a + * {@link StyleImageInterface#render} method. The method is called every frame and + * can be used to update the image. + * + * @interface StyleImageInterface + * @property {number} width + * @property {number} height + * @property {Uint8Array | Uint8ClampedArray} data + * + * @see [Add an animated icon to the map.](https://docs.mapbox.com/mapbox-gl-js/example/add-image-animated/) + * + * @example + * var flashingSquare = { + * width: 64, + * height: 64, + * data: new Uint8Array(64 * 64 * 4), + * + * onAdd: function(map) { + * this.map = map; + * }, + * + * render: function() { + * // keep repainting while the icon is on the map + * this.map.triggerRepaint(); + * + * // alternate between black and white based on the time + * var value = Math.round(Date.now() / 1000) % 2 === 0 ? 255 : 0; + * + * // check if image needs to be changed + * if (value !== this.previousValue) { + * this.previousValue = value; + * + * var bytesPerPixel = 4; + * for (var x = 0; x < this.width; x++) { + * for (var y = 0; y < this.height; y++) { + * var offset = (y * this.width + x) * bytesPerPixel; + * this.data[offset + 0] = value; + * this.data[offset + 1] = value; + * this.data[offset + 2] = value; + * this.data[offset + 3] = 255; + * } + * } + * + * // return true to indicate that the image changed + * return true; + * } + * } + * } + * + * map.addImage('flashing_square', flashingSquare); + */ + +/** + * This method is called once before every frame where the icon will be used. + * The method can optionally update the image's `data` member with a new image. + * + * If the method updates the image it must return `true` to commit the change. + * If the method returns `false` or nothing the image is assumed to not have changed. + * + * If updates are infrequent it maybe easier to use {@link Map#updateImage} to update + * the image instead of implementing this method. + * + * @function + * @memberof StyleImageInterface + * @instance + * @name render + * @return {boolean} `true` if this method updated the image. `false` if the image was not changed. + */ + +/** + * Optional method called when the layer has been added to the Map with {@link Map#addImage}. + * + * @function + * @memberof StyleImageInterface + * @instance + * @name onAdd + * @param {Map} map The Map this custom layer was just added to. + */ + +/** + * Optional method called when the icon is removed from the map with {@link Map#removeImage}. + * This gives the image a chance to clean up resources and event listeners. + * + * @function + * @memberof StyleImageInterface + * @instance + * @name onRemove + */ diff --git a/node_modules/mapbox-gl/src/style/style_layer.js b/node_modules/mapbox-gl/src/style/style_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..c2a7d6cb0cb579e9fb01c31fbcef2d4fc9c5f8c3 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer.js @@ -0,0 +1,283 @@ +// @flow + +import {endsWith, filterObject} from '../util/util'; + +import styleSpec from '../style-spec/reference/latest'; +import { + validateStyle, + validateLayoutProperty, + validatePaintProperty, + emitValidationErrors +} from './validate_style'; +import {Evented} from '../util/evented'; +import {Layout, Transitionable, Transitioning, Properties, PossiblyEvaluated, PossiblyEvaluatedPropertyValue} from './properties'; +import {supportsPropertyExpression} from '../style-spec/util/properties'; + +import type {FeatureState} from '../style-spec/expression'; +import type {Bucket} from '../data/bucket'; +import type Point from '@mapbox/point-geometry'; +import type {FeatureFilter} from '../style-spec/feature_filter'; +import type {TransitionParameters, PropertyValue} from './properties'; +import type EvaluationParameters, {CrossfadeParameters} from './evaluation_parameters'; +import type Transform from '../geo/transform'; +import type { + LayerSpecification, + FilterSpecification +} from '../style-spec/types'; +import type {CustomLayerInterface} from './style_layer/custom_style_layer'; +import type Map from '../ui/map'; +import type {StyleSetterOptions} from './style'; + +const TRANSITION_SUFFIX = '-transition'; + +class StyleLayer extends Evented { + id: string; + metadata: mixed; + type: string; + source: string; + sourceLayer: ?string; + minzoom: ?number; + maxzoom: ?number; + filter: FilterSpecification | void; + visibility: 'visible' | 'none' | void; + _crossfadeParameters: CrossfadeParameters; + + _unevaluatedLayout: Layout; + +layout: mixed; + + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + +paint: mixed; + + _featureFilter: FeatureFilter; + + +queryRadius: (bucket: Bucket) => number; + +queryIntersectsFeature: (queryGeometry: Array, + feature: VectorTileFeature, + featureState: FeatureState, + geometry: Array>, + zoom: number, + transform: Transform, + pixelsToTileUnits: number, + pixelPosMatrix: Float32Array) => boolean | number; + + +onAdd: ?(map: Map) => void; + +onRemove: ?(map: Map) => void; + + constructor(layer: LayerSpecification | CustomLayerInterface, properties: $ReadOnly<{layout?: Properties<*>, paint?: Properties<*>}>) { + super(); + + this.id = layer.id; + this.type = layer.type; + this._featureFilter = {filter: () => true, needGeometry: false}; + + if (layer.type === 'custom') return; + + layer = ((layer: any): LayerSpecification); + + this.metadata = layer.metadata; + this.minzoom = layer.minzoom; + this.maxzoom = layer.maxzoom; + + if (layer.type !== 'background') { + this.source = layer.source; + this.sourceLayer = layer['source-layer']; + this.filter = layer.filter; + } + + if (properties.layout) { + this._unevaluatedLayout = new Layout(properties.layout); + } + + if (properties.paint) { + this._transitionablePaint = new Transitionable(properties.paint); + + for (const property in layer.paint) { + this.setPaintProperty(property, layer.paint[property], {validate: false}); + } + for (const property in layer.layout) { + this.setLayoutProperty(property, layer.layout[property], {validate: false}); + } + + this._transitioningPaint = this._transitionablePaint.untransitioned(); + //$FlowFixMe + this.paint = new PossiblyEvaluated(properties.paint); + } + } + + getCrossfadeParameters() { + return this._crossfadeParameters; + } + + getLayoutProperty(name: string) { + if (name === 'visibility') { + return this.visibility; + } + + return this._unevaluatedLayout.getValue(name); + } + + setLayoutProperty(name: string, value: any, options: StyleSetterOptions = {}) { + if (value !== null && value !== undefined) { + const key = `layers.${this.id}.layout.${name}`; + if (this._validate(validateLayoutProperty, key, name, value, options)) { + return; + } + } + + if (name === 'visibility') { + this.visibility = value; + return; + } + + this._unevaluatedLayout.setValue(name, value); + } + + getPaintProperty(name: string) { + if (endsWith(name, TRANSITION_SUFFIX)) { + return this._transitionablePaint.getTransition(name.slice(0, -TRANSITION_SUFFIX.length)); + } else { + return this._transitionablePaint.getValue(name); + } + } + + setPaintProperty(name: string, value: mixed, options: StyleSetterOptions = {}) { + if (value !== null && value !== undefined) { + const key = `layers.${this.id}.paint.${name}`; + if (this._validate(validatePaintProperty, key, name, value, options)) { + return false; + } + } + + if (endsWith(name, TRANSITION_SUFFIX)) { + this._transitionablePaint.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), (value: any) || undefined); + return false; + } else { + const transitionable = this._transitionablePaint._values[name]; + const isCrossFadedProperty = transitionable.property.specification["property-type"] === 'cross-faded-data-driven'; + const wasDataDriven = transitionable.value.isDataDriven(); + const oldValue = transitionable.value; + + this._transitionablePaint.setValue(name, value); + this._handleSpecialPaintPropertyUpdate(name); + + const newValue = this._transitionablePaint._values[name].value; + const isDataDriven = newValue.isDataDriven(); + + // if a cross-faded value is changed, we need to make sure the new icons get added to each tile's iconAtlas + // so a call to _updateLayer is necessary, and we return true from this function so it gets called in + // Style#setPaintProperty + return isDataDriven || wasDataDriven || isCrossFadedProperty || this._handleOverridablePaintPropertyUpdate(name, oldValue, newValue); + } + } + + _handleSpecialPaintPropertyUpdate(_: string) { + // No-op; can be overridden by derived classes. + } + + // eslint-disable-next-line no-unused-vars + _handleOverridablePaintPropertyUpdate(name: string, oldValue: PropertyValue, newValue: PropertyValue): boolean { + // No-op; can be overridden by derived classes. + return false; + } + + isHidden(zoom: number) { + if (this.minzoom && zoom < this.minzoom) return true; + if (this.maxzoom && zoom >= this.maxzoom) return true; + return this.visibility === 'none'; + } + + updateTransitions(parameters: TransitionParameters) { + this._transitioningPaint = this._transitionablePaint.transitioned(parameters, this._transitioningPaint); + } + + hasTransition() { + return this._transitioningPaint.hasTransition(); + } + + recalculate(parameters: EvaluationParameters, availableImages: Array) { + if (parameters.getCrossfadeParameters) { + this._crossfadeParameters = parameters.getCrossfadeParameters(); + } + + if (this._unevaluatedLayout) { + (this: any).layout = this._unevaluatedLayout.possiblyEvaluate(parameters, undefined, availableImages); + } + + (this: any).paint = this._transitioningPaint.possiblyEvaluate(parameters, undefined, availableImages); + } + + serialize() { + const output: any = { + 'id': this.id, + 'type': this.type, + 'source': this.source, + 'source-layer': this.sourceLayer, + 'metadata': this.metadata, + 'minzoom': this.minzoom, + 'maxzoom': this.maxzoom, + 'filter': this.filter, + 'layout': this._unevaluatedLayout && this._unevaluatedLayout.serialize(), + 'paint': this._transitionablePaint && this._transitionablePaint.serialize() + }; + + if (this.visibility) { + output.layout = output.layout || {}; + output.layout.visibility = this.visibility; + } + + return filterObject(output, (value, key) => { + return value !== undefined && + !(key === 'layout' && !Object.keys(value).length) && + !(key === 'paint' && !Object.keys(value).length); + }); + } + + _validate(validate: Function, key: string, name: string, value: mixed, options: StyleSetterOptions = {}) { + if (options && options.validate === false) { + return false; + } + return emitValidationErrors(this, validate.call(validateStyle, { + key, + layerType: this.type, + objectKey: name, + value, + styleSpec, + // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407 + style: {glyphs: true, sprite: true} + })); + } + + is3D() { + return false; + } + + isTileClipped() { + return false; + } + + hasOffscreenPass() { + return false; + } + + resize() { + // noop + } + + isStateDependent() { + for (const property in (this: any).paint._values) { + const value = (this: any).paint.get(property); + if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) { + continue; + } + + if ((value.value.kind === 'source' || value.value.kind === 'composite') && + value.value.isStateDependent) { + return true; + } + } + return false; + } +} + +export default StyleLayer; diff --git a/node_modules/mapbox-gl/src/style/style_layer/background_style_layer.js b/node_modules/mapbox-gl/src/style/style_layer/background_style_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..33a2ead347ecbfe38c203777999237e1b59055e1 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/background_style_layer.js @@ -0,0 +1,21 @@ +// @flow + +import StyleLayer from '../style_layer'; + +import properties from './background_style_layer_properties'; +import {Transitionable, Transitioning, PossiblyEvaluated} from '../properties'; + +import type {PaintProps} from './background_style_layer_properties'; +import type {LayerSpecification} from '../../style-spec/types'; + +class BackgroundStyleLayer extends StyleLayer { + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + + constructor(layer: LayerSpecification) { + super(layer, properties); + } +} + +export default BackgroundStyleLayer; diff --git a/node_modules/mapbox-gl/src/style/style_layer/background_style_layer_properties.js b/node_modules/mapbox-gl/src/style/style_layer/background_style_layer_properties.js new file mode 100644 index 0000000000000000000000000000000000000000..868663cfce19b148efc1e4d0f262b103e2b7d046 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/background_style_layer_properties.js @@ -0,0 +1,40 @@ +// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`. +// @flow +/* eslint-disable */ + +import styleSpec from '../../style-spec/reference/latest'; + +import { + Properties, + DataConstantProperty, + DataDrivenProperty, + CrossFadedDataDrivenProperty, + CrossFadedProperty, + ColorRampProperty +} from '../properties'; + +import type Color from '../../style-spec/util/color'; + +import type Formatted from '../../style-spec/expression/types/formatted'; + +import type ResolvedImage from '../../style-spec/expression/types/resolved_image'; + + +export type PaintProps = {| + "background-color": DataConstantProperty, + "background-pattern": CrossFadedProperty, + "background-opacity": DataConstantProperty, +|}; + +const paint: Properties = new Properties({ + "background-color": new DataConstantProperty(styleSpec["paint_background"]["background-color"]), + "background-pattern": new CrossFadedProperty(styleSpec["paint_background"]["background-pattern"]), + "background-opacity": new DataConstantProperty(styleSpec["paint_background"]["background-opacity"]), +}); + +// Note: without adding the explicit type annotation, Flow infers weaker types +// for these objects from their use in the constructor to StyleLayer, as +// {layout?: Properties<...>, paint: Properties<...>} +export default ({ paint }: $Exact<{ + paint: Properties +}>); diff --git a/node_modules/mapbox-gl/src/style/style_layer/circle_style_layer.js b/node_modules/mapbox-gl/src/style/style_layer/circle_style_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..e5168f56a29d3a3e13a756beb0ded3ae283c7eab --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/circle_style_layer.js @@ -0,0 +1,98 @@ +// @flow + +import StyleLayer from '../style_layer'; + +import CircleBucket from '../../data/bucket/circle_bucket'; +import {polygonIntersectsBufferedPoint} from '../../util/intersection_tests'; +import {getMaximumPaintValue, translateDistance, translate} from '../query_utils'; +import properties from './circle_style_layer_properties'; +import {Transitionable, Transitioning, Layout, PossiblyEvaluated} from '../properties'; +import {vec4} from 'gl-matrix'; +import Point from '@mapbox/point-geometry'; + +import type {FeatureState} from '../../style-spec/expression'; +import type Transform from '../../geo/transform'; +import type {Bucket, BucketParameters} from '../../data/bucket'; +import type {LayoutProps, PaintProps} from './circle_style_layer_properties'; +import type {LayerSpecification} from '../../style-spec/types'; + +class CircleStyleLayer extends StyleLayer { + _unevaluatedLayout: Layout; + layout: PossiblyEvaluated; + + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + + constructor(layer: LayerSpecification) { + super(layer, properties); + } + + createBucket(parameters: BucketParameters<*>) { + return new CircleBucket(parameters); + } + + queryRadius(bucket: Bucket): number { + const circleBucket: CircleBucket = (bucket: any); + return getMaximumPaintValue('circle-radius', this, circleBucket) + + getMaximumPaintValue('circle-stroke-width', this, circleBucket) + + translateDistance(this.paint.get('circle-translate')); + } + + queryIntersectsFeature(queryGeometry: Array, + feature: VectorTileFeature, + featureState: FeatureState, + geometry: Array>, + zoom: number, + transform: Transform, + pixelsToTileUnits: number, + pixelPosMatrix: Float32Array): boolean { + const translatedPolygon = translate(queryGeometry, + this.paint.get('circle-translate'), + this.paint.get('circle-translate-anchor'), + transform.angle, pixelsToTileUnits); + const radius = this.paint.get('circle-radius').evaluate(feature, featureState); + const stroke = this.paint.get('circle-stroke-width').evaluate(feature, featureState); + const size = radius + stroke; + + // For pitch-alignment: map, compare feature geometry to query geometry in the plane of the tile + // // Otherwise, compare geometry in the plane of the viewport + // // A circle with fixed scaling relative to the viewport gets larger in tile space as it moves into the distance + // // A circle with fixed scaling relative to the map gets smaller in viewport space as it moves into the distance + const alignWithMap = this.paint.get('circle-pitch-alignment') === 'map'; + const transformedPolygon = alignWithMap ? translatedPolygon : projectQueryGeometry(translatedPolygon, pixelPosMatrix); + const transformedSize = alignWithMap ? size * pixelsToTileUnits : size; + + for (const ring of geometry) { + for (const point of ring) { + + const transformedPoint = alignWithMap ? point : projectPoint(point, pixelPosMatrix); + + let adjustedSize = transformedSize; + const projectedCenter = vec4.transformMat4([], [point.x, point.y, 0, 1], pixelPosMatrix); + if (this.paint.get('circle-pitch-scale') === 'viewport' && this.paint.get('circle-pitch-alignment') === 'map') { + adjustedSize *= projectedCenter[3] / transform.cameraToCenterDistance; + } else if (this.paint.get('circle-pitch-scale') === 'map' && this.paint.get('circle-pitch-alignment') === 'viewport') { + adjustedSize *= transform.cameraToCenterDistance / projectedCenter[3]; + } + + if (polygonIntersectsBufferedPoint(transformedPolygon, transformedPoint, adjustedSize)) return true; + } + } + + return false; + } +} + +function projectPoint(p: Point, pixelPosMatrix: Float32Array) { + const point = vec4.transformMat4([], [p.x, p.y, 0, 1], pixelPosMatrix); + return new Point(point[0] / point[3], point[1] / point[3]); +} + +function projectQueryGeometry(queryGeometry: Array, pixelPosMatrix: Float32Array) { + return queryGeometry.map((p) => { + return projectPoint(p, pixelPosMatrix); + }); +} + +export default CircleStyleLayer; diff --git a/node_modules/mapbox-gl/src/style/style_layer/circle_style_layer_properties.js b/node_modules/mapbox-gl/src/style/style_layer/circle_style_layer_properties.js new file mode 100644 index 0000000000000000000000000000000000000000..5b8224423bb53b2adfba3e19f1d52ffddfcc8a8f --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/circle_style_layer_properties.js @@ -0,0 +1,63 @@ +// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`. +// @flow +/* eslint-disable */ + +import styleSpec from '../../style-spec/reference/latest'; + +import { + Properties, + DataConstantProperty, + DataDrivenProperty, + CrossFadedDataDrivenProperty, + CrossFadedProperty, + ColorRampProperty +} from '../properties'; + +import type Color from '../../style-spec/util/color'; + +import type Formatted from '../../style-spec/expression/types/formatted'; + +import type ResolvedImage from '../../style-spec/expression/types/resolved_image'; + +export type LayoutProps = {| + "circle-sort-key": DataDrivenProperty, +|}; + +const layout: Properties = new Properties({ + "circle-sort-key": new DataDrivenProperty(styleSpec["layout_circle"]["circle-sort-key"]), +}); + +export type PaintProps = {| + "circle-radius": DataDrivenProperty, + "circle-color": DataDrivenProperty, + "circle-blur": DataDrivenProperty, + "circle-opacity": DataDrivenProperty, + "circle-translate": DataConstantProperty<[number, number]>, + "circle-translate-anchor": DataConstantProperty<"map" | "viewport">, + "circle-pitch-scale": DataConstantProperty<"map" | "viewport">, + "circle-pitch-alignment": DataConstantProperty<"map" | "viewport">, + "circle-stroke-width": DataDrivenProperty, + "circle-stroke-color": DataDrivenProperty, + "circle-stroke-opacity": DataDrivenProperty, +|}; + +const paint: Properties = new Properties({ + "circle-radius": new DataDrivenProperty(styleSpec["paint_circle"]["circle-radius"]), + "circle-color": new DataDrivenProperty(styleSpec["paint_circle"]["circle-color"]), + "circle-blur": new DataDrivenProperty(styleSpec["paint_circle"]["circle-blur"]), + "circle-opacity": new DataDrivenProperty(styleSpec["paint_circle"]["circle-opacity"]), + "circle-translate": new DataConstantProperty(styleSpec["paint_circle"]["circle-translate"]), + "circle-translate-anchor": new DataConstantProperty(styleSpec["paint_circle"]["circle-translate-anchor"]), + "circle-pitch-scale": new DataConstantProperty(styleSpec["paint_circle"]["circle-pitch-scale"]), + "circle-pitch-alignment": new DataConstantProperty(styleSpec["paint_circle"]["circle-pitch-alignment"]), + "circle-stroke-width": new DataDrivenProperty(styleSpec["paint_circle"]["circle-stroke-width"]), + "circle-stroke-color": new DataDrivenProperty(styleSpec["paint_circle"]["circle-stroke-color"]), + "circle-stroke-opacity": new DataDrivenProperty(styleSpec["paint_circle"]["circle-stroke-opacity"]), +}); + +// Note: without adding the explicit type annotation, Flow infers weaker types +// for these objects from their use in the constructor to StyleLayer, as +// {layout?: Properties<...>, paint: Properties<...>} +export default ({ paint, layout }: $Exact<{ + paint: Properties, layout: Properties +}>); diff --git a/node_modules/mapbox-gl/src/style/style_layer/custom_style_layer.js b/node_modules/mapbox-gl/src/style/style_layer/custom_style_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..87afc2af2290fdcc6179c5beab5cc8944f44169c --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/custom_style_layer.js @@ -0,0 +1,223 @@ +// @flow + +import StyleLayer from '../style_layer'; +import type Map from '../../ui/map'; +import assert from 'assert'; + +type CustomRenderMethod = (gl: WebGLRenderingContext, matrix: Array) => void; + +/** + * Interface for custom style layers. This is a specification for + * implementers to model: it is not an exported method or class. + * + * Custom layers allow a user to render directly into the map's GL context using the map's camera. + * These layers can be added between any regular layers using {@link Map#addLayer}. + * + * Custom layers must have a unique `id` and must have the `type` of `"custom"`. + * They must implement `render` and may implement `prerender`, `onAdd` and `onRemove`. + * They can trigger rendering using {@link Map#triggerRepaint} + * and they should appropriately handle {@link Map.event:webglcontextlost} and + * {@link Map.event:webglcontextrestored}. + * + * The `renderingMode` property controls whether the layer is treated as a `"2d"` or `"3d"` map layer. Use: + * - `"renderingMode": "3d"` to use the depth buffer and share it with other layers + * - `"renderingMode": "2d"` to add a layer with no depth. If you need to use the depth buffer for a `"2d"` layer you must use an offscreen + * framebuffer and {@link CustomLayerInterface#prerender} + * + * @interface CustomLayerInterface + * @property {string} id A unique layer id. + * @property {string} type The layer's type. Must be `"custom"`. + * @property {string} renderingMode Either `"2d"` or `"3d"`. Defaults to `"2d"`. + * @example + * // Custom layer implemented as ES6 class + * class NullIslandLayer { + * constructor() { + * this.id = 'null-island'; + * this.type = 'custom'; + * this.renderingMode = '2d'; + * } + * + * onAdd(map, gl) { + * const vertexSource = ` + * uniform mat4 u_matrix; + * void main() { + * gl_Position = u_matrix * vec4(0.5, 0.5, 0.0, 1.0); + * gl_PointSize = 20.0; + * }`; + * + * const fragmentSource = ` + * void main() { + * gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); + * }`; + * + * const vertexShader = gl.createShader(gl.VERTEX_SHADER); + * gl.shaderSource(vertexShader, vertexSource); + * gl.compileShader(vertexShader); + * const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); + * gl.shaderSource(fragmentShader, fragmentSource); + * gl.compileShader(fragmentShader); + * + * this.program = gl.createProgram(); + * gl.attachShader(this.program, vertexShader); + * gl.attachShader(this.program, fragmentShader); + * gl.linkProgram(this.program); + * } + * + * render(gl, matrix) { + * gl.useProgram(this.program); + * gl.uniformMatrix4fv(gl.getUniformLocation(this.program, "u_matrix"), false, matrix); + * gl.drawArrays(gl.POINTS, 0, 1); + * } + * } + * + * map.on('load', function() { + * map.addLayer(new NullIslandLayer()); + * }); + */ + +/** + * Optional method called when the layer has been added to the Map with {@link Map#addLayer}. This + * gives the layer a chance to initialize gl resources and register event listeners. + * + * @function + * @memberof CustomLayerInterface + * @instance + * @name onAdd + * @param {Map} map The Map this custom layer was just added to. + * @param {WebGLRenderingContext} gl The gl context for the map. + */ + +/** + * Optional method called when the layer has been removed from the Map with {@link Map#removeLayer}. This + * gives the layer a chance to clean up gl resources and event listeners. + * + * @function + * @memberof CustomLayerInterface + * @instance + * @name onRemove + * @param {Map} map The Map this custom layer was just added to. + * @param {WebGLRenderingContext} gl The gl context for the map. + */ + +/** + * Optional method called during a render frame to allow a layer to prepare resources or render into a texture. + * + * The layer cannot make any assumptions about the current GL state and must bind a framebuffer before rendering. + * + * @function + * @memberof CustomLayerInterface + * @instance + * @name prerender + * @param {WebGLRenderingContext} gl The map's gl context. + * @param {Array} matrix The map's camera matrix. It projects spherical mercator + * coordinates to gl coordinates. The mercator coordinate `[0, 0]` represents the + * top left corner of the mercator world and `[1, 1]` represents the bottom right corner. When + * the `renderingMode` is `"3d"`, the z coordinate is conformal. A box with identical x, y, and z + * lengths in mercator units would be rendered as a cube. {@link MercatorCoordinate}.fromLngLat + * can be used to project a `LngLat` to a mercator coordinate. + */ + +/** + * Called during a render frame allowing the layer to draw into the GL context. + * + * The layer can assume blending and depth state is set to allow the layer to properly + * blend and clip other layers. The layer cannot make any other assumptions about the + * current GL state. + * + * If the layer needs to render to a texture, it should implement the `prerender` method + * to do this and only use the `render` method for drawing directly into the main framebuffer. + * + * The blend function is set to `gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`. This expects + * colors to be provided in premultiplied alpha form where the `r`, `g` and `b` values are already + * multiplied by the `a` value. If you are unable to provide colors in premultiplied form you + * may want to change the blend function to + * `gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`. + * + * @function + * @memberof CustomLayerInterface + * @instance + * @name render + * @param {WebGLRenderingContext} gl The map's gl context. + * @param {Array} matrix The map's camera matrix. It projects spherical mercator + * coordinates to gl coordinates. The spherical mercator coordinate `[0, 0]` represents the + * top left corner of the mercator world and `[1, 1]` represents the bottom right corner. When + * the `renderingMode` is `"3d"`, the z coordinate is conformal. A box with identical x, y, and z + * lengths in mercator units would be rendered as a cube. {@link MercatorCoordinate}.fromLngLat + * can be used to project a `LngLat` to a mercator coordinate. + */ +export type CustomLayerInterface = { + id: string, + type: "custom", + renderingMode: "2d" | "3d", + render: CustomRenderMethod, + prerender: ?CustomRenderMethod, + onAdd: ?(map: Map, gl: WebGLRenderingContext) => void, + onRemove: ?(map: Map, gl: WebGLRenderingContext) => void +} + +export function validateCustomStyleLayer(layerObject: CustomLayerInterface) { + const errors = []; + const id = layerObject.id; + + if (id === undefined) { + errors.push({ + message: `layers.${id}: missing required property "id"` + }); + } + + if (layerObject.render === undefined) { + errors.push({ + message: `layers.${id}: missing required method "render"` + }); + } + + if (layerObject.renderingMode && + layerObject.renderingMode !== '2d' && + layerObject.renderingMode !== '3d') { + errors.push({ + message: `layers.${id}: property "renderingMode" must be either "2d" or "3d"` + }); + } + + return errors; +} + +class CustomStyleLayer extends StyleLayer { + + implementation: CustomLayerInterface; + + constructor(implementation: CustomLayerInterface) { + super(implementation, {}); + this.implementation = implementation; + } + + is3D() { + return this.implementation.renderingMode === '3d'; + } + + hasOffscreenPass() { + return this.implementation.prerender !== undefined; + } + + recalculate() {} + updateTransitions() {} + hasTransition() {} + + serialize() { + assert(false, "Custom layers cannot be serialized"); + } + + onAdd(map: Map) { + if (this.implementation.onAdd) { + this.implementation.onAdd(map, map.painter.context.gl); + } + } + + onRemove(map: Map) { + if (this.implementation.onRemove) { + this.implementation.onRemove(map, map.painter.context.gl); + } + } +} + +export default CustomStyleLayer; diff --git a/node_modules/mapbox-gl/src/style/style_layer/fill_extrusion_style_layer.js b/node_modules/mapbox-gl/src/style/style_layer/fill_extrusion_style_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..900879b811856fd1fbda424123f53f34b03708c7 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/fill_extrusion_style_layer.js @@ -0,0 +1,224 @@ +// @flow + +import StyleLayer from '../style_layer'; + +import FillExtrusionBucket from '../../data/bucket/fill_extrusion_bucket'; +import {polygonIntersectsPolygon, polygonIntersectsMultiPolygon} from '../../util/intersection_tests'; +import {translateDistance, translate} from '../query_utils'; +import properties from './fill_extrusion_style_layer_properties'; +import {Transitionable, Transitioning, PossiblyEvaluated} from '../properties'; +import {vec4} from 'gl-matrix'; +import Point from '@mapbox/point-geometry'; + +import type {FeatureState} from '../../style-spec/expression'; +import type {BucketParameters} from '../../data/bucket'; +import type {PaintProps} from './fill_extrusion_style_layer_properties'; +import type Transform from '../../geo/transform'; +import type {LayerSpecification} from '../../style-spec/types'; + +class FillExtrusionStyleLayer extends StyleLayer { + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + + constructor(layer: LayerSpecification) { + super(layer, properties); + } + + createBucket(parameters: BucketParameters) { + return new FillExtrusionBucket(parameters); + } + + queryRadius(): number { + return translateDistance(this.paint.get('fill-extrusion-translate')); + } + + is3D(): boolean { + return true; + } + + queryIntersectsFeature(queryGeometry: Array, + feature: VectorTileFeature, + featureState: FeatureState, + geometry: Array>, + zoom: number, + transform: Transform, + pixelsToTileUnits: number, + pixelPosMatrix: Float32Array): boolean | number { + + const translatedPolygon = translate(queryGeometry, + this.paint.get('fill-extrusion-translate'), + this.paint.get('fill-extrusion-translate-anchor'), + transform.angle, pixelsToTileUnits); + + const height = this.paint.get('fill-extrusion-height').evaluate(feature, featureState); + const base = this.paint.get('fill-extrusion-base').evaluate(feature, featureState); + + const projectedQueryGeometry = projectQueryGeometry(translatedPolygon, pixelPosMatrix, transform, 0); + + const projected = projectExtrusion(geometry, base, height, pixelPosMatrix); + const projectedBase = projected[0]; + const projectedTop = projected[1]; + return checkIntersection(projectedBase, projectedTop, projectedQueryGeometry); + } +} + +function dot(a, b) { + return a.x * b.x + a.y * b.y; +} + +export function getIntersectionDistance(projectedQueryGeometry: Array, projectedFace: Array) { + + if (projectedQueryGeometry.length === 1) { + // For point queries calculate the z at which the point intersects the face + // using barycentric coordinates. + + // Find the barycentric coordinates of the projected point within the first + // triangle of the face, using only the xy plane. It doesn't matter if the + // point is outside the first triangle because all the triangles in the face + // are in the same plane. + // + // Check whether points are coincident and use other points if they are. + let i = 0; + const a = projectedFace[i++]; + let b; + while (!b || a.equals(b)) { + b = projectedFace[i++]; + if (!b) return Infinity; + } + + // Loop until point `c` is not colinear with points `a` and `b`. + for (; i < projectedFace.length; i++) { + const c = projectedFace[i]; + + const p = projectedQueryGeometry[0]; + + const ab = b.sub(a); + const ac = c.sub(a); + const ap = p.sub(a); + + const dotABAB = dot(ab, ab); + const dotABAC = dot(ab, ac); + const dotACAC = dot(ac, ac); + const dotAPAB = dot(ap, ab); + const dotAPAC = dot(ap, ac); + const denom = dotABAB * dotACAC - dotABAC * dotABAC; + + const v = (dotACAC * dotAPAB - dotABAC * dotAPAC) / denom; + const w = (dotABAB * dotAPAC - dotABAC * dotAPAB) / denom; + const u = 1 - v - w; + + // Use the barycentric weighting along with the original triangle z coordinates to get the point of intersection. + const distance = a.z * u + b.z * v + c.z * w; + + if (isFinite(distance)) return distance; + } + + return Infinity; + + } else { + // The counts as closest is less clear when the query is a box. This + // returns the distance to the nearest point on the face, whether it is + // within the query or not. It could be more correct to return the + // distance to the closest point within the query box but this would be + // more complicated and expensive to calculate with little benefit. + let closestDistance = Infinity; + for (const p of projectedFace) { + closestDistance = Math.min(closestDistance, p.z); + } + return closestDistance; + } +} + +function checkIntersection(projectedBase: Array, projectedTop: Array, projectedQueryGeometry: Array) { + let closestDistance = Infinity; + + if (polygonIntersectsMultiPolygon(projectedQueryGeometry, projectedTop)) { + closestDistance = getIntersectionDistance(projectedQueryGeometry, projectedTop[0]); + } + + for (let r = 0; r < projectedTop.length; r++) { + const ringTop = projectedTop[r]; + const ringBase = projectedBase[r]; + for (let p = 0; p < ringTop.length - 1; p++) { + const topA = ringTop[p]; + const topB = ringTop[p + 1]; + const baseA = ringBase[p]; + const baseB = ringBase[p + 1]; + const face = [topA, topB, baseB, baseA, topA]; + if (polygonIntersectsPolygon(projectedQueryGeometry, face)) { + closestDistance = Math.min(closestDistance, getIntersectionDistance(projectedQueryGeometry, face)); + } + } + } + + return closestDistance === Infinity ? false : closestDistance; +} + +/* + * Project the geometry using matrix `m`. This is essentially doing + * `vec4.transformMat4([], [p.x, p.y, z, 1], m)` but the multiplication + * is inlined so that parts of the projection that are the same across + * different points can only be done once. This produced a measurable + * performance improvement. + */ +function projectExtrusion(geometry: Array>, zBase: number, zTop: number, m: Float32Array) { + const projectedBase = []; + const projectedTop = []; + + const baseXZ = m[8] * zBase; + const baseYZ = m[9] * zBase; + const baseZZ = m[10] * zBase; + const baseWZ = m[11] * zBase; + const topXZ = m[8] * zTop; + const topYZ = m[9] * zTop; + const topZZ = m[10] * zTop; + const topWZ = m[11] * zTop; + + for (const r of geometry) { + const ringBase = []; + const ringTop = []; + for (const p of r) { + const x = p.x; + const y = p.y; + + const sX = m[0] * x + m[4] * y + m[12]; + const sY = m[1] * x + m[5] * y + m[13]; + const sZ = m[2] * x + m[6] * y + m[14]; + const sW = m[3] * x + m[7] * y + m[15]; + + const baseX = sX + baseXZ; + const baseY = sY + baseYZ; + const baseZ = sZ + baseZZ; + const baseW = sW + baseWZ; + + const topX = sX + topXZ; + const topY = sY + topYZ; + const topZ = sZ + topZZ; + const topW = sW + topWZ; + + const b = new Point(baseX / baseW, baseY / baseW); + b.z = baseZ / baseW; + ringBase.push(b); + + const t = new Point(topX / topW, topY / topW); + t.z = topZ / topW; + ringTop.push(t); + } + projectedBase.push(ringBase); + projectedTop.push(ringTop); + } + return [projectedBase, projectedTop]; +} + +function projectQueryGeometry(queryGeometry: Array, pixelPosMatrix: Float32Array, transform: Transform, z: number) { + const projectedQueryGeometry = []; + for (const p of queryGeometry) { + const v = [p.x, p.y, z, 1]; + vec4.transformMat4(v, v, pixelPosMatrix); + projectedQueryGeometry.push(new Point(v[0] / v[3], v[1] / v[3])); + } + return projectedQueryGeometry; +} + +export default FillExtrusionStyleLayer; diff --git a/node_modules/mapbox-gl/src/style/style_layer/fill_extrusion_style_layer_properties.js b/node_modules/mapbox-gl/src/style/style_layer/fill_extrusion_style_layer_properties.js new file mode 100644 index 0000000000000000000000000000000000000000..7118f9063385d9e762bef06c285429618a8a824d --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/fill_extrusion_style_layer_properties.js @@ -0,0 +1,50 @@ +// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`. +// @flow +/* eslint-disable */ + +import styleSpec from '../../style-spec/reference/latest'; + +import { + Properties, + DataConstantProperty, + DataDrivenProperty, + CrossFadedDataDrivenProperty, + CrossFadedProperty, + ColorRampProperty +} from '../properties'; + +import type Color from '../../style-spec/util/color'; + +import type Formatted from '../../style-spec/expression/types/formatted'; + +import type ResolvedImage from '../../style-spec/expression/types/resolved_image'; + + +export type PaintProps = {| + "fill-extrusion-opacity": DataConstantProperty, + "fill-extrusion-color": DataDrivenProperty, + "fill-extrusion-translate": DataConstantProperty<[number, number]>, + "fill-extrusion-translate-anchor": DataConstantProperty<"map" | "viewport">, + "fill-extrusion-pattern": CrossFadedDataDrivenProperty, + "fill-extrusion-height": DataDrivenProperty, + "fill-extrusion-base": DataDrivenProperty, + "fill-extrusion-vertical-gradient": DataConstantProperty, +|}; + +const paint: Properties = new Properties({ + "fill-extrusion-opacity": new DataConstantProperty(styleSpec["paint_fill-extrusion"]["fill-extrusion-opacity"]), + "fill-extrusion-color": new DataDrivenProperty(styleSpec["paint_fill-extrusion"]["fill-extrusion-color"]), + "fill-extrusion-translate": new DataConstantProperty(styleSpec["paint_fill-extrusion"]["fill-extrusion-translate"]), + "fill-extrusion-translate-anchor": new DataConstantProperty(styleSpec["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]), + "fill-extrusion-pattern": new CrossFadedDataDrivenProperty(styleSpec["paint_fill-extrusion"]["fill-extrusion-pattern"]), + "fill-extrusion-height": new DataDrivenProperty(styleSpec["paint_fill-extrusion"]["fill-extrusion-height"]), + "fill-extrusion-base": new DataDrivenProperty(styleSpec["paint_fill-extrusion"]["fill-extrusion-base"]), + "fill-extrusion-vertical-gradient": new DataConstantProperty(styleSpec["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"]), +}); + +// Note: without adding the explicit type annotation, Flow infers weaker types +// for these objects from their use in the constructor to StyleLayer, as +// {layout?: Properties<...>, paint: Properties<...>} +export default ({ paint }: $Exact<{ + paint: Properties +}>); diff --git a/node_modules/mapbox-gl/src/style/style_layer/fill_style_layer.js b/node_modules/mapbox-gl/src/style/style_layer/fill_style_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..7afb6bca33df8822601f821d1c7bad3b4de914ef --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/fill_style_layer.js @@ -0,0 +1,67 @@ +// @flow + +import StyleLayer from '../style_layer'; + +import FillBucket from '../../data/bucket/fill_bucket'; +import {polygonIntersectsMultiPolygon} from '../../util/intersection_tests'; +import {translateDistance, translate} from '../query_utils'; +import properties from './fill_style_layer_properties'; +import {Transitionable, Transitioning, Layout, PossiblyEvaluated} from '../properties'; + +import type {FeatureState} from '../../style-spec/expression'; +import type {BucketParameters} from '../../data/bucket'; +import type Point from '@mapbox/point-geometry'; +import type {LayoutProps, PaintProps} from './fill_style_layer_properties'; +import type EvaluationParameters from '../evaluation_parameters'; +import type Transform from '../../geo/transform'; +import type {LayerSpecification} from '../../style-spec/types'; + +class FillStyleLayer extends StyleLayer { + _unevaluatedLayout: Layout; + layout: PossiblyEvaluated; + + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + + constructor(layer: LayerSpecification) { + super(layer, properties); + } + + recalculate(parameters: EvaluationParameters, availableImages: Array) { + super.recalculate(parameters, availableImages); + + const outlineColor = this.paint._values['fill-outline-color']; + if (outlineColor.value.kind === 'constant' && outlineColor.value.value === undefined) { + this.paint._values['fill-outline-color'] = this.paint._values['fill-color']; + } + } + + createBucket(parameters: BucketParameters<*>) { + return new FillBucket(parameters); + } + + queryRadius(): number { + return translateDistance(this.paint.get('fill-translate')); + } + + queryIntersectsFeature(queryGeometry: Array, + feature: VectorTileFeature, + featureState: FeatureState, + geometry: Array>, + zoom: number, + transform: Transform, + pixelsToTileUnits: number): boolean { + const translatedPolygon = translate(queryGeometry, + this.paint.get('fill-translate'), + this.paint.get('fill-translate-anchor'), + transform.angle, pixelsToTileUnits); + return polygonIntersectsMultiPolygon(translatedPolygon, geometry); + } + + isTileClipped() { + return true; + } +} + +export default FillStyleLayer; diff --git a/node_modules/mapbox-gl/src/style/style_layer/fill_style_layer_properties.js b/node_modules/mapbox-gl/src/style/style_layer/fill_style_layer_properties.js new file mode 100644 index 0000000000000000000000000000000000000000..55ff413208dfb71aca7fb945a1a043edbbd65a16 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/fill_style_layer_properties.js @@ -0,0 +1,55 @@ +// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`. +// @flow +/* eslint-disable */ + +import styleSpec from '../../style-spec/reference/latest'; + +import { + Properties, + DataConstantProperty, + DataDrivenProperty, + CrossFadedDataDrivenProperty, + CrossFadedProperty, + ColorRampProperty +} from '../properties'; + +import type Color from '../../style-spec/util/color'; + +import type Formatted from '../../style-spec/expression/types/formatted'; + +import type ResolvedImage from '../../style-spec/expression/types/resolved_image'; + +export type LayoutProps = {| + "fill-sort-key": DataDrivenProperty, +|}; + +const layout: Properties = new Properties({ + "fill-sort-key": new DataDrivenProperty(styleSpec["layout_fill"]["fill-sort-key"]), +}); + +export type PaintProps = {| + "fill-antialias": DataConstantProperty, + "fill-opacity": DataDrivenProperty, + "fill-color": DataDrivenProperty, + "fill-outline-color": DataDrivenProperty, + "fill-translate": DataConstantProperty<[number, number]>, + "fill-translate-anchor": DataConstantProperty<"map" | "viewport">, + "fill-pattern": CrossFadedDataDrivenProperty, +|}; + +const paint: Properties = new Properties({ + "fill-antialias": new DataConstantProperty(styleSpec["paint_fill"]["fill-antialias"]), + "fill-opacity": new DataDrivenProperty(styleSpec["paint_fill"]["fill-opacity"]), + "fill-color": new DataDrivenProperty(styleSpec["paint_fill"]["fill-color"]), + "fill-outline-color": new DataDrivenProperty(styleSpec["paint_fill"]["fill-outline-color"]), + "fill-translate": new DataConstantProperty(styleSpec["paint_fill"]["fill-translate"]), + "fill-translate-anchor": new DataConstantProperty(styleSpec["paint_fill"]["fill-translate-anchor"]), + "fill-pattern": new CrossFadedDataDrivenProperty(styleSpec["paint_fill"]["fill-pattern"]), +}); + +// Note: without adding the explicit type annotation, Flow infers weaker types +// for these objects from their use in the constructor to StyleLayer, as +// {layout?: Properties<...>, paint: Properties<...>} +export default ({ paint, layout }: $Exact<{ + paint: Properties, layout: Properties +}>); diff --git a/node_modules/mapbox-gl/src/style/style_layer/heatmap_style_layer.js b/node_modules/mapbox-gl/src/style/style_layer/heatmap_style_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..a8f115c798e6c0876bc7e77d13137fba47162886 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/heatmap_style_layer.js @@ -0,0 +1,73 @@ +// @flow + +import StyleLayer from '../style_layer'; + +import HeatmapBucket from '../../data/bucket/heatmap_bucket'; +import {RGBAImage} from '../../util/image'; +import properties from './heatmap_style_layer_properties'; +import {renderColorRamp} from '../../util/color_ramp'; +import {Transitionable, Transitioning, PossiblyEvaluated} from '../properties'; + +import type Texture from '../../render/texture'; +import type Framebuffer from '../../gl/framebuffer'; +import type {PaintProps} from './heatmap_style_layer_properties'; +import type {LayerSpecification} from '../../style-spec/types'; + +class HeatmapStyleLayer extends StyleLayer { + + heatmapFbo: ?Framebuffer; + colorRamp: RGBAImage; + colorRampTexture: ?Texture; + + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + + createBucket(options: any) { + return new HeatmapBucket(options); + } + + constructor(layer: LayerSpecification) { + super(layer, properties); + + // make sure color ramp texture is generated for default heatmap color too + this._updateColorRamp(); + } + + _handleSpecialPaintPropertyUpdate(name: string) { + if (name === 'heatmap-color') { + this._updateColorRamp(); + } + } + + _updateColorRamp() { + const expression = this._transitionablePaint._values['heatmap-color'].value.expression; + this.colorRamp = renderColorRamp({ + expression, + evaluationKey: 'heatmapDensity', + image: this.colorRamp + }); + this.colorRampTexture = null; + } + + resize() { + if (this.heatmapFbo) { + this.heatmapFbo.destroy(); + this.heatmapFbo = null; + } + } + + queryRadius(): number { + return 0; + } + + queryIntersectsFeature(): boolean { + return false; + } + + hasOffscreenPass() { + return this.paint.get('heatmap-opacity') !== 0 && this.visibility !== 'none'; + } +} + +export default HeatmapStyleLayer; diff --git a/node_modules/mapbox-gl/src/style/style_layer/heatmap_style_layer_properties.js b/node_modules/mapbox-gl/src/style/style_layer/heatmap_style_layer_properties.js new file mode 100644 index 0000000000000000000000000000000000000000..53bdaf3baa3a8de8310fae669c491d4f11ed705e --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/heatmap_style_layer_properties.js @@ -0,0 +1,44 @@ +// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`. +// @flow +/* eslint-disable */ + +import styleSpec from '../../style-spec/reference/latest'; + +import { + Properties, + DataConstantProperty, + DataDrivenProperty, + CrossFadedDataDrivenProperty, + CrossFadedProperty, + ColorRampProperty +} from '../properties'; + +import type Color from '../../style-spec/util/color'; + +import type Formatted from '../../style-spec/expression/types/formatted'; + +import type ResolvedImage from '../../style-spec/expression/types/resolved_image'; + + +export type PaintProps = {| + "heatmap-radius": DataDrivenProperty, + "heatmap-weight": DataDrivenProperty, + "heatmap-intensity": DataConstantProperty, + "heatmap-color": ColorRampProperty, + "heatmap-opacity": DataConstantProperty, +|}; + +const paint: Properties = new Properties({ + "heatmap-radius": new DataDrivenProperty(styleSpec["paint_heatmap"]["heatmap-radius"]), + "heatmap-weight": new DataDrivenProperty(styleSpec["paint_heatmap"]["heatmap-weight"]), + "heatmap-intensity": new DataConstantProperty(styleSpec["paint_heatmap"]["heatmap-intensity"]), + "heatmap-color": new ColorRampProperty(styleSpec["paint_heatmap"]["heatmap-color"]), + "heatmap-opacity": new DataConstantProperty(styleSpec["paint_heatmap"]["heatmap-opacity"]), +}); + +// Note: without adding the explicit type annotation, Flow infers weaker types +// for these objects from their use in the constructor to StyleLayer, as +// {layout?: Properties<...>, paint: Properties<...>} +export default ({ paint }: $Exact<{ + paint: Properties +}>); diff --git a/node_modules/mapbox-gl/src/style/style_layer/hillshade_style_layer.js b/node_modules/mapbox-gl/src/style/style_layer/hillshade_style_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..782ebe3d564837639f85389b3fdf92a8b6c31923 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/hillshade_style_layer.js @@ -0,0 +1,25 @@ +// @flow + +import StyleLayer from '../style_layer'; + +import properties from './hillshade_style_layer_properties'; +import {Transitionable, Transitioning, PossiblyEvaluated} from '../properties'; + +import type {PaintProps} from './hillshade_style_layer_properties'; +import type {LayerSpecification} from '../../style-spec/types'; + +class HillshadeStyleLayer extends StyleLayer { + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + + constructor(layer: LayerSpecification) { + super(layer, properties); + } + + hasOffscreenPass() { + return this.paint.get('hillshade-exaggeration') !== 0 && this.visibility !== 'none'; + } +} + +export default HillshadeStyleLayer; diff --git a/node_modules/mapbox-gl/src/style/style_layer/hillshade_style_layer_properties.js b/node_modules/mapbox-gl/src/style/style_layer/hillshade_style_layer_properties.js new file mode 100644 index 0000000000000000000000000000000000000000..7a82d3e36a3e595f4f45dc224957a1ad6287b9a6 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/hillshade_style_layer_properties.js @@ -0,0 +1,46 @@ +// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`. +// @flow +/* eslint-disable */ + +import styleSpec from '../../style-spec/reference/latest'; + +import { + Properties, + DataConstantProperty, + DataDrivenProperty, + CrossFadedDataDrivenProperty, + CrossFadedProperty, + ColorRampProperty +} from '../properties'; + +import type Color from '../../style-spec/util/color'; + +import type Formatted from '../../style-spec/expression/types/formatted'; + +import type ResolvedImage from '../../style-spec/expression/types/resolved_image'; + + +export type PaintProps = {| + "hillshade-illumination-direction": DataConstantProperty, + "hillshade-illumination-anchor": DataConstantProperty<"map" | "viewport">, + "hillshade-exaggeration": DataConstantProperty, + "hillshade-shadow-color": DataConstantProperty, + "hillshade-highlight-color": DataConstantProperty, + "hillshade-accent-color": DataConstantProperty, +|}; + +const paint: Properties = new Properties({ + "hillshade-illumination-direction": new DataConstantProperty(styleSpec["paint_hillshade"]["hillshade-illumination-direction"]), + "hillshade-illumination-anchor": new DataConstantProperty(styleSpec["paint_hillshade"]["hillshade-illumination-anchor"]), + "hillshade-exaggeration": new DataConstantProperty(styleSpec["paint_hillshade"]["hillshade-exaggeration"]), + "hillshade-shadow-color": new DataConstantProperty(styleSpec["paint_hillshade"]["hillshade-shadow-color"]), + "hillshade-highlight-color": new DataConstantProperty(styleSpec["paint_hillshade"]["hillshade-highlight-color"]), + "hillshade-accent-color": new DataConstantProperty(styleSpec["paint_hillshade"]["hillshade-accent-color"]), +}); + +// Note: without adding the explicit type annotation, Flow infers weaker types +// for these objects from their use in the constructor to StyleLayer, as +// {layout?: Properties<...>, paint: Properties<...>} +export default ({ paint }: $Exact<{ + paint: Properties +}>); diff --git a/node_modules/mapbox-gl/src/style/style_layer/layer_properties.js.ejs b/node_modules/mapbox-gl/src/style/style_layer/layer_properties.js.ejs new file mode 100644 index 0000000000000000000000000000000000000000..497242d7c23b14780f2848d1509c90925132789f --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/layer_properties.js.ejs @@ -0,0 +1,69 @@ +<% + const type = locals.type; + const layoutProperties = locals.layoutProperties; + const paintProperties = locals.paintProperties; +-%> +// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`. +// @flow +/* eslint-disable */ + +import styleSpec from '../../style-spec/reference/latest'; + +import { + Properties, + DataConstantProperty, + DataDrivenProperty, + CrossFadedDataDrivenProperty, + CrossFadedProperty, + ColorRampProperty +} from '../properties'; + +import type Color from '../../style-spec/util/color'; + +import type Formatted from '../../style-spec/expression/types/formatted'; + +import type ResolvedImage from '../../style-spec/expression/types/resolved_image'; +<% +const overridables = paintProperties.filter(p => p.overridable) +if (overridables.length) { -%> + +import { + <%= overridables.reduce((imports, prop) => { imports.push(runtimeType(prop)); return imports; }, []).join(',\n\t'); -%> + +} from '../../style-spec/expression/types'; +<% } -%> + +<% if (layoutProperties.length) { -%> +export type LayoutProps = {| +<% for (const property of layoutProperties) { -%> + "<%= property.name %>": <%- propertyType(property) %>, +<% } -%> +|}; + +const layout: Properties = new Properties({ +<% for (const property of layoutProperties) { -%> + "<%= property.name %>": <%- propertyValue(property, 'layout') %>, +<% } -%> +}); +<% } -%> +<% if(paintProperties.length){ %> +export type PaintProps = {| +<% for (const property of paintProperties) { -%> + "<%= property.name %>": <%- propertyType(property) %>, +<% } -%> +|}; +<% } else{ %> +export type PaintProps = {}; +<% } %> +const paint: Properties = new Properties({ +<% for (const property of paintProperties) { -%> + "<%= property.name %>": <%- propertyValue(property, 'paint') %>, +<% } -%> +}); + +// Note: without adding the explicit type annotation, Flow infers weaker types +// for these objects from their use in the constructor to StyleLayer, as +// {layout?: Properties<...>, paint: Properties<...>} +export default ({ paint<% if (layoutProperties.length) { %>, layout<% } %> }: $Exact<{ + paint: Properties<% if (layoutProperties.length) { %>, layout: Properties<% } %> +}>); diff --git a/node_modules/mapbox-gl/src/style/style_layer/line_style_layer.js b/node_modules/mapbox-gl/src/style/style_layer/line_style_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..480975c7428b173894692b976ebbdb5a43101ffd --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/line_style_layer.js @@ -0,0 +1,150 @@ +// @flow + +import Point from '@mapbox/point-geometry'; + +import StyleLayer from '../style_layer'; +import LineBucket from '../../data/bucket/line_bucket'; +import {polygonIntersectsBufferedMultiLine} from '../../util/intersection_tests'; +import {getMaximumPaintValue, translateDistance, translate} from '../query_utils'; +import properties from './line_style_layer_properties'; +import {extend, MAX_SAFE_INTEGER} from '../../util/util'; +import EvaluationParameters from '../evaluation_parameters'; +import {Transitionable, Transitioning, Layout, PossiblyEvaluated, DataDrivenProperty} from '../properties'; + +import Step from '../../style-spec/expression/definitions/step'; +import type {FeatureState, ZoomConstantExpression} from '../../style-spec/expression'; +import type {Bucket, BucketParameters} from '../../data/bucket'; +import type {LayoutProps, PaintProps} from './line_style_layer_properties'; +import type Transform from '../../geo/transform'; +import type {LayerSpecification} from '../../style-spec/types'; + +class LineFloorwidthProperty extends DataDrivenProperty { + useIntegerZoom: true; + + possiblyEvaluate(value, parameters) { + parameters = new EvaluationParameters(Math.floor(parameters.zoom), { + now: parameters.now, + fadeDuration: parameters.fadeDuration, + zoomHistory: parameters.zoomHistory, + transition: parameters.transition + }); + return super.possiblyEvaluate(value, parameters); + } + + evaluate(value, globals, feature, featureState) { + globals = extend({}, globals, {zoom: Math.floor(globals.zoom)}); + return super.evaluate(value, globals, feature, featureState); + } +} + +const lineFloorwidthProperty = new LineFloorwidthProperty(properties.paint.properties['line-width'].specification); +lineFloorwidthProperty.useIntegerZoom = true; + +class LineStyleLayer extends StyleLayer { + _unevaluatedLayout: Layout; + layout: PossiblyEvaluated; + + gradientVersion: number; + stepInterpolant: boolean; + + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + + constructor(layer: LayerSpecification) { + super(layer, properties); + this.gradientVersion = 0; + } + + _handleSpecialPaintPropertyUpdate(name: string) { + if (name === 'line-gradient') { + const expression: ZoomConstantExpression<'source'> = ((this._transitionablePaint._values['line-gradient'].value.expression): any); + this.stepInterpolant = expression._styleExpression.expression instanceof Step; + this.gradientVersion = (this.gradientVersion + 1) % MAX_SAFE_INTEGER; + } + } + + gradientExpression() { + return this._transitionablePaint._values['line-gradient'].value.expression; + } + + recalculate(parameters: EvaluationParameters, availableImages: Array) { + super.recalculate(parameters, availableImages); + + (this.paint._values: any)['line-floorwidth'] = + lineFloorwidthProperty.possiblyEvaluate(this._transitioningPaint._values['line-width'].value, parameters); + } + + createBucket(parameters: BucketParameters<*>) { + return new LineBucket(parameters); + } + + queryRadius(bucket: Bucket): number { + const lineBucket: LineBucket = (bucket: any); + const width = getLineWidth( + getMaximumPaintValue('line-width', this, lineBucket), + getMaximumPaintValue('line-gap-width', this, lineBucket)); + const offset = getMaximumPaintValue('line-offset', this, lineBucket); + return width / 2 + Math.abs(offset) + translateDistance(this.paint.get('line-translate')); + } + + queryIntersectsFeature(queryGeometry: Array, + feature: VectorTileFeature, + featureState: FeatureState, + geometry: Array>, + zoom: number, + transform: Transform, + pixelsToTileUnits: number): boolean { + const translatedPolygon = translate(queryGeometry, + this.paint.get('line-translate'), + this.paint.get('line-translate-anchor'), + transform.angle, pixelsToTileUnits); + const halfWidth = pixelsToTileUnits / 2 * getLineWidth( + this.paint.get('line-width').evaluate(feature, featureState), + this.paint.get('line-gap-width').evaluate(feature, featureState)); + const lineOffset = this.paint.get('line-offset').evaluate(feature, featureState); + if (lineOffset) { + geometry = offsetLine(geometry, lineOffset * pixelsToTileUnits); + } + + return polygonIntersectsBufferedMultiLine(translatedPolygon, geometry, halfWidth); + } + + isTileClipped() { + return true; + } +} + +export default LineStyleLayer; + +function getLineWidth(lineWidth, lineGapWidth) { + if (lineGapWidth > 0) { + return lineGapWidth + 2 * lineWidth; + } else { + return lineWidth; + } +} + +function offsetLine(rings, offset) { + const newRings = []; + const zero = new Point(0, 0); + for (let k = 0; k < rings.length; k++) { + const ring = rings[k]; + const newRing = []; + for (let i = 0; i < ring.length; i++) { + const a = ring[i - 1]; + const b = ring[i]; + const c = ring[i + 1]; + const aToB = i === 0 ? zero : b.sub(a)._unit()._perp(); + const bToC = i === ring.length - 1 ? zero : c.sub(b)._unit()._perp(); + const extrude = aToB._add(bToC)._unit(); + + const cosHalfAngle = extrude.x * bToC.x + extrude.y * bToC.y; + extrude._mult(1 / cosHalfAngle); + + newRing.push(extrude._mult(offset)._add(b)); + } + newRings.push(newRing); + } + return newRings; +} diff --git a/node_modules/mapbox-gl/src/style/style_layer/line_style_layer_properties.js b/node_modules/mapbox-gl/src/style/style_layer/line_style_layer_properties.js new file mode 100644 index 0000000000000000000000000000000000000000..55c635f71e405ac18d27242a9f0a2fdb8c6f46e1 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/line_style_layer_properties.js @@ -0,0 +1,71 @@ +// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`. +// @flow +/* eslint-disable */ + +import styleSpec from '../../style-spec/reference/latest'; + +import { + Properties, + DataConstantProperty, + DataDrivenProperty, + CrossFadedDataDrivenProperty, + CrossFadedProperty, + ColorRampProperty +} from '../properties'; + +import type Color from '../../style-spec/util/color'; + +import type Formatted from '../../style-spec/expression/types/formatted'; + +import type ResolvedImage from '../../style-spec/expression/types/resolved_image'; + +export type LayoutProps = {| + "line-cap": DataConstantProperty<"butt" | "round" | "square">, + "line-join": DataDrivenProperty<"bevel" | "round" | "miter">, + "line-miter-limit": DataConstantProperty, + "line-round-limit": DataConstantProperty, + "line-sort-key": DataDrivenProperty, +|}; + +const layout: Properties = new Properties({ + "line-cap": new DataConstantProperty(styleSpec["layout_line"]["line-cap"]), + "line-join": new DataDrivenProperty(styleSpec["layout_line"]["line-join"]), + "line-miter-limit": new DataConstantProperty(styleSpec["layout_line"]["line-miter-limit"]), + "line-round-limit": new DataConstantProperty(styleSpec["layout_line"]["line-round-limit"]), + "line-sort-key": new DataDrivenProperty(styleSpec["layout_line"]["line-sort-key"]), +}); + +export type PaintProps = {| + "line-opacity": DataDrivenProperty, + "line-color": DataDrivenProperty, + "line-translate": DataConstantProperty<[number, number]>, + "line-translate-anchor": DataConstantProperty<"map" | "viewport">, + "line-width": DataDrivenProperty, + "line-gap-width": DataDrivenProperty, + "line-offset": DataDrivenProperty, + "line-blur": DataDrivenProperty, + "line-dasharray": CrossFadedProperty>, + "line-pattern": CrossFadedDataDrivenProperty, + "line-gradient": ColorRampProperty, +|}; + +const paint: Properties = new Properties({ + "line-opacity": new DataDrivenProperty(styleSpec["paint_line"]["line-opacity"]), + "line-color": new DataDrivenProperty(styleSpec["paint_line"]["line-color"]), + "line-translate": new DataConstantProperty(styleSpec["paint_line"]["line-translate"]), + "line-translate-anchor": new DataConstantProperty(styleSpec["paint_line"]["line-translate-anchor"]), + "line-width": new DataDrivenProperty(styleSpec["paint_line"]["line-width"]), + "line-gap-width": new DataDrivenProperty(styleSpec["paint_line"]["line-gap-width"]), + "line-offset": new DataDrivenProperty(styleSpec["paint_line"]["line-offset"]), + "line-blur": new DataDrivenProperty(styleSpec["paint_line"]["line-blur"]), + "line-dasharray": new CrossFadedProperty(styleSpec["paint_line"]["line-dasharray"]), + "line-pattern": new CrossFadedDataDrivenProperty(styleSpec["paint_line"]["line-pattern"]), + "line-gradient": new ColorRampProperty(styleSpec["paint_line"]["line-gradient"]), +}); + +// Note: without adding the explicit type annotation, Flow infers weaker types +// for these objects from their use in the constructor to StyleLayer, as +// {layout?: Properties<...>, paint: Properties<...>} +export default ({ paint, layout }: $Exact<{ + paint: Properties, layout: Properties +}>); diff --git a/node_modules/mapbox-gl/src/style/style_layer/raster_style_layer.js b/node_modules/mapbox-gl/src/style/style_layer/raster_style_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..33033909cb6e57841a117eaa21557c170a7a46be --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/raster_style_layer.js @@ -0,0 +1,21 @@ +// @flow + +import StyleLayer from '../style_layer'; + +import properties from './raster_style_layer_properties'; +import {Transitionable, Transitioning, PossiblyEvaluated} from '../properties'; + +import type {PaintProps} from './raster_style_layer_properties'; +import type {LayerSpecification} from '../../style-spec/types'; + +class RasterStyleLayer extends StyleLayer { + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + + constructor(layer: LayerSpecification) { + super(layer, properties); + } +} + +export default RasterStyleLayer; diff --git a/node_modules/mapbox-gl/src/style/style_layer/raster_style_layer_properties.js b/node_modules/mapbox-gl/src/style/style_layer/raster_style_layer_properties.js new file mode 100644 index 0000000000000000000000000000000000000000..15356168308b913ff7072f5076bef140c7e41cb3 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/raster_style_layer_properties.js @@ -0,0 +1,50 @@ +// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`. +// @flow +/* eslint-disable */ + +import styleSpec from '../../style-spec/reference/latest'; + +import { + Properties, + DataConstantProperty, + DataDrivenProperty, + CrossFadedDataDrivenProperty, + CrossFadedProperty, + ColorRampProperty +} from '../properties'; + +import type Color from '../../style-spec/util/color'; + +import type Formatted from '../../style-spec/expression/types/formatted'; + +import type ResolvedImage from '../../style-spec/expression/types/resolved_image'; + + +export type PaintProps = {| + "raster-opacity": DataConstantProperty, + "raster-hue-rotate": DataConstantProperty, + "raster-brightness-min": DataConstantProperty, + "raster-brightness-max": DataConstantProperty, + "raster-saturation": DataConstantProperty, + "raster-contrast": DataConstantProperty, + "raster-resampling": DataConstantProperty<"linear" | "nearest">, + "raster-fade-duration": DataConstantProperty, +|}; + +const paint: Properties = new Properties({ + "raster-opacity": new DataConstantProperty(styleSpec["paint_raster"]["raster-opacity"]), + "raster-hue-rotate": new DataConstantProperty(styleSpec["paint_raster"]["raster-hue-rotate"]), + "raster-brightness-min": new DataConstantProperty(styleSpec["paint_raster"]["raster-brightness-min"]), + "raster-brightness-max": new DataConstantProperty(styleSpec["paint_raster"]["raster-brightness-max"]), + "raster-saturation": new DataConstantProperty(styleSpec["paint_raster"]["raster-saturation"]), + "raster-contrast": new DataConstantProperty(styleSpec["paint_raster"]["raster-contrast"]), + "raster-resampling": new DataConstantProperty(styleSpec["paint_raster"]["raster-resampling"]), + "raster-fade-duration": new DataConstantProperty(styleSpec["paint_raster"]["raster-fade-duration"]), +}); + +// Note: without adding the explicit type annotation, Flow infers weaker types +// for these objects from their use in the constructor to StyleLayer, as +// {layout?: Properties<...>, paint: Properties<...>} +export default ({ paint }: $Exact<{ + paint: Properties +}>); diff --git a/node_modules/mapbox-gl/src/style/style_layer/symbol_style_layer.js b/node_modules/mapbox-gl/src/style/style_layer/symbol_style_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..37254264509c86e244d65b5e7d8d83bb0bc43ce8 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/symbol_style_layer.js @@ -0,0 +1,190 @@ +// @flow + +import StyleLayer from '../style_layer'; + +import assert from 'assert'; +import SymbolBucket from '../../data/bucket/symbol_bucket'; +import resolveTokens from '../../util/resolve_tokens'; +import properties from './symbol_style_layer_properties'; + +import { + Transitionable, + Transitioning, + Layout, + PossiblyEvaluated, + PossiblyEvaluatedPropertyValue, + PropertyValue +} from '../properties'; + +import { + isExpression, + StyleExpression, + ZoomConstantExpression, + ZoomDependentExpression +} from '../../style-spec/expression'; + +import type {BucketParameters} from '../../data/bucket'; +import type {LayoutProps, PaintProps} from './symbol_style_layer_properties'; +import type EvaluationParameters from '../evaluation_parameters'; +import type {LayerSpecification} from '../../style-spec/types'; +import type {Feature, SourceExpression, CompositeExpression} from '../../style-spec/expression'; +import type {Expression} from '../../style-spec/expression/expression'; +import type {CanonicalTileID} from '../../source/tile_id'; +import {FormattedType} from '../../style-spec/expression/types'; +import {typeOf} from '../../style-spec/expression/values'; +import Formatted from '../../style-spec/expression/types/formatted'; +import FormatSectionOverride from '../format_section_override'; +import FormatExpression from '../../style-spec/expression/definitions/format'; +import Literal from '../../style-spec/expression/definitions/literal'; + +class SymbolStyleLayer extends StyleLayer { + _unevaluatedLayout: Layout; + layout: PossiblyEvaluated; + + _transitionablePaint: Transitionable; + _transitioningPaint: Transitioning; + paint: PossiblyEvaluated; + + constructor(layer: LayerSpecification) { + super(layer, properties); + } + + recalculate(parameters: EvaluationParameters, availableImages: Array) { + super.recalculate(parameters, availableImages); + + if (this.layout.get('icon-rotation-alignment') === 'auto') { + if (this.layout.get('symbol-placement') !== 'point') { + this.layout._values['icon-rotation-alignment'] = 'map'; + } else { + this.layout._values['icon-rotation-alignment'] = 'viewport'; + } + } + + if (this.layout.get('text-rotation-alignment') === 'auto') { + if (this.layout.get('symbol-placement') !== 'point') { + this.layout._values['text-rotation-alignment'] = 'map'; + } else { + this.layout._values['text-rotation-alignment'] = 'viewport'; + } + } + + // If unspecified, `*-pitch-alignment` inherits `*-rotation-alignment` + if (this.layout.get('text-pitch-alignment') === 'auto') { + this.layout._values['text-pitch-alignment'] = this.layout.get('text-rotation-alignment'); + } + if (this.layout.get('icon-pitch-alignment') === 'auto') { + this.layout._values['icon-pitch-alignment'] = this.layout.get('icon-rotation-alignment'); + } + + if (this.layout.get('symbol-placement') === 'point') { + const writingModes = this.layout.get('text-writing-mode'); + if (writingModes) { + // remove duplicates, preserving order + const deduped = []; + for (const m of writingModes) { + if (deduped.indexOf(m) < 0) deduped.push(m); + } + this.layout._values['text-writing-mode'] = deduped; + } else { + this.layout._values['text-writing-mode'] = ['horizontal']; + } + } + + this._setPaintOverrides(); + } + + getValueAndResolveTokens(name: *, feature: Feature, canonical: CanonicalTileID, availableImages: Array) { + const value = this.layout.get(name).evaluate(feature, {}, canonical, availableImages); + const unevaluated = this._unevaluatedLayout._values[name]; + if (!unevaluated.isDataDriven() && !isExpression(unevaluated.value) && value) { + return resolveTokens(feature.properties, value); + } + + return value; + } + + createBucket(parameters: BucketParameters<*>) { + return new SymbolBucket(parameters); + } + + queryRadius(): number { + return 0; + } + + queryIntersectsFeature(): boolean { + assert(false); // Should take a different path in FeatureIndex + return false; + } + + _setPaintOverrides() { + for (const overridable of properties.paint.overridableProperties) { + if (!SymbolStyleLayer.hasPaintOverride(this.layout, overridable)) { + continue; + } + const overriden = this.paint.get(overridable); + const override = new FormatSectionOverride(overriden); + const styleExpression = new StyleExpression(override, overriden.property.specification); + let expression = null; + if (overriden.value.kind === 'constant' || overriden.value.kind === 'source') { + expression = (new ZoomConstantExpression('source', styleExpression): SourceExpression); + } else { + expression = (new ZoomDependentExpression('composite', + styleExpression, + overriden.value.zoomStops, + overriden.value._interpolationType): CompositeExpression); + } + this.paint._values[overridable] = new PossiblyEvaluatedPropertyValue(overriden.property, + expression, + overriden.parameters); + } + } + + _handleOverridablePaintPropertyUpdate(name: string, oldValue: PropertyValue, newValue: PropertyValue): boolean { + if (!this.layout || oldValue.isDataDriven() || newValue.isDataDriven()) { + return false; + } + return SymbolStyleLayer.hasPaintOverride(this.layout, name); + } + + static hasPaintOverride(layout: PossiblyEvaluated, propertyName: string): boolean { + const textField = layout.get('text-field'); + const property = properties.paint.properties[propertyName]; + let hasOverrides = false; + + const checkSections = (sections) => { + for (const section of sections) { + if (property.overrides && property.overrides.hasOverride(section)) { + hasOverrides = true; + return; + } + } + }; + + if (textField.value.kind === 'constant' && textField.value.value instanceof Formatted) { + checkSections(textField.value.value.sections); + } else if (textField.value.kind === 'source') { + + const checkExpression = (expression: Expression) => { + if (hasOverrides) return; + + if (expression instanceof Literal && typeOf(expression.value) === FormattedType) { + const formatted: Formatted = ((expression.value): any); + checkSections(formatted.sections); + } else if (expression instanceof FormatExpression) { + checkSections(expression.sections); + } else { + expression.eachChild(checkExpression); + } + }; + + const expr: ZoomConstantExpression<'source'> = ((textField.value): any); + if (expr._styleExpression) { + checkExpression(expr._styleExpression.expression); + } + } + + return hasOverrides; + } +} + +export default SymbolStyleLayer; diff --git a/node_modules/mapbox-gl/src/style/style_layer/symbol_style_layer_properties.js b/node_modules/mapbox-gl/src/style/style_layer/symbol_style_layer_properties.js new file mode 100644 index 0000000000000000000000000000000000000000..d6df3d9974b6177ed78ac899dec85b453b2da9fb --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/symbol_style_layer_properties.js @@ -0,0 +1,153 @@ +// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`. +// @flow +/* eslint-disable */ + +import styleSpec from '../../style-spec/reference/latest'; + +import { + Properties, + DataConstantProperty, + DataDrivenProperty, + CrossFadedDataDrivenProperty, + CrossFadedProperty, + ColorRampProperty +} from '../properties'; + +import type Color from '../../style-spec/util/color'; + +import type Formatted from '../../style-spec/expression/types/formatted'; + +import type ResolvedImage from '../../style-spec/expression/types/resolved_image'; + +import { + ColorType +} from '../../style-spec/expression/types'; + +export type LayoutProps = {| + "symbol-placement": DataConstantProperty<"point" | "line" | "line-center">, + "symbol-spacing": DataConstantProperty, + "symbol-avoid-edges": DataConstantProperty, + "symbol-sort-key": DataDrivenProperty, + "symbol-z-order": DataConstantProperty<"auto" | "viewport-y" | "source">, + "icon-allow-overlap": DataConstantProperty, + "icon-ignore-placement": DataConstantProperty, + "icon-optional": DataConstantProperty, + "icon-rotation-alignment": DataConstantProperty<"map" | "viewport" | "auto">, + "icon-size": DataDrivenProperty, + "icon-text-fit": DataConstantProperty<"none" | "width" | "height" | "both">, + "icon-text-fit-padding": DataConstantProperty<[number, number, number, number]>, + "icon-image": DataDrivenProperty, + "icon-rotate": DataDrivenProperty, + "icon-padding": DataConstantProperty, + "icon-keep-upright": DataConstantProperty, + "icon-offset": DataDrivenProperty<[number, number]>, + "icon-anchor": DataDrivenProperty<"center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right">, + "icon-pitch-alignment": DataConstantProperty<"map" | "viewport" | "auto">, + "text-pitch-alignment": DataConstantProperty<"map" | "viewport" | "auto">, + "text-rotation-alignment": DataConstantProperty<"map" | "viewport" | "auto">, + "text-field": DataDrivenProperty, + "text-font": DataDrivenProperty>, + "text-size": DataDrivenProperty, + "text-max-width": DataDrivenProperty, + "text-line-height": DataConstantProperty, + "text-letter-spacing": DataDrivenProperty, + "text-justify": DataDrivenProperty<"auto" | "left" | "center" | "right">, + "text-radial-offset": DataDrivenProperty, + "text-variable-anchor": DataConstantProperty>, + "text-anchor": DataDrivenProperty<"center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right">, + "text-max-angle": DataConstantProperty, + "text-writing-mode": DataConstantProperty>, + "text-rotate": DataDrivenProperty, + "text-padding": DataConstantProperty, + "text-keep-upright": DataConstantProperty, + "text-transform": DataDrivenProperty<"none" | "uppercase" | "lowercase">, + "text-offset": DataDrivenProperty<[number, number]>, + "text-allow-overlap": DataConstantProperty, + "text-ignore-placement": DataConstantProperty, + "text-optional": DataConstantProperty, +|}; + +const layout: Properties = new Properties({ + "symbol-placement": new DataConstantProperty(styleSpec["layout_symbol"]["symbol-placement"]), + "symbol-spacing": new DataConstantProperty(styleSpec["layout_symbol"]["symbol-spacing"]), + "symbol-avoid-edges": new DataConstantProperty(styleSpec["layout_symbol"]["symbol-avoid-edges"]), + "symbol-sort-key": new DataDrivenProperty(styleSpec["layout_symbol"]["symbol-sort-key"]), + "symbol-z-order": new DataConstantProperty(styleSpec["layout_symbol"]["symbol-z-order"]), + "icon-allow-overlap": new DataConstantProperty(styleSpec["layout_symbol"]["icon-allow-overlap"]), + "icon-ignore-placement": new DataConstantProperty(styleSpec["layout_symbol"]["icon-ignore-placement"]), + "icon-optional": new DataConstantProperty(styleSpec["layout_symbol"]["icon-optional"]), + "icon-rotation-alignment": new DataConstantProperty(styleSpec["layout_symbol"]["icon-rotation-alignment"]), + "icon-size": new DataDrivenProperty(styleSpec["layout_symbol"]["icon-size"]), + "icon-text-fit": new DataConstantProperty(styleSpec["layout_symbol"]["icon-text-fit"]), + "icon-text-fit-padding": new DataConstantProperty(styleSpec["layout_symbol"]["icon-text-fit-padding"]), + "icon-image": new DataDrivenProperty(styleSpec["layout_symbol"]["icon-image"]), + "icon-rotate": new DataDrivenProperty(styleSpec["layout_symbol"]["icon-rotate"]), + "icon-padding": new DataConstantProperty(styleSpec["layout_symbol"]["icon-padding"]), + "icon-keep-upright": new DataConstantProperty(styleSpec["layout_symbol"]["icon-keep-upright"]), + "icon-offset": new DataDrivenProperty(styleSpec["layout_symbol"]["icon-offset"]), + "icon-anchor": new DataDrivenProperty(styleSpec["layout_symbol"]["icon-anchor"]), + "icon-pitch-alignment": new DataConstantProperty(styleSpec["layout_symbol"]["icon-pitch-alignment"]), + "text-pitch-alignment": new DataConstantProperty(styleSpec["layout_symbol"]["text-pitch-alignment"]), + "text-rotation-alignment": new DataConstantProperty(styleSpec["layout_symbol"]["text-rotation-alignment"]), + "text-field": new DataDrivenProperty(styleSpec["layout_symbol"]["text-field"]), + "text-font": new DataDrivenProperty(styleSpec["layout_symbol"]["text-font"]), + "text-size": new DataDrivenProperty(styleSpec["layout_symbol"]["text-size"]), + "text-max-width": new DataDrivenProperty(styleSpec["layout_symbol"]["text-max-width"]), + "text-line-height": new DataConstantProperty(styleSpec["layout_symbol"]["text-line-height"]), + "text-letter-spacing": new DataDrivenProperty(styleSpec["layout_symbol"]["text-letter-spacing"]), + "text-justify": new DataDrivenProperty(styleSpec["layout_symbol"]["text-justify"]), + "text-radial-offset": new DataDrivenProperty(styleSpec["layout_symbol"]["text-radial-offset"]), + "text-variable-anchor": new DataConstantProperty(styleSpec["layout_symbol"]["text-variable-anchor"]), + "text-anchor": new DataDrivenProperty(styleSpec["layout_symbol"]["text-anchor"]), + "text-max-angle": new DataConstantProperty(styleSpec["layout_symbol"]["text-max-angle"]), + "text-writing-mode": new DataConstantProperty(styleSpec["layout_symbol"]["text-writing-mode"]), + "text-rotate": new DataDrivenProperty(styleSpec["layout_symbol"]["text-rotate"]), + "text-padding": new DataConstantProperty(styleSpec["layout_symbol"]["text-padding"]), + "text-keep-upright": new DataConstantProperty(styleSpec["layout_symbol"]["text-keep-upright"]), + "text-transform": new DataDrivenProperty(styleSpec["layout_symbol"]["text-transform"]), + "text-offset": new DataDrivenProperty(styleSpec["layout_symbol"]["text-offset"]), + "text-allow-overlap": new DataConstantProperty(styleSpec["layout_symbol"]["text-allow-overlap"]), + "text-ignore-placement": new DataConstantProperty(styleSpec["layout_symbol"]["text-ignore-placement"]), + "text-optional": new DataConstantProperty(styleSpec["layout_symbol"]["text-optional"]), +}); + +export type PaintProps = {| + "icon-opacity": DataDrivenProperty, + "icon-color": DataDrivenProperty, + "icon-halo-color": DataDrivenProperty, + "icon-halo-width": DataDrivenProperty, + "icon-halo-blur": DataDrivenProperty, + "icon-translate": DataConstantProperty<[number, number]>, + "icon-translate-anchor": DataConstantProperty<"map" | "viewport">, + "text-opacity": DataDrivenProperty, + "text-color": DataDrivenProperty, + "text-halo-color": DataDrivenProperty, + "text-halo-width": DataDrivenProperty, + "text-halo-blur": DataDrivenProperty, + "text-translate": DataConstantProperty<[number, number]>, + "text-translate-anchor": DataConstantProperty<"map" | "viewport">, +|}; + +const paint: Properties = new Properties({ + "icon-opacity": new DataDrivenProperty(styleSpec["paint_symbol"]["icon-opacity"]), + "icon-color": new DataDrivenProperty(styleSpec["paint_symbol"]["icon-color"]), + "icon-halo-color": new DataDrivenProperty(styleSpec["paint_symbol"]["icon-halo-color"]), + "icon-halo-width": new DataDrivenProperty(styleSpec["paint_symbol"]["icon-halo-width"]), + "icon-halo-blur": new DataDrivenProperty(styleSpec["paint_symbol"]["icon-halo-blur"]), + "icon-translate": new DataConstantProperty(styleSpec["paint_symbol"]["icon-translate"]), + "icon-translate-anchor": new DataConstantProperty(styleSpec["paint_symbol"]["icon-translate-anchor"]), + "text-opacity": new DataDrivenProperty(styleSpec["paint_symbol"]["text-opacity"]), + "text-color": new DataDrivenProperty(styleSpec["paint_symbol"]["text-color"], { runtimeType: ColorType, getOverride: (o) => o.textColor, hasOverride: (o) => !!o.textColor }), + "text-halo-color": new DataDrivenProperty(styleSpec["paint_symbol"]["text-halo-color"]), + "text-halo-width": new DataDrivenProperty(styleSpec["paint_symbol"]["text-halo-width"]), + "text-halo-blur": new DataDrivenProperty(styleSpec["paint_symbol"]["text-halo-blur"]), + "text-translate": new DataConstantProperty(styleSpec["paint_symbol"]["text-translate"]), + "text-translate-anchor": new DataConstantProperty(styleSpec["paint_symbol"]["text-translate-anchor"]), +}); + +// Note: without adding the explicit type annotation, Flow infers weaker types +// for these objects from their use in the constructor to StyleLayer, as +// {layout?: Properties<...>, paint: Properties<...>} +export default ({ paint, layout }: $Exact<{ + paint: Properties, layout: Properties +}>); diff --git a/node_modules/mapbox-gl/src/style/style_layer/typed_style_layer.js b/node_modules/mapbox-gl/src/style/style_layer/typed_style_layer.js new file mode 100644 index 0000000000000000000000000000000000000000..51cd3a8691ca80f906fe3e7463c5d77bc3b26e9d --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer/typed_style_layer.js @@ -0,0 +1,17 @@ +// @flow + +import type CircleStyleLayer from './circle_style_layer'; +import type FillStyleLayer from './fill_style_layer'; +import type FillExtrusionStyleLayer from './fill_extrusion_style_layer'; +import type HeatmapStyleLayer from './heatmap_style_layer'; +import type HillshadeStyleLayer from './hillshade_style_layer'; +import type LineStyleLayer from './line_style_layer'; +import type SymbolStyleLayer from './symbol_style_layer'; + +export type TypedStyleLayer = CircleStyleLayer | + FillStyleLayer | + FillExtrusionStyleLayer | + HeatmapStyleLayer | + HillshadeStyleLayer | + LineStyleLayer | + SymbolStyleLayer; diff --git a/node_modules/mapbox-gl/src/style/style_layer_index.js b/node_modules/mapbox-gl/src/style/style_layer_index.js new file mode 100644 index 0000000000000000000000000000000000000000..555c0993dcdda68840ebc392a65ff09ee2dff2eb --- /dev/null +++ b/node_modules/mapbox-gl/src/style/style_layer_index.js @@ -0,0 +1,80 @@ +// @flow + +import StyleLayer from './style_layer'; +import createStyleLayer from './create_style_layer'; + +import {values} from '../util/util'; +import featureFilter from '../style-spec/feature_filter'; +import groupByLayout from '../style-spec/group_by_layout'; + +import type {TypedStyleLayer} from './style_layer/typed_style_layer'; +import type {LayerSpecification} from '../style-spec/types'; + +export type LayerConfigs = {[_: string]: LayerSpecification }; +export type Family = Array; + +class StyleLayerIndex { + familiesBySource: { [source: string]: { [sourceLayer: string]: Array> } }; + keyCache: { [source: string]: string }; + + _layerConfigs: LayerConfigs; + _layers: {[_: string]: StyleLayer }; + + constructor(layerConfigs: ?Array) { + this.keyCache = {}; + if (layerConfigs) { + this.replace(layerConfigs); + } + } + + replace(layerConfigs: Array) { + this._layerConfigs = {}; + this._layers = {}; + this.update(layerConfigs, []); + } + + update(layerConfigs: Array, removedIds: Array) { + for (const layerConfig of layerConfigs) { + this._layerConfigs[layerConfig.id] = layerConfig; + + const layer = this._layers[layerConfig.id] = createStyleLayer(layerConfig); + layer._featureFilter = featureFilter(layer.filter); + if (this.keyCache[layerConfig.id]) + delete this.keyCache[layerConfig.id]; + } + for (const id of removedIds) { + delete this.keyCache[id]; + delete this._layerConfigs[id]; + delete this._layers[id]; + } + + this.familiesBySource = {}; + + const groups = groupByLayout(values(this._layerConfigs), this.keyCache); + + for (const layerConfigs of groups) { + const layers = layerConfigs.map((layerConfig) => this._layers[layerConfig.id]); + + const layer = layers[0]; + if (layer.visibility === 'none') { + continue; + } + + const sourceId = layer.source || ''; + let sourceGroup = this.familiesBySource[sourceId]; + if (!sourceGroup) { + sourceGroup = this.familiesBySource[sourceId] = {}; + } + + const sourceLayerId = layer.sourceLayer || '_geojsonTileLayer'; + let sourceLayerFamilies = sourceGroup[sourceLayerId]; + if (!sourceLayerFamilies) { + sourceLayerFamilies = sourceGroup[sourceLayerId] = []; + } + + sourceLayerFamilies.push(layers); + } + } +} + +export default StyleLayerIndex; diff --git a/node_modules/mapbox-gl/src/style/validate_style.js b/node_modules/mapbox-gl/src/style/validate_style.js new file mode 100644 index 0000000000000000000000000000000000000000..a84a38de69856ae787a8c8971e562882b322fa82 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/validate_style.js @@ -0,0 +1,42 @@ +// @flow +import validateStyleMin from '../style-spec/validate_style.min'; +import {ErrorEvent} from '../util/evented'; + +import type {Evented} from '../util/evented'; + +type ValidationError = { + message: string, + line: number, + identifier?: string +}; + +export type Validator = (Object) => $ReadOnlyArray; + +type ValidateStyle = { + (Object, ?Object): $ReadOnlyArray, + source: Validator, + layer: Validator, + light: Validator, + filter: Validator, + paintProperty: Validator, + layoutProperty: Validator +}; + +export const validateStyle = (validateStyleMin: ValidateStyle); + +export const validateSource = validateStyle.source; +export const validateLight = validateStyle.light; +export const validateFilter = validateStyle.filter; +export const validatePaintProperty = validateStyle.paintProperty; +export const validateLayoutProperty = validateStyle.layoutProperty; + +export function emitValidationErrors(emitter: Evented, errors: ?$ReadOnlyArray<{message: string, identifier?: string}>): boolean { + let hasErrors = false; + if (errors && errors.length) { + for (const error of errors) { + emitter.fire(new ErrorEvent(new Error(error.message))); + hasErrors = true; + } + } + return hasErrors; +} diff --git a/node_modules/mapbox-gl/src/style/zoom_history.js b/node_modules/mapbox-gl/src/style/zoom_history.js new file mode 100644 index 0000000000000000000000000000000000000000..b2f684e2a69fd94bae6f8ffb93bca39b94db9cf1 --- /dev/null +++ b/node_modules/mapbox-gl/src/style/zoom_history.js @@ -0,0 +1,44 @@ +// @flow + +class ZoomHistory { + lastZoom: number; + lastFloorZoom: number; + lastIntegerZoom: number; + lastIntegerZoomTime: number; + first: boolean; + + constructor() { + this.first = true; + } + + update(z: number, now: number) { + const floorZ = Math.floor(z); + + if (this.first) { + this.first = false; + this.lastIntegerZoom = floorZ; + this.lastIntegerZoomTime = 0; + this.lastZoom = z; + this.lastFloorZoom = floorZ; + return true; + } + + if (this.lastFloorZoom > floorZ) { + this.lastIntegerZoom = floorZ + 1; + this.lastIntegerZoomTime = now; + } else if (this.lastFloorZoom < floorZ) { + this.lastIntegerZoom = floorZ; + this.lastIntegerZoomTime = now; + } + + if (z !== this.lastZoom) { + this.lastZoom = z; + this.lastFloorZoom = floorZ; + return true; + } + + return false; + } +} + +export default ZoomHistory; diff --git a/node_modules/mapbox-gl/src/symbol/anchor.js b/node_modules/mapbox-gl/src/symbol/anchor.js new file mode 100644 index 0000000000000000000000000000000000000000..cd756cc72f824f02ccac242c802bcddd0a4d8c90 --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/anchor.js @@ -0,0 +1,26 @@ +// @flow + +import Point from '@mapbox/point-geometry'; + +import {register} from '../util/web_worker_transfer'; + +class Anchor extends Point { + angle: any; + segment: number | void; + + constructor(x: number, y: number, angle: number, segment?: number) { + super(x, y); + this.angle = angle; + if (segment !== undefined) { + this.segment = segment; + } + } + + clone() { + return new Anchor(this.x, this.y, this.angle, this.segment); + } +} + +register('Anchor', Anchor); + +export default Anchor; diff --git a/node_modules/mapbox-gl/src/symbol/check_max_angle.js b/node_modules/mapbox-gl/src/symbol/check_max_angle.js new file mode 100644 index 0000000000000000000000000000000000000000..f6eddf09496186cc3d88d9e7ea004086ee436379 --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/check_max_angle.js @@ -0,0 +1,81 @@ +// @flow + +export default checkMaxAngle; + +import type Point from '@mapbox/point-geometry'; +import type Anchor from './anchor'; + +/** + * Labels placed around really sharp angles aren't readable. Check if any + * part of the potential label has a combined angle that is too big. + * + * @param line + * @param anchor The point on the line around which the label is anchored. + * @param labelLength The length of the label in geometry units. + * @param windowSize The check fails if the combined angles within a part of the line that is `windowSize` long is too big. + * @param maxAngle The maximum combined angle that any window along the label is allowed to have. + * + * @returns {boolean} whether the label should be placed + * @private + */ +function checkMaxAngle(line: Array, anchor: Anchor, labelLength: number, windowSize: number, maxAngle: number) { + + // horizontal labels always pass + if (anchor.segment === undefined) return true; + + let p = anchor; + let index = anchor.segment + 1; + let anchorDistance = 0; + + // move backwards along the line to the first segment the label appears on + while (anchorDistance > -labelLength / 2) { + index--; + + // there isn't enough room for the label after the beginning of the line + if (index < 0) return false; + + anchorDistance -= line[index].dist(p); + p = line[index]; + } + + anchorDistance += line[index].dist(line[index + 1]); + index++; + + // store recent corners and their total angle difference + const recentCorners = []; + let recentAngleDelta = 0; + + // move forwards by the length of the label and check angles along the way + while (anchorDistance < labelLength / 2) { + const prev = line[index - 1]; + const current = line[index]; + const next = line[index + 1]; + + // there isn't enough room for the label before the end of the line + if (!next) return false; + + let angleDelta = prev.angleTo(current) - current.angleTo(next); + // restrict angle to -pi..pi range + angleDelta = Math.abs(((angleDelta + 3 * Math.PI) % (Math.PI * 2)) - Math.PI); + + recentCorners.push({ + distance: anchorDistance, + angleDelta + }); + recentAngleDelta += angleDelta; + + // remove corners that are far enough away from the list of recent anchors + while (anchorDistance - recentCorners[0].distance > windowSize) { + recentAngleDelta -= recentCorners.shift().angleDelta; + } + + // the sum of angles within the window area exceeds the maximum allowed value. check fails. + if (recentAngleDelta > maxAngle) return false; + + index++; + anchorDistance += current.dist(next); + } + + // no part of the line had an angle greater than the maximum allowed. check passes. + return true; +} diff --git a/node_modules/mapbox-gl/src/symbol/clip_line.js b/node_modules/mapbox-gl/src/symbol/clip_line.js new file mode 100644 index 0000000000000000000000000000000000000000..1abfea48419552c43925050ba87f3143a840de24 --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/clip_line.js @@ -0,0 +1,71 @@ +// @flow + +import Point from '@mapbox/point-geometry'; + +export default clipLine; + +/** + * Returns the part of a multiline that intersects with the provided rectangular box. + * + * @param lines + * @param x1 the left edge of the box + * @param y1 the top edge of the box + * @param x2 the right edge of the box + * @param y2 the bottom edge of the box + * @returns lines + * @private + */ +function clipLine(lines: Array>, x1: number, y1: number, x2: number, y2: number): Array> { + const clippedLines = []; + + for (let l = 0; l < lines.length; l++) { + const line = lines[l]; + let clippedLine; + + for (let i = 0; i < line.length - 1; i++) { + let p0 = line[i]; + let p1 = line[i + 1]; + + if (p0.x < x1 && p1.x < x1) { + continue; + } else if (p0.x < x1) { + p0 = new Point(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round(); + } else if (p1.x < x1) { + p1 = new Point(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round(); + } + + if (p0.y < y1 && p1.y < y1) { + continue; + } else if (p0.y < y1) { + p0 = new Point(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round(); + } else if (p1.y < y1) { + p1 = new Point(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round(); + } + + if (p0.x >= x2 && p1.x >= x2) { + continue; + } else if (p0.x >= x2) { + p0 = new Point(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round(); + } else if (p1.x >= x2) { + p1 = new Point(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round(); + } + + if (p0.y >= y2 && p1.y >= y2) { + continue; + } else if (p0.y >= y2) { + p0 = new Point(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round(); + } else if (p1.y >= y2) { + p1 = new Point(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round(); + } + + if (!clippedLine || !p0.equals(clippedLine[clippedLine.length - 1])) { + clippedLine = [p0]; + clippedLines.push(clippedLine); + } + + clippedLine.push(p1); + } + } + + return clippedLines; +} diff --git a/node_modules/mapbox-gl/src/symbol/collision_feature.js b/node_modules/mapbox-gl/src/symbol/collision_feature.js new file mode 100644 index 0000000000000000000000000000000000000000..faf3eb48a59cc931c52eb199d79970cccdc19ecf --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/collision_feature.js @@ -0,0 +1,109 @@ +// @flow + +import type {CollisionBoxArray} from '../data/array_types'; +import Point from '@mapbox/point-geometry'; +import type Anchor from './anchor'; + +/** + * A CollisionFeature represents the area of the tile covered by a single label. + * It is used with CollisionIndex to check if the label overlaps with any + * previous labels. A CollisionFeature is mostly just a set of CollisionBox + * objects. + * + * @private + */ +class CollisionFeature { + boxStartIndex: number; + boxEndIndex: number; + circleDiameter: ?number; + + /** + * Create a CollisionFeature, adding its collision box data to the given collisionBoxArray in the process. + * For line aligned labels a collision circle diameter is computed instead. + * + * @param anchor The point along the line around which the label is anchored. + * @param shaped The text or icon shaping results. + * @param boxScale A magic number used to convert from glyph metrics units to geometry units. + * @param padding The amount of padding to add around the label edges. + * @param alignLine Whether the label is aligned with the line or the viewport. + * @private + */ + constructor(collisionBoxArray: CollisionBoxArray, + anchor: Anchor, + featureIndex: number, + sourceLayerIndex: number, + bucketIndex: number, + shaped: Object, + boxScale: number, + padding: number, + alignLine: boolean, + rotate: number) { + + this.boxStartIndex = collisionBoxArray.length; + + if (alignLine) { + // Compute height of the shape in glyph metrics and apply collision padding. + // Note that the pixel based 'text-padding' is applied at runtime + let top = shaped.top; + let bottom = shaped.bottom; + const collisionPadding = shaped.collisionPadding; + + if (collisionPadding) { + top -= collisionPadding[1]; + bottom += collisionPadding[3]; + } + + let height = bottom - top; + + if (height > 0) { + // set minimum box height to avoid very many small labels + height = Math.max(10, height); + this.circleDiameter = height; + } + } else { + let y1 = shaped.top * boxScale - padding; + let y2 = shaped.bottom * boxScale + padding; + let x1 = shaped.left * boxScale - padding; + let x2 = shaped.right * boxScale + padding; + + const collisionPadding = shaped.collisionPadding; + if (collisionPadding) { + x1 -= collisionPadding[0] * boxScale; + y1 -= collisionPadding[1] * boxScale; + x2 += collisionPadding[2] * boxScale; + y2 += collisionPadding[3] * boxScale; + } + + if (rotate) { + // Account for *-rotate in point collision boxes + // See https://github.com/mapbox/mapbox-gl-js/issues/6075 + // Doesn't account for icon-text-fit + + const tl = new Point(x1, y1); + const tr = new Point(x2, y1); + const bl = new Point(x1, y2); + const br = new Point(x2, y2); + + const rotateRadians = rotate * Math.PI / 180; + + tl._rotate(rotateRadians); + tr._rotate(rotateRadians); + bl._rotate(rotateRadians); + br._rotate(rotateRadians); + + // Collision features require an "on-axis" geometry, + // so take the envelope of the rotated geometry + // (may be quite large for wide labels rotated 45 degrees) + x1 = Math.min(tl.x, tr.x, bl.x, br.x); + x2 = Math.max(tl.x, tr.x, bl.x, br.x); + y1 = Math.min(tl.y, tr.y, bl.y, br.y); + y2 = Math.max(tl.y, tr.y, bl.y, br.y); + } + collisionBoxArray.emplaceBack(anchor.x, anchor.y, x1, y1, x2, y2, featureIndex, sourceLayerIndex, bucketIndex); + } + + this.boxEndIndex = collisionBoxArray.length; + } +} + +export default CollisionFeature; diff --git a/node_modules/mapbox-gl/src/symbol/collision_index.js b/node_modules/mapbox-gl/src/symbol/collision_index.js new file mode 100644 index 0000000000000000000000000000000000000000..f553e610761013babb4562d9c0d74501b738e958 --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/collision_index.js @@ -0,0 +1,373 @@ +// @flow + +import Point from '@mapbox/point-geometry'; +import clipLine from './clip_line'; +import PathInterpolator from './path_interpolator'; + +import * as intersectionTests from '../util/intersection_tests'; +import Grid from './grid_index'; +import {mat4} from 'gl-matrix'; +import ONE_EM from '../symbol/one_em'; +import assert from 'assert'; + +import * as projection from '../symbol/projection'; + +import type Transform from '../geo/transform'; +import type {SingleCollisionBox} from '../data/bucket/symbol_bucket'; +import type { + GlyphOffsetArray, + SymbolLineVertexArray +} from '../data/array_types'; + +// When a symbol crosses the edge that causes it to be included in +// collision detection, it will cause changes in the symbols around +// it. This constant specifies how many pixels to pad the edge of +// the viewport for collision detection so that the bulk of the changes +// occur offscreen. Making this constant greater increases label +// stability, but it's expensive. +const viewportPadding = 100; + +/** + * A collision index used to prevent symbols from overlapping. It keep tracks of + * where previous symbols have been placed and is used to check if a new + * symbol overlaps with any previously added symbols. + * + * There are two steps to insertion: first placeCollisionBox/Circles checks if + * there's room for a symbol, then insertCollisionBox/Circles actually puts the + * symbol in the index. The two step process allows paired symbols to be inserted + * together even if they overlap. + * + * @private + */ +class CollisionIndex { + grid: Grid; + ignoredGrid: Grid; + transform: Transform; + pitchfactor: number; + screenRightBoundary: number; + screenBottomBoundary: number; + gridRightBoundary: number; + gridBottomBoundary: number; + + constructor( + transform: Transform, + grid: Grid = new Grid(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25), + ignoredGrid: Grid = new Grid(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25) + ) { + this.transform = transform; + + this.grid = grid; + this.ignoredGrid = ignoredGrid; + this.pitchfactor = Math.cos(transform._pitch) * transform.cameraToCenterDistance; + + this.screenRightBoundary = transform.width + viewportPadding; + this.screenBottomBoundary = transform.height + viewportPadding; + this.gridRightBoundary = transform.width + 2 * viewportPadding; + this.gridBottomBoundary = transform.height + 2 * viewportPadding; + } + + placeCollisionBox(collisionBox: SingleCollisionBox, allowOverlap: boolean, textPixelRatio: number, posMatrix: mat4, collisionGroupPredicate?: any): { box: Array, offscreen: boolean } { + const projectedPoint = this.projectAndGetPerspectiveRatio(posMatrix, collisionBox.anchorPointX, collisionBox.anchorPointY); + const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio; + const tlX = collisionBox.x1 * tileToViewport + projectedPoint.point.x; + const tlY = collisionBox.y1 * tileToViewport + projectedPoint.point.y; + const brX = collisionBox.x2 * tileToViewport + projectedPoint.point.x; + const brY = collisionBox.y2 * tileToViewport + projectedPoint.point.y; + + if (!this.isInsideGrid(tlX, tlY, brX, brY) || + (!allowOverlap && this.grid.hitTest(tlX, tlY, brX, brY, collisionGroupPredicate))) { + return { + box: [], + offscreen: false + }; + } + + return { + box: [tlX, tlY, brX, brY], + offscreen: this.isOffscreen(tlX, tlY, brX, brY) + }; + } + + placeCollisionCircles(allowOverlap: boolean, + symbol: any, + lineVertexArray: SymbolLineVertexArray, + glyphOffsetArray: GlyphOffsetArray, + fontSize: number, + posMatrix: mat4, + labelPlaneMatrix: mat4, + labelToScreenMatrix?: mat4, + showCollisionCircles: boolean, + pitchWithMap: boolean, + collisionGroupPredicate?: any, + circlePixelDiameter: number, + textPixelPadding: number): { circles: Array, offscreen: boolean, collisionDetected: boolean } { + const placedCollisionCircles = []; + + const tileUnitAnchorPoint = new Point(symbol.anchorX, symbol.anchorY); + const screenAnchorPoint = projection.project(tileUnitAnchorPoint, posMatrix); + const perspectiveRatio = projection.getPerspectiveRatio(this.transform.cameraToCenterDistance, screenAnchorPoint.signedDistanceFromCamera); + const labelPlaneFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio; + const labelPlaneFontScale = labelPlaneFontSize / ONE_EM; + + const labelPlaneAnchorPoint = projection.project(tileUnitAnchorPoint, labelPlaneMatrix).point; + + const projectionCache = {}; + const lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale; + const lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale; + + const firstAndLastGlyph = projection.placeFirstAndLastGlyph( + labelPlaneFontScale, + glyphOffsetArray, + lineOffsetX, + lineOffsetY, + /*flip*/ false, + labelPlaneAnchorPoint, + tileUnitAnchorPoint, + symbol, + lineVertexArray, + labelPlaneMatrix, + projectionCache); + + let collisionDetected = false; + let inGrid = false; + let entirelyOffscreen = true; + + if (firstAndLastGlyph) { + const radius = circlePixelDiameter * 0.5 * perspectiveRatio + textPixelPadding; + const screenPlaneMin = new Point(-viewportPadding, -viewportPadding); + const screenPlaneMax = new Point(this.screenRightBoundary, this.screenBottomBoundary); + const interpolator = new PathInterpolator(); + + // Construct a projected path from projected line vertices. Anchor points are ignored and removed + const first = firstAndLastGlyph.first; + const last = firstAndLastGlyph.last; + + let projectedPath = []; + for (let i = first.path.length - 1; i >= 1; i--) { + projectedPath.push(first.path[i]); + } + for (let i = 1; i < last.path.length; i++) { + projectedPath.push(last.path[i]); + } + assert(projectedPath.length >= 2); + + // Tolerate a slightly longer distance than one diameter between two adjacent circles + const circleDist = radius * 2.5; + + // The path might need to be converted into screen space if a pitched map is used as the label space + if (labelToScreenMatrix) { + const screenSpacePath = projectedPath.map(p => projection.project(p, labelToScreenMatrix)); + + // Do not try to place collision circles if even of the points is behind the camera. + // This is a plausible scenario with big camera pitch angles + if (screenSpacePath.some(point => point.signedDistanceFromCamera <= 0)) { + projectedPath = []; + } else { + projectedPath = screenSpacePath.map(p => p.point); + } + } + + let segments = []; + + if (projectedPath.length > 0) { + // Quickly check if the path is fully inside or outside of the padded collision region. + // For overlapping paths we'll only create collision circles for the visible segments + const minPoint = projectedPath[0].clone(); + const maxPoint = projectedPath[0].clone(); + + for (let i = 1; i < projectedPath.length; i++) { + minPoint.x = Math.min(minPoint.x, projectedPath[i].x); + minPoint.y = Math.min(minPoint.y, projectedPath[i].y); + maxPoint.x = Math.max(maxPoint.x, projectedPath[i].x); + maxPoint.y = Math.max(maxPoint.y, projectedPath[i].y); + } + + if (minPoint.x >= screenPlaneMin.x && maxPoint.x <= screenPlaneMax.x && + minPoint.y >= screenPlaneMin.y && maxPoint.y <= screenPlaneMax.y) { + // Quad fully visible + segments = [projectedPath]; + } else if (maxPoint.x < screenPlaneMin.x || minPoint.x > screenPlaneMax.x || + maxPoint.y < screenPlaneMin.y || minPoint.y > screenPlaneMax.y) { + // Not visible + segments = []; + } else { + segments = clipLine([projectedPath], screenPlaneMin.x, screenPlaneMin.y, screenPlaneMax.x, screenPlaneMax.y); + } + } + + for (const seg of segments) { + // interpolate positions for collision circles. Add a small padding to both ends of the segment + assert(seg.length > 0); + interpolator.reset(seg, radius * 0.25); + + let numCircles = 0; + + if (interpolator.length <= 0.5 * radius) { + numCircles = 1; + } else { + numCircles = Math.ceil(interpolator.paddedLength / circleDist) + 1; + } + + for (let i = 0; i < numCircles; i++) { + const t = i / Math.max(numCircles - 1, 1); + const circlePosition = interpolator.lerp(t); + + // add viewport padding to the position and perform initial collision check + const centerX = circlePosition.x + viewportPadding; + const centerY = circlePosition.y + viewportPadding; + + placedCollisionCircles.push(centerX, centerY, radius, 0); + + const x1 = centerX - radius; + const y1 = centerY - radius; + const x2 = centerX + radius; + const y2 = centerY + radius; + + entirelyOffscreen = entirelyOffscreen && this.isOffscreen(x1, y1, x2, y2); + inGrid = inGrid || this.isInsideGrid(x1, y1, x2, y2); + + if (!allowOverlap) { + if (this.grid.hitTestCircle(centerX, centerY, radius, collisionGroupPredicate)) { + // Don't early exit if we're showing the debug circles because we still want to calculate + // which circles are in use + collisionDetected = true; + if (!showCollisionCircles) { + return { + circles: [], + offscreen: false, + collisionDetected + }; + } + } + } + } + } + } + + return { + circles: ((!showCollisionCircles && collisionDetected) || !inGrid) ? [] : placedCollisionCircles, + offscreen: entirelyOffscreen, + collisionDetected + }; + } + + /** + * Because the geometries in the CollisionIndex are an approximation of the shape of + * symbols on the map, we use the CollisionIndex to look up the symbol part of + * `queryRenderedFeatures`. + * + * @private + */ + queryRenderedSymbols(viewportQueryGeometry: Array) { + if (viewportQueryGeometry.length === 0 || (this.grid.keysLength() === 0 && this.ignoredGrid.keysLength() === 0)) { + return {}; + } + + const query = []; + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const point of viewportQueryGeometry) { + const gridPoint = new Point(point.x + viewportPadding, point.y + viewportPadding); + minX = Math.min(minX, gridPoint.x); + minY = Math.min(minY, gridPoint.y); + maxX = Math.max(maxX, gridPoint.x); + maxY = Math.max(maxY, gridPoint.y); + query.push(gridPoint); + } + + const features = this.grid.query(minX, minY, maxX, maxY) + .concat(this.ignoredGrid.query(minX, minY, maxX, maxY)); + + const seenFeatures = {}; + const result = {}; + + for (const feature of features) { + const featureKey = feature.key; + // Skip already seen features. + if (seenFeatures[featureKey.bucketInstanceId] === undefined) { + seenFeatures[featureKey.bucketInstanceId] = {}; + } + if (seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex]) { + continue; + } + + // Check if query intersects with the feature box + // "Collision Circles" for line labels are treated as boxes here + // Since there's no actual collision taking place, the circle vs. square + // distinction doesn't matter as much, and box geometry is easier + // to work with. + const bbox = [ + new Point(feature.x1, feature.y1), + new Point(feature.x2, feature.y1), + new Point(feature.x2, feature.y2), + new Point(feature.x1, feature.y2) + ]; + if (!intersectionTests.polygonIntersectsPolygon(query, bbox)) { + continue; + } + + seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex] = true; + if (result[featureKey.bucketInstanceId] === undefined) { + result[featureKey.bucketInstanceId] = []; + } + result[featureKey.bucketInstanceId].push(featureKey.featureIndex); + } + + return result; + } + + insertCollisionBox(collisionBox: Array, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number) { + const grid = ignorePlacement ? this.ignoredGrid : this.grid; + + const key = {bucketInstanceId, featureIndex, collisionGroupID}; + grid.insert(key, collisionBox[0], collisionBox[1], collisionBox[2], collisionBox[3]); + } + + insertCollisionCircles(collisionCircles: Array, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number) { + const grid = ignorePlacement ? this.ignoredGrid : this.grid; + + const key = {bucketInstanceId, featureIndex, collisionGroupID}; + for (let k = 0; k < collisionCircles.length; k += 4) { + grid.insertCircle(key, collisionCircles[k], collisionCircles[k + 1], collisionCircles[k + 2]); + } + } + + projectAndGetPerspectiveRatio(posMatrix: mat4, x: number, y: number) { + const p = [x, y, 0, 1]; + projection.xyTransformMat4(p, p, posMatrix); + const a = new Point( + (((p[0] / p[3] + 1) / 2) * this.transform.width) + viewportPadding, + (((-p[1] / p[3] + 1) / 2) * this.transform.height) + viewportPadding + ); + return { + point: a, + // See perspective ratio comment in symbol_sdf.vertex + // We're doing collision detection in viewport space so we need + // to scale down boxes in the distance + perspectiveRatio: 0.5 + 0.5 * (this.transform.cameraToCenterDistance / p[3]) + }; + } + + isOffscreen(x1: number, y1: number, x2: number, y2: number) { + return x2 < viewportPadding || x1 >= this.screenRightBoundary || y2 < viewportPadding || y1 > this.screenBottomBoundary; + } + + isInsideGrid(x1: number, y1: number, x2: number, y2: number) { + return x2 >= 0 && x1 < this.gridRightBoundary && y2 >= 0 && y1 < this.gridBottomBoundary; + } + + /* + * Returns a matrix for transforming collision shapes to viewport coordinate space. + * Use this function to render e.g. collision circles on the screen. + * example transformation: clipPos = glCoordMatrix * viewportMatrix * circle_pos + */ + getViewportMatrix(): mat4 { + const m = mat4.identity([]); + mat4.translate(m, m, [-viewportPadding, -viewportPadding, 0.0]); + return m; + } +} + +export default CollisionIndex; diff --git a/node_modules/mapbox-gl/src/symbol/cross_tile_symbol_index.js b/node_modules/mapbox-gl/src/symbol/cross_tile_symbol_index.js new file mode 100644 index 0000000000000000000000000000000000000000..103d8399612db53f1a8efa3d4334d2bfa8287b28 --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/cross_tile_symbol_index.js @@ -0,0 +1,301 @@ +// @flow + +import EXTENT from '../data/extent'; + +import {SymbolInstanceArray} from '../data/array_types'; + +import type {SymbolInstance} from '../data/array_types'; +import type {OverscaledTileID} from '../source/tile_id'; +import type SymbolBucket from '../data/bucket/symbol_bucket'; +import type StyleLayer from '../style/style_layer'; +import type Tile from '../source/tile'; + +/* + The CrossTileSymbolIndex generally works on the assumption that + a conceptual "unique symbol" can be identified by the text of + the label combined with the anchor point. The goal is to assign + these conceptual "unique symbols" a shared crossTileID that can be + used by Placement to keep fading opacity states consistent and to + deduplicate labels. + + The CrossTileSymbolIndex indexes all the current symbol instances and + their crossTileIDs. When a symbol bucket gets added or updated, the + index assigns a crossTileID to each of it's symbol instances by either + matching it with an existing id or assigning a new one. +*/ + +// Round anchor positions to roughly 4 pixel grid +const roundingFactor = 512 / EXTENT / 2; + +class TileLayerIndex { + tileID: OverscaledTileID; + indexedSymbolInstances: {[_: number]: Array<{ + crossTileID: number, + coord: { + x: number, + y: number + } + }>}; + bucketInstanceId: number; + + constructor(tileID: OverscaledTileID, symbolInstances: SymbolInstanceArray, bucketInstanceId: number) { + this.tileID = tileID; + this.indexedSymbolInstances = {}; + this.bucketInstanceId = bucketInstanceId; + + for (let i = 0; i < symbolInstances.length; i++) { + const symbolInstance = symbolInstances.get(i); + const key = symbolInstance.key; + if (!this.indexedSymbolInstances[key]) { + this.indexedSymbolInstances[key] = []; + } + // This tile may have multiple symbol instances with the same key + // Store each one along with its coordinates + this.indexedSymbolInstances[key].push({ + crossTileID: symbolInstance.crossTileID, + coord: this.getScaledCoordinates(symbolInstance, tileID) + }); + } + } + + // Converts the coordinates of the input symbol instance into coordinates that be can compared + // against other symbols in this index. Coordinates are: + // (1) world-based (so after conversion the source tile is irrelevant) + // (2) converted to the z-scale of this TileLayerIndex + // (3) down-sampled by "roundingFactor" from tile coordinate precision in order to be + // more tolerant of small differences between tiles. + getScaledCoordinates(symbolInstance: SymbolInstance, childTileID: OverscaledTileID) { + const zDifference = childTileID.canonical.z - this.tileID.canonical.z; + const scale = roundingFactor / Math.pow(2, zDifference); + return { + x: Math.floor((childTileID.canonical.x * EXTENT + symbolInstance.anchorX) * scale), + y: Math.floor((childTileID.canonical.y * EXTENT + symbolInstance.anchorY) * scale) + }; + } + + findMatches(symbolInstances: SymbolInstanceArray, newTileID: OverscaledTileID, zoomCrossTileIDs: {[crossTileID: number]: boolean}) { + const tolerance = this.tileID.canonical.z < newTileID.canonical.z ? 1 : Math.pow(2, this.tileID.canonical.z - newTileID.canonical.z); + + for (let i = 0; i < symbolInstances.length; i++) { + const symbolInstance = symbolInstances.get(i); + if (symbolInstance.crossTileID) { + // already has a match, skip + continue; + } + + const indexedInstances = this.indexedSymbolInstances[symbolInstance.key]; + if (!indexedInstances) { + // No symbol with this key in this bucket + continue; + } + + const scaledSymbolCoord = this.getScaledCoordinates(symbolInstance, newTileID); + + for (const thisTileSymbol of indexedInstances) { + // Return any symbol with the same keys whose coordinates are within 1 + // grid unit. (with a 4px grid, this covers a 12px by 12px area) + if (Math.abs(thisTileSymbol.coord.x - scaledSymbolCoord.x) <= tolerance && + Math.abs(thisTileSymbol.coord.y - scaledSymbolCoord.y) <= tolerance && + !zoomCrossTileIDs[thisTileSymbol.crossTileID]) { + // Once we've marked ourselves duplicate against this parent symbol, + // don't let any other symbols at the same zoom level duplicate against + // the same parent (see issue #5993) + zoomCrossTileIDs[thisTileSymbol.crossTileID] = true; + symbolInstance.crossTileID = thisTileSymbol.crossTileID; + break; + } + } + } + } +} + +class CrossTileIDs { + maxCrossTileID: number; + constructor() { + this.maxCrossTileID = 0; + } + generate() { + return ++this.maxCrossTileID; + } +} + +class CrossTileSymbolLayerIndex { + indexes: {[zoom: string | number]: {[tileId: string | number]: TileLayerIndex}}; + usedCrossTileIDs: {[zoom: string | number]: {[crossTileID: number]: boolean}}; + lng: number; + + constructor() { + this.indexes = {}; + this.usedCrossTileIDs = {}; + this.lng = 0; + } + + /* + * Sometimes when a user pans across the antimeridian the longitude value gets wrapped. + * To prevent labels from flashing out and in we adjust the tileID values in the indexes + * so that they match the new wrapped version of the map. + */ + handleWrapJump(lng: number) { + const wrapDelta = Math.round((lng - this.lng) / 360); + if (wrapDelta !== 0) { + for (const zoom in this.indexes) { + const zoomIndexes = this.indexes[zoom]; + const newZoomIndex = {}; + for (const key in zoomIndexes) { + // change the tileID's wrap and add it to a new index + const index = zoomIndexes[key]; + index.tileID = index.tileID.unwrapTo(index.tileID.wrap + wrapDelta); + newZoomIndex[index.tileID.key] = index; + } + this.indexes[zoom] = newZoomIndex; + } + } + this.lng = lng; + } + + addBucket(tileID: OverscaledTileID, bucket: SymbolBucket, crossTileIDs: CrossTileIDs) { + if (this.indexes[tileID.overscaledZ] && + this.indexes[tileID.overscaledZ][tileID.key]) { + if (this.indexes[tileID.overscaledZ][tileID.key].bucketInstanceId === + bucket.bucketInstanceId) { + return false; + } else { + // We're replacing this bucket with an updated version + // Remove the old bucket's "used crossTileIDs" now so that + // the new bucket can claim them. + // The old index entries themselves stick around until + // 'removeStaleBuckets' is called. + this.removeBucketCrossTileIDs(tileID.overscaledZ, + this.indexes[tileID.overscaledZ][tileID.key]); + } + } + + for (let i = 0; i < bucket.symbolInstances.length; i++) { + const symbolInstance = bucket.symbolInstances.get(i); + symbolInstance.crossTileID = 0; + } + + if (!this.usedCrossTileIDs[tileID.overscaledZ]) { + this.usedCrossTileIDs[tileID.overscaledZ] = {}; + } + const zoomCrossTileIDs = this.usedCrossTileIDs[tileID.overscaledZ]; + + for (const zoom in this.indexes) { + const zoomIndexes = this.indexes[zoom]; + if (Number(zoom) > tileID.overscaledZ) { + for (const id in zoomIndexes) { + const childIndex = zoomIndexes[id]; + if (childIndex.tileID.isChildOf(tileID)) { + childIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs); + } + } + } else { + const parentCoord = tileID.scaledTo(Number(zoom)); + const parentIndex = zoomIndexes[parentCoord.key]; + if (parentIndex) { + parentIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs); + } + } + } + + for (let i = 0; i < bucket.symbolInstances.length; i++) { + const symbolInstance = bucket.symbolInstances.get(i); + if (!symbolInstance.crossTileID) { + // symbol did not match any known symbol, assign a new id + symbolInstance.crossTileID = crossTileIDs.generate(); + zoomCrossTileIDs[symbolInstance.crossTileID] = true; + } + } + + if (this.indexes[tileID.overscaledZ] === undefined) { + this.indexes[tileID.overscaledZ] = {}; + } + this.indexes[tileID.overscaledZ][tileID.key] = new TileLayerIndex(tileID, bucket.symbolInstances, bucket.bucketInstanceId); + + return true; + } + + removeBucketCrossTileIDs(zoom: string | number, removedBucket: TileLayerIndex) { + for (const key in removedBucket.indexedSymbolInstances) { + for (const symbolInstance of removedBucket.indexedSymbolInstances[(key: any)]) { + delete this.usedCrossTileIDs[zoom][symbolInstance.crossTileID]; + } + } + } + + removeStaleBuckets(currentIDs: { [string | number]: boolean }) { + let tilesChanged = false; + for (const z in this.indexes) { + const zoomIndexes = this.indexes[z]; + for (const tileKey in zoomIndexes) { + if (!currentIDs[zoomIndexes[tileKey].bucketInstanceId]) { + this.removeBucketCrossTileIDs(z, zoomIndexes[tileKey]); + delete zoomIndexes[tileKey]; + tilesChanged = true; + } + } + } + return tilesChanged; + } +} + +class CrossTileSymbolIndex { + layerIndexes: {[layerId: string]: CrossTileSymbolLayerIndex}; + crossTileIDs: CrossTileIDs; + maxBucketInstanceId: number; + bucketsInCurrentPlacement: {[_: number]: boolean}; + + constructor() { + this.layerIndexes = {}; + this.crossTileIDs = new CrossTileIDs(); + this.maxBucketInstanceId = 0; + this.bucketsInCurrentPlacement = {}; + } + + addLayer(styleLayer: StyleLayer, tiles: Array, lng: number) { + let layerIndex = this.layerIndexes[styleLayer.id]; + if (layerIndex === undefined) { + layerIndex = this.layerIndexes[styleLayer.id] = new CrossTileSymbolLayerIndex(); + } + + let symbolBucketsChanged = false; + const currentBucketIDs = {}; + + layerIndex.handleWrapJump(lng); + + for (const tile of tiles) { + const symbolBucket = ((tile.getBucket(styleLayer): any): SymbolBucket); + if (!symbolBucket || styleLayer.id !== symbolBucket.layerIds[0]) + continue; + + if (!symbolBucket.bucketInstanceId) { + symbolBucket.bucketInstanceId = ++this.maxBucketInstanceId; + } + + if (layerIndex.addBucket(tile.tileID, symbolBucket, this.crossTileIDs)) { + symbolBucketsChanged = true; + } + currentBucketIDs[symbolBucket.bucketInstanceId] = true; + } + + if (layerIndex.removeStaleBuckets(currentBucketIDs)) { + symbolBucketsChanged = true; + } + + return symbolBucketsChanged; + } + + pruneUnusedLayers(usedLayers: Array) { + const usedLayerMap = {}; + usedLayers.forEach((usedLayer) => { + usedLayerMap[usedLayer] = true; + }); + for (const layerId in this.layerIndexes) { + if (!usedLayerMap[layerId]) { + delete this.layerIndexes[layerId]; + } + } + } +} + +export default CrossTileSymbolIndex; diff --git a/node_modules/mapbox-gl/src/symbol/get_anchors.js b/node_modules/mapbox-gl/src/symbol/get_anchors.js new file mode 100644 index 0000000000000000000000000000000000000000..9b034b4bc865cfc51ef52f5bdfe80ef9ccaf232e --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/get_anchors.js @@ -0,0 +1,167 @@ +// @flow + +import {number as interpolate} from '../style-spec/util/interpolate'; + +import Anchor from '../symbol/anchor'; +import checkMaxAngle from './check_max_angle'; + +import type Point from '@mapbox/point-geometry'; +import type {Shaping, PositionedIcon} from './shaping'; + +export {getAnchors, getCenterAnchor}; + +function getLineLength(line: Array): number { + let lineLength = 0; + for (let k = 0; k < line.length - 1; k++) { + lineLength += line[k].dist(line[k + 1]); + } + return lineLength; +} + +function getAngleWindowSize(shapedText: ?Shaping, + glyphSize: number, + boxScale: number): number { + return shapedText ? + 3 / 5 * glyphSize * boxScale : + 0; +} + +function getShapedLabelLength(shapedText: ?Shaping, shapedIcon: ?PositionedIcon): number { + return Math.max( + shapedText ? shapedText.right - shapedText.left : 0, + shapedIcon ? shapedIcon.right - shapedIcon.left : 0); +} + +function getCenterAnchor(line: Array, + maxAngle: number, + shapedText: ?Shaping, + shapedIcon: ?PositionedIcon, + glyphSize: number, + boxScale: number) { + const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale); + const labelLength = getShapedLabelLength(shapedText, shapedIcon) * boxScale; + + let prevDistance = 0; + const centerDistance = getLineLength(line) / 2; + + for (let i = 0; i < line.length - 1; i++) { + + const a = line[i], + b = line[i + 1]; + + const segmentDistance = a.dist(b); + + if (prevDistance + segmentDistance > centerDistance) { + // The center is on this segment + const t = (centerDistance - prevDistance) / segmentDistance, + x = interpolate(a.x, b.x, t), + y = interpolate(a.y, b.y, t); + + const anchor = new Anchor(x, y, b.angleTo(a), i); + anchor._round(); + if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { + return anchor; + } else { + return; + } + } + + prevDistance += segmentDistance; + } +} + +function getAnchors(line: Array, + spacing: number, + maxAngle: number, + shapedText: ?Shaping, + shapedIcon: ?PositionedIcon, + glyphSize: number, + boxScale: number, + overscaling: number, + tileExtent: number) { + + // Resample a line to get anchor points for labels and check that each + // potential label passes text-max-angle check and has enough froom to fit + // on the line. + + const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale); + const shapedLabelLength = getShapedLabelLength(shapedText, shapedIcon); + const labelLength = shapedLabelLength * boxScale; + + // Is the line continued from outside the tile boundary? + const isLineContinued = line[0].x === 0 || line[0].x === tileExtent || line[0].y === 0 || line[0].y === tileExtent; + + // Is the label long, relative to the spacing? + // If so, adjust the spacing so there is always a minimum space of `spacing / 4` between label edges. + if (spacing - labelLength < spacing / 4) { + spacing = labelLength + spacing / 4; + } + + // Offset the first anchor by: + // Either half the label length plus a fixed extra offset if the line is not continued + // Or half the spacing if the line is continued. + + // For non-continued lines, add a bit of fixed extra offset to avoid collisions at T intersections. + const fixedExtraOffset = glyphSize * 2; + + const offset = !isLineContinued ? + ((shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling) % spacing : + (spacing / 2 * overscaling) % spacing; + + return resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, false, tileExtent); +} + +function resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, placeAtMiddle, tileExtent) { + + const halfLabelLength = labelLength / 2; + const lineLength = getLineLength(line); + + let distance = 0, + markedDistance = offset - spacing; + + let anchors = []; + + for (let i = 0; i < line.length - 1; i++) { + + const a = line[i], + b = line[i + 1]; + + const segmentDist = a.dist(b), + angle = b.angleTo(a); + + while (markedDistance + spacing < distance + segmentDist) { + markedDistance += spacing; + + const t = (markedDistance - distance) / segmentDist, + x = interpolate(a.x, b.x, t), + y = interpolate(a.y, b.y, t); + + // Check that the point is within the tile boundaries and that + // the label would fit before the beginning and end of the line + // if placed at this point. + if (x >= 0 && x < tileExtent && y >= 0 && y < tileExtent && + markedDistance - halfLabelLength >= 0 && + markedDistance + halfLabelLength <= lineLength) { + const anchor = new Anchor(x, y, angle, i); + anchor._round(); + + if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) { + anchors.push(anchor); + } + } + } + + distance += segmentDist; + } + + if (!placeAtMiddle && !anchors.length && !isLineContinued) { + // The first attempt at finding anchors at which labels can be placed failed. + // Try again, but this time just try placing one anchor at the middle of the line. + // This has the most effect for short lines in overscaled tiles, since the + // initial offset used in overscaled tiles is calculated to align labels with positions in + // parent tiles instead of placing the label as close to the beginning as possible. + anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, true, tileExtent); + } + + return anchors; +} diff --git a/node_modules/mapbox-gl/src/symbol/grid_index.js b/node_modules/mapbox-gl/src/symbol/grid_index.js new file mode 100644 index 0000000000000000000000000000000000000000..fa1dc103436297943b0b262cc48e7e25c66ba1ce --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/grid_index.js @@ -0,0 +1,335 @@ +// @flow + +/** + * GridIndex is a data structure for testing the intersection of + * circles and rectangles in a 2d plane. + * It is optimized for rapid insertion and querying. + * GridIndex splits the plane into a set of "cells" and keeps track + * of which geometries intersect with each cell. At query time, + * full geometry comparisons are only done for items that share + * at least one cell. As long as the geometries are relatively + * uniformly distributed across the plane, this greatly reduces + * the number of comparisons necessary. + * + * @private + */ +class GridIndex { + circleKeys: Array; + boxKeys: Array; + boxCells: Array>; + circleCells: Array>; + bboxes: Array; + circles: Array; + xCellCount: number; + yCellCount: number; + width: number; + height: number; + xScale: number; + yScale: number; + boxUid: number; + circleUid: number; + + constructor (width: number, height: number, cellSize: number) { + const boxCells = this.boxCells = []; + const circleCells = this.circleCells = []; + + // More cells -> fewer geometries to check per cell, but items tend + // to be split across more cells. + // Sweet spot allows most small items to fit in one cell + this.xCellCount = Math.ceil(width / cellSize); + this.yCellCount = Math.ceil(height / cellSize); + + for (let i = 0; i < this.xCellCount * this.yCellCount; i++) { + boxCells.push([]); + circleCells.push([]); + } + this.circleKeys = []; + this.boxKeys = []; + this.bboxes = []; + this.circles = []; + + this.width = width; + this.height = height; + this.xScale = this.xCellCount / width; + this.yScale = this.yCellCount / height; + this.boxUid = 0; + this.circleUid = 0; + } + + keysLength() { + return this.boxKeys.length + this.circleKeys.length; + } + + insert(key: any, x1: number, y1: number, x2: number, y2: number) { + this._forEachCell(x1, y1, x2, y2, this._insertBoxCell, this.boxUid++); + this.boxKeys.push(key); + this.bboxes.push(x1); + this.bboxes.push(y1); + this.bboxes.push(x2); + this.bboxes.push(y2); + } + + insertCircle(key: any, x: number, y: number, radius: number) { + // Insert circle into grid for all cells in the circumscribing square + // It's more than necessary (by a factor of 4/PI), but fast to insert + this._forEachCell(x - radius, y - radius, x + radius, y + radius, this._insertCircleCell, this.circleUid++); + this.circleKeys.push(key); + this.circles.push(x); + this.circles.push(y); + this.circles.push(radius); + } + + _insertBoxCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number) { + this.boxCells[cellIndex].push(uid); + } + + _insertCircleCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number) { + this.circleCells[cellIndex].push(uid); + } + + _query(x1: number, y1: number, x2: number, y2: number, hitTest: boolean, predicate?: any) { + if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) { + return hitTest ? false : []; + } + const result = []; + if (x1 <= 0 && y1 <= 0 && this.width <= x2 && this.height <= y2) { + if (hitTest) { + return true; + } + for (let boxUid = 0; boxUid < this.boxKeys.length; boxUid++) { + result.push({ + key: this.boxKeys[boxUid], + x1: this.bboxes[boxUid * 4], + y1: this.bboxes[boxUid * 4 + 1], + x2: this.bboxes[boxUid * 4 + 2], + y2: this.bboxes[boxUid * 4 + 3] + }); + } + for (let circleUid = 0; circleUid < this.circleKeys.length; circleUid++) { + const x = this.circles[circleUid * 3]; + const y = this.circles[circleUid * 3 + 1]; + const radius = this.circles[circleUid * 3 + 2]; + result.push({ + key: this.circleKeys[circleUid], + x1: x - radius, + y1: y - radius, + x2: x + radius, + y2: y + radius + }); + } + return predicate ? result.filter(predicate) : result; + } else { + const queryArgs = { + hitTest, + seenUids: {box: {}, circle: {}} + }; + this._forEachCell(x1, y1, x2, y2, this._queryCell, result, queryArgs, predicate); + return hitTest ? result.length > 0 : result; + } + } + + _queryCircle(x: number, y: number, radius: number, hitTest: boolean, predicate?: any) { + // Insert circle into grid for all cells in the circumscribing square + // It's more than necessary (by a factor of 4/PI), but fast to insert + const x1 = x - radius; + const x2 = x + radius; + const y1 = y - radius; + const y2 = y + radius; + if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) { + return hitTest ? false : []; + } + + // Box query early exits if the bounding box is larger than the grid, but we don't do + // the equivalent calculation for circle queries because early exit is less likely + // and the calculation is more expensive + const result = []; + const queryArgs = { + hitTest, + circle: {x, y, radius}, + seenUids: {box: {}, circle: {}} + }; + this._forEachCell(x1, y1, x2, y2, this._queryCellCircle, result, queryArgs, predicate); + return hitTest ? result.length > 0 : result; + } + + query(x1: number, y1: number, x2: number, y2: number, predicate?: any): Array { + return (this._query(x1, y1, x2, y2, false, predicate): any); + } + + hitTest(x1: number, y1: number, x2: number, y2: number, predicate?: any): boolean { + return (this._query(x1, y1, x2, y2, true, predicate): any); + } + + hitTestCircle(x: number, y: number, radius: number, predicate?: any): boolean { + return (this._queryCircle(x, y, radius, true, predicate): any); + } + + _queryCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: any, queryArgs: any, predicate?: any) { + const seenUids = queryArgs.seenUids; + const boxCell = this.boxCells[cellIndex]; + if (boxCell !== null) { + const bboxes = this.bboxes; + for (const boxUid of boxCell) { + if (!seenUids.box[boxUid]) { + seenUids.box[boxUid] = true; + const offset = boxUid * 4; + if ((x1 <= bboxes[offset + 2]) && + (y1 <= bboxes[offset + 3]) && + (x2 >= bboxes[offset + 0]) && + (y2 >= bboxes[offset + 1]) && + (!predicate || predicate(this.boxKeys[boxUid]))) { + if (queryArgs.hitTest) { + result.push(true); + return true; + } else { + result.push({ + key: this.boxKeys[boxUid], + x1: bboxes[offset], + y1: bboxes[offset + 1], + x2: bboxes[offset + 2], + y2: bboxes[offset + 3] + }); + } + } + } + } + } + const circleCell = this.circleCells[cellIndex]; + if (circleCell !== null) { + const circles = this.circles; + for (const circleUid of circleCell) { + if (!seenUids.circle[circleUid]) { + seenUids.circle[circleUid] = true; + const offset = circleUid * 3; + if (this._circleAndRectCollide( + circles[offset], + circles[offset + 1], + circles[offset + 2], + x1, + y1, + x2, + y2) && + (!predicate || predicate(this.circleKeys[circleUid]))) { + if (queryArgs.hitTest) { + result.push(true); + return true; + } else { + const x = circles[offset]; + const y = circles[offset + 1]; + const radius = circles[offset + 2]; + result.push({ + key: this.circleKeys[circleUid], + x1: x - radius, + y1: y - radius, + x2: x + radius, + y2: y + radius + }); + } + } + } + } + } + } + + _queryCellCircle(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: any, queryArgs: any, predicate?: any) { + const circle = queryArgs.circle; + const seenUids = queryArgs.seenUids; + const boxCell = this.boxCells[cellIndex]; + if (boxCell !== null) { + const bboxes = this.bboxes; + for (const boxUid of boxCell) { + if (!seenUids.box[boxUid]) { + seenUids.box[boxUid] = true; + const offset = boxUid * 4; + if (this._circleAndRectCollide( + circle.x, + circle.y, + circle.radius, + bboxes[offset + 0], + bboxes[offset + 1], + bboxes[offset + 2], + bboxes[offset + 3]) && + (!predicate || predicate(this.boxKeys[boxUid]))) { + result.push(true); + return true; + } + } + } + } + + const circleCell = this.circleCells[cellIndex]; + if (circleCell !== null) { + const circles = this.circles; + for (const circleUid of circleCell) { + if (!seenUids.circle[circleUid]) { + seenUids.circle[circleUid] = true; + const offset = circleUid * 3; + if (this._circlesCollide( + circles[offset], + circles[offset + 1], + circles[offset + 2], + circle.x, + circle.y, + circle.radius) && + (!predicate || predicate(this.circleKeys[circleUid]))) { + result.push(true); + return true; + } + } + } + } + } + + _forEachCell(x1: number, y1: number, x2: number, y2: number, fn: any, arg1: any, arg2?: any, predicate?: any) { + const cx1 = this._convertToXCellCoord(x1); + const cy1 = this._convertToYCellCoord(y1); + const cx2 = this._convertToXCellCoord(x2); + const cy2 = this._convertToYCellCoord(y2); + + for (let x = cx1; x <= cx2; x++) { + for (let y = cy1; y <= cy2; y++) { + const cellIndex = this.xCellCount * y + x; + if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, predicate)) return; + } + } + } + + _convertToXCellCoord(x: number) { + return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(x * this.xScale))); + } + + _convertToYCellCoord(y: number) { + return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(y * this.yScale))); + } + + _circlesCollide(x1: number, y1: number, r1: number, x2: number, y2: number, r2: number): boolean { + const dx = x2 - x1; + const dy = y2 - y1; + const bothRadii = r1 + r2; + return (bothRadii * bothRadii) > (dx * dx + dy * dy); + } + + _circleAndRectCollide(circleX: number, circleY: number, radius: number, x1: number, y1: number, x2: number, y2: number): boolean { + const halfRectWidth = (x2 - x1) / 2; + const distX = Math.abs(circleX - (x1 + halfRectWidth)); + if (distX > (halfRectWidth + radius)) { + return false; + } + + const halfRectHeight = (y2 - y1) / 2; + const distY = Math.abs(circleY - (y1 + halfRectHeight)); + if (distY > (halfRectHeight + radius)) { + return false; + } + + if (distX <= halfRectWidth || distY <= halfRectHeight) { + return true; + } + + const dx = distX - halfRectWidth; + const dy = distY - halfRectHeight; + return (dx * dx + dy * dy <= (radius * radius)); + } +} + +export default GridIndex; diff --git a/node_modules/mapbox-gl/src/symbol/mergelines.js b/node_modules/mapbox-gl/src/symbol/mergelines.js new file mode 100644 index 0000000000000000000000000000000000000000..34b5d383495c4ac5fb5ab4781d734215f326ae40 --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/mergelines.js @@ -0,0 +1,82 @@ +// @flow + +import type {SymbolFeature} from '../data/bucket/symbol_bucket'; + +export default function (features: Array): Array { + const leftIndex: {[_: string]: number} = {}; + const rightIndex: {[_: string]: number} = {}; + const mergedFeatures = []; + let mergedIndex = 0; + + function add(k) { + mergedFeatures.push(features[k]); + mergedIndex++; + } + + function mergeFromRight(leftKey: string, rightKey: string, geom) { + const i = rightIndex[leftKey]; + delete rightIndex[leftKey]; + rightIndex[rightKey] = i; + + mergedFeatures[i].geometry[0].pop(); + mergedFeatures[i].geometry[0] = mergedFeatures[i].geometry[0].concat(geom[0]); + return i; + } + + function mergeFromLeft(leftKey: string, rightKey: string, geom) { + const i = leftIndex[rightKey]; + delete leftIndex[rightKey]; + leftIndex[leftKey] = i; + + mergedFeatures[i].geometry[0].shift(); + mergedFeatures[i].geometry[0] = geom[0].concat(mergedFeatures[i].geometry[0]); + return i; + } + + function getKey(text, geom, onRight) { + const point = onRight ? geom[0][geom[0].length - 1] : geom[0][0]; + return `${text}:${point.x}:${point.y}`; + } + + for (let k = 0; k < features.length; k++) { + const feature = features[k]; + const geom = feature.geometry; + const text = feature.text ? feature.text.toString() : null; + + if (!text) { + add(k); + continue; + } + + const leftKey = getKey(text, geom), + rightKey = getKey(text, geom, true); + + if ((leftKey in rightIndex) && (rightKey in leftIndex) && (rightIndex[leftKey] !== leftIndex[rightKey])) { + // found lines with the same text adjacent to both ends of the current line, merge all three + const j = mergeFromLeft(leftKey, rightKey, geom); + const i = mergeFromRight(leftKey, rightKey, mergedFeatures[j].geometry); + + delete leftIndex[leftKey]; + delete rightIndex[rightKey]; + + rightIndex[getKey(text, mergedFeatures[i].geometry, true)] = i; + mergedFeatures[j].geometry = (null: any); + + } else if (leftKey in rightIndex) { + // found mergeable line adjacent to the start of the current line, merge + mergeFromRight(leftKey, rightKey, geom); + + } else if (rightKey in leftIndex) { + // found mergeable line adjacent to the end of the current line, merge + mergeFromLeft(leftKey, rightKey, geom); + + } else { + // no adjacent lines, add as a new item + add(k); + leftIndex[leftKey] = mergedIndex - 1; + rightIndex[rightKey] = mergedIndex - 1; + } + } + + return mergedFeatures.filter((f) => f.geometry); +} diff --git a/node_modules/mapbox-gl/src/symbol/one_em.js b/node_modules/mapbox-gl/src/symbol/one_em.js new file mode 100644 index 0000000000000000000000000000000000000000..7e20115bd9625c3f50b9d196358b458d50982c8a --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/one_em.js @@ -0,0 +1,4 @@ +// @flow +// ONE_EM constant used to go between "em" units used in style spec and "points" used internally for layout + +export default 24; diff --git a/node_modules/mapbox-gl/src/symbol/opacity_state.js b/node_modules/mapbox-gl/src/symbol/opacity_state.js new file mode 100644 index 0000000000000000000000000000000000000000..1649b2c2a0f603bbd7b0924b28848c06938fec50 --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/opacity_state.js @@ -0,0 +1,27 @@ +// @flow + +import {register} from '../util/web_worker_transfer'; + +class OpacityState { + opacity: number; + targetOpacity: number; + time: number + + constructor() { + this.opacity = 0; + this.targetOpacity = 0; + this.time = 0; + } + + clone() { + const clone = new OpacityState(); + clone.opacity = this.opacity; + clone.targetOpacity = this.targetOpacity; + clone.time = this.time; + return clone; + } +} + +register('OpacityState', OpacityState); + +export default OpacityState; diff --git a/node_modules/mapbox-gl/src/symbol/path_interpolator.js b/node_modules/mapbox-gl/src/symbol/path_interpolator.js new file mode 100644 index 0000000000000000000000000000000000000000..f64467a5a99cb441bd51d9af041afb9df8fc714a --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/path_interpolator.js @@ -0,0 +1,61 @@ +// @flow + +import {clamp} from '../util/util'; +import Point from '@mapbox/point-geometry'; +import assert from 'assert'; + +class PathInterpolator { + points: Array; + length: number; + paddedLength: number; + padding: number; + _distances: Array; + + constructor(points_: ?Array, padding_: ?number) { + this.reset(points_, padding_); + } + + reset(points_: ?Array, padding_: ?number) { + this.points = points_ || []; + + // Compute cumulative distance from first point to every other point in the segment. + // Last entry in the array is total length of the path + this._distances = [0.0]; + + for (let i = 1; i < this.points.length; i++) { + this._distances[i] = this._distances[i - 1] + this.points[i].dist(this.points[i - 1]); + } + + this.length = this._distances[this._distances.length - 1]; + this.padding = Math.min(padding_ || 0, this.length * 0.5); + this.paddedLength = this.length - this.padding * 2.0; + } + + lerp(t: number): Point { + assert(this.points.length > 0); + if (this.points.length === 1) { + return this.points[0]; + } + + t = clamp(t, 0, 1); + + // Find the correct segment [p0, p1] where p0 <= x < p1 + let currentIndex = 1; + let distOfCurrentIdx = this._distances[currentIndex]; + const distToTarget = t * this.paddedLength + this.padding; + + while (distOfCurrentIdx < distToTarget && currentIndex < this._distances.length) { + distOfCurrentIdx = this._distances[++currentIndex]; + } + + // Interpolate between the two points of the segment + const idxOfPrevPoint = currentIndex - 1; + const distOfPrevIdx = this._distances[idxOfPrevPoint]; + const segmentLength = distOfCurrentIdx - distOfPrevIdx; + const segmentT = segmentLength > 0 ? (distToTarget - distOfPrevIdx) / segmentLength : 0; + + return this.points[idxOfPrevPoint].mult(1.0 - segmentT).add(this.points[currentIndex].mult(segmentT)); + } +} + +export default PathInterpolator; diff --git a/node_modules/mapbox-gl/src/symbol/placement.js b/node_modules/mapbox-gl/src/symbol/placement.js new file mode 100644 index 0000000000000000000000000000000000000000..b7e06fb865af552e967d8bc676f23c9d556abf57 --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/placement.js @@ -0,0 +1,1124 @@ +// @flow + +import CollisionIndex from './collision_index'; +import EXTENT from '../data/extent'; +import * as symbolSize from './symbol_size'; +import * as projection from './projection'; +import {getAnchorJustification, evaluateVariableOffset} from './symbol_layout'; +import {getAnchorAlignment, WritingMode} from './shaping'; +import {mat4} from 'gl-matrix'; +import assert from 'assert'; +import pixelsToTileUnits from '../source/pixels_to_tile_units'; +import Point from '@mapbox/point-geometry'; +import type Transform from '../geo/transform'; +import type StyleLayer from '../style/style_layer'; + +import type Tile from '../source/tile'; +import type SymbolBucket, {CollisionArrays, SingleCollisionBox} from '../data/bucket/symbol_bucket'; +import type {CollisionBoxArray, CollisionVertexArray, SymbolInstance} from '../data/array_types'; +import type FeatureIndex from '../data/feature_index'; +import type {OverscaledTileID} from '../source/tile_id'; +import type {TextAnchor} from './symbol_layout'; + +class OpacityState { + opacity: number; + placed: boolean; + constructor(prevState: ?OpacityState, increment: number, placed: boolean, skipFade: ?boolean) { + if (prevState) { + this.opacity = Math.max(0, Math.min(1, prevState.opacity + (prevState.placed ? increment : -increment))); + } else { + this.opacity = (skipFade && placed) ? 1 : 0; + } + this.placed = placed; + } + isHidden() { + return this.opacity === 0 && !this.placed; + } +} + +class JointOpacityState { + text: OpacityState; + icon: OpacityState; + constructor(prevState: ?JointOpacityState, increment: number, placedText: boolean, placedIcon: boolean, skipFade: ?boolean) { + this.text = new OpacityState(prevState ? prevState.text : null, increment, placedText, skipFade); + this.icon = new OpacityState(prevState ? prevState.icon : null, increment, placedIcon, skipFade); + } + isHidden() { + return this.text.isHidden() && this.icon.isHidden(); + } +} + +class JointPlacement { + text: boolean; + icon: boolean; + // skipFade = outside viewport, but within CollisionIndex::viewportPadding px of the edge + // Because these symbols aren't onscreen yet, we can skip the "fade in" animation, + // and if a subsequent viewport change brings them into view, they'll be fully + // visible right away. + skipFade: boolean; + constructor(text: boolean, icon: boolean, skipFade: boolean) { + this.text = text; + this.icon = icon; + this.skipFade = skipFade; + } +} + +class CollisionCircleArray { + // Stores collision circles and placement matrices of a bucket for debug rendering. + invProjMatrix: mat4; + viewportMatrix: mat4; + circles: Array; + + constructor() { + this.invProjMatrix = mat4.create(); + this.viewportMatrix = mat4.create(); + this.circles = []; + } +} + +export class RetainedQueryData { + bucketInstanceId: number; + featureIndex: FeatureIndex; + sourceLayerIndex: number; + bucketIndex: number; + tileID: OverscaledTileID; + featureSortOrder: ?Array + constructor(bucketInstanceId: number, + featureIndex: FeatureIndex, + sourceLayerIndex: number, + bucketIndex: number, + tileID: OverscaledTileID) { + this.bucketInstanceId = bucketInstanceId; + this.featureIndex = featureIndex; + this.sourceLayerIndex = sourceLayerIndex; + this.bucketIndex = bucketIndex; + this.tileID = tileID; + } +} + +type CollisionGroup = { ID: number, predicate?: any }; + +class CollisionGroups { + collisionGroups: {[groupName: string]: CollisionGroup}; + maxGroupID: number; + crossSourceCollisions: boolean; + + constructor(crossSourceCollisions: boolean) { + this.crossSourceCollisions = crossSourceCollisions; + this.maxGroupID = 0; + this.collisionGroups = {}; + } + + get(sourceID: string) { + // The predicate/groupID mechanism allows for arbitrary grouping, + // but the current interface defines one source == one group when + // crossSourceCollisions == true. + if (!this.crossSourceCollisions) { + if (!this.collisionGroups[sourceID]) { + const nextGroupID = ++this.maxGroupID; + this.collisionGroups[sourceID] = { + ID: nextGroupID, + predicate: (key) => { + return key.collisionGroupID === nextGroupID; + } + }; + } + return this.collisionGroups[sourceID]; + } else { + return {ID: 0, predicate: null}; + } + } +} + +function calculateVariableLayoutShift(anchor: TextAnchor, width: number, height: number, textOffset: [number, number], textBoxScale: number): Point { + const {horizontalAlign, verticalAlign} = getAnchorAlignment(anchor); + const shiftX = -(horizontalAlign - 0.5) * width; + const shiftY = -(verticalAlign - 0.5) * height; + const offset = evaluateVariableOffset(anchor, textOffset); + return new Point( + shiftX + offset[0] * textBoxScale, + shiftY + offset[1] * textBoxScale + ); +} + +function shiftVariableCollisionBox(collisionBox: SingleCollisionBox, + shiftX: number, shiftY: number, + rotateWithMap: boolean, pitchWithMap: boolean, + angle: number) { + const {x1, x2, y1, y2, anchorPointX, anchorPointY} = collisionBox; + const rotatedOffset = new Point(shiftX, shiftY); + if (rotateWithMap) { + rotatedOffset._rotate(pitchWithMap ? angle : -angle); + } + return { + x1: x1 + rotatedOffset.x, + y1: y1 + rotatedOffset.y, + x2: x2 + rotatedOffset.x, + y2: y2 + rotatedOffset.y, + // symbol anchor point stays the same regardless of text-anchor + anchorPointX, + anchorPointY + }; +} + +export type VariableOffset = { + textOffset: [number, number], + width: number, + height: number, + anchor: TextAnchor, + textBoxScale: number, + prevAnchor?: TextAnchor +}; + +type TileLayerParameters = { + bucket: SymbolBucket, + layout: any, + posMatrix: mat4, + textLabelPlaneMatrix: mat4, + labelToScreenMatrix: mat4, + scale: number, + textPixelRatio: number, + holdingForFade: boolean, + collisionBoxArray: ?CollisionBoxArray, + partiallyEvaluatedTextSize: any, + collisionGroup: any +}; + +export type BucketPart = { + sortKey?: number | void, + symbolInstanceStart: number, + symbolInstanceEnd: number, + parameters: TileLayerParameters +}; + +export type CrossTileID = string | number; + +export class Placement { + transform: Transform; + collisionIndex: CollisionIndex; + placements: { [_: CrossTileID]: JointPlacement }; + opacities: { [_: CrossTileID]: JointOpacityState }; + variableOffsets: {[_: CrossTileID]: VariableOffset }; + placedOrientations: {[_: CrossTileID]: number }; + commitTime: number; + prevZoomAdjustment: number; + lastPlacementChangeTime: number; + stale: boolean; + fadeDuration: number; + retainedQueryData: {[_: number]: RetainedQueryData}; + collisionGroups: CollisionGroups; + prevPlacement: ?Placement; + zoomAtLastRecencyCheck: number; + collisionCircleArrays: {[any]: CollisionCircleArray}; + + constructor(transform: Transform, fadeDuration: number, crossSourceCollisions: boolean, prevPlacement?: Placement) { + this.transform = transform.clone(); + this.collisionIndex = new CollisionIndex(this.transform); + this.placements = {}; + this.opacities = {}; + this.variableOffsets = {}; + this.stale = false; + this.commitTime = 0; + this.fadeDuration = fadeDuration; + this.retainedQueryData = {}; + this.collisionGroups = new CollisionGroups(crossSourceCollisions); + this.collisionCircleArrays = {}; + + this.prevPlacement = prevPlacement; + if (prevPlacement) { + prevPlacement.prevPlacement = undefined; // Only hold on to one placement back + } + + this.placedOrientations = {}; + } + + getBucketParts(results: Array, styleLayer: StyleLayer, tile: Tile, sortAcrossTiles: boolean) { + const symbolBucket = ((tile.getBucket(styleLayer): any): SymbolBucket); + const bucketFeatureIndex = tile.latestFeatureIndex; + if (!symbolBucket || !bucketFeatureIndex || styleLayer.id !== symbolBucket.layerIds[0]) + return; + + const collisionBoxArray = tile.collisionBoxArray; + + const layout = symbolBucket.layers[0].layout; + + const scale = Math.pow(2, this.transform.zoom - tile.tileID.overscaledZ); + const textPixelRatio = tile.tileSize / EXTENT; + + const posMatrix = this.transform.calculatePosMatrix(tile.tileID.toUnwrapped()); + + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pixelsToTiles = pixelsToTileUnits(tile, 1, this.transform.zoom); + + const textLabelPlaneMatrix = projection.getLabelPlaneMatrix(posMatrix, + pitchWithMap, + rotateWithMap, + this.transform, + pixelsToTiles); + + let labelToScreenMatrix = null; + + if (pitchWithMap) { + const glMatrix = projection.getGlCoordMatrix( + posMatrix, + pitchWithMap, + rotateWithMap, + this.transform, + pixelsToTiles); + + labelToScreenMatrix = mat4.multiply([], this.transform.labelPlaneMatrix, glMatrix); + } + + // As long as this placement lives, we have to hold onto this bucket's + // matching FeatureIndex/data for querying purposes + this.retainedQueryData[symbolBucket.bucketInstanceId] = new RetainedQueryData( + symbolBucket.bucketInstanceId, + bucketFeatureIndex, + symbolBucket.sourceLayerIndex, + symbolBucket.index, + tile.tileID + ); + + const parameters = { + bucket: symbolBucket, + layout, + posMatrix, + textLabelPlaneMatrix, + labelToScreenMatrix, + scale, + textPixelRatio, + holdingForFade: tile.holdingForFade(), + collisionBoxArray, + partiallyEvaluatedTextSize: symbolSize.evaluateSizeForZoom(symbolBucket.textSizeData, this.transform.zoom), + collisionGroup: this.collisionGroups.get(symbolBucket.sourceID) + }; + + if (sortAcrossTiles) { + for (const range of symbolBucket.sortKeyRanges) { + const {sortKey, symbolInstanceStart, symbolInstanceEnd} = range; + results.push({sortKey, symbolInstanceStart, symbolInstanceEnd, parameters}); + } + } else { + results.push({ + symbolInstanceStart: 0, + symbolInstanceEnd: symbolBucket.symbolInstances.length, + parameters + }); + } + } + + attemptAnchorPlacement(anchor: TextAnchor, textBox: SingleCollisionBox, width: number, height: number, + textBoxScale: number, rotateWithMap: boolean, + pitchWithMap: boolean, textPixelRatio: number, posMatrix: mat4, collisionGroup: CollisionGroup, + textAllowOverlap: boolean, symbolInstance: SymbolInstance, bucket: SymbolBucket, orientation: number, iconBox: ?SingleCollisionBox): ?{ shift: Point, placedGlyphBoxes: { box: Array, offscreen: boolean } } { + + const textOffset = [symbolInstance.textOffset0, symbolInstance.textOffset1]; + const shift = calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale); + + const placedGlyphBoxes = this.collisionIndex.placeCollisionBox( + shiftVariableCollisionBox( + textBox, shift.x, shift.y, + rotateWithMap, pitchWithMap, this.transform.angle), + textAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate); + + if (iconBox) { + const placedIconBoxes = this.collisionIndex.placeCollisionBox( + shiftVariableCollisionBox( + iconBox, shift.x, shift.y, + rotateWithMap, pitchWithMap, this.transform.angle), + textAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate); + if (placedIconBoxes.box.length === 0) return; + } + + if (placedGlyphBoxes.box.length > 0) { + let prevAnchor; + // If this label was placed in the previous placement, record the anchor position + // to allow us to animate the transition + if (this.prevPlacement && + this.prevPlacement.variableOffsets[symbolInstance.crossTileID] && + this.prevPlacement.placements[symbolInstance.crossTileID] && + this.prevPlacement.placements[symbolInstance.crossTileID].text) { + prevAnchor = this.prevPlacement.variableOffsets[symbolInstance.crossTileID].anchor; + } + assert(symbolInstance.crossTileID !== 0); + this.variableOffsets[symbolInstance.crossTileID] = { + textOffset, + width, + height, + anchor, + textBoxScale, + prevAnchor + }; + this.markUsedJustification(bucket, anchor, symbolInstance, orientation); + + if (bucket.allowVerticalPlacement) { + this.markUsedOrientation(bucket, orientation, symbolInstance); + this.placedOrientations[symbolInstance.crossTileID] = orientation; + } + + return {shift, placedGlyphBoxes}; + } + } + + placeLayerBucketPart(bucketPart: Object, seenCrossTileIDs: { [string | number]: boolean }, showCollisionBoxes: boolean) { + + const { + bucket, + layout, + posMatrix, + textLabelPlaneMatrix, + labelToScreenMatrix, + textPixelRatio, + holdingForFade, + collisionBoxArray, + partiallyEvaluatedTextSize, + collisionGroup + } = bucketPart.parameters; + + const textOptional = layout.get('text-optional'); + const iconOptional = layout.get('icon-optional'); + const textAllowOverlap = layout.get('text-allow-overlap'); + const iconAllowOverlap = layout.get('icon-allow-overlap'); + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const hasIconTextFit = layout.get('icon-text-fit') !== 'none'; + const zOrderByViewportY = layout.get('symbol-z-order') === 'viewport-y'; + + // This logic is similar to the "defaultOpacityState" logic below in updateBucketOpacities + // If we know a symbol is always supposed to show, force it to be marked visible even if + // it wasn't placed into the collision index (because some or all of it was outside the range + // of the collision grid). + // There is a subtle edge case here we're accepting: + // Symbol A has text-allow-overlap: true, icon-allow-overlap: true, icon-optional: false + // A's icon is outside the grid, so doesn't get placed + // A's text would be inside grid, but doesn't get placed because of icon-optional: false + // We still show A because of the allow-overlap settings. + // Symbol B has allow-overlap: false, and gets placed where A's text would be + // On panning in, there is a short period when Symbol B and Symbol A will overlap + // This is the reverse of our normal policy of "fade in on pan", but should look like any other + // collision and hopefully not be too noticeable. + // See https://github.com/mapbox/mapbox-gl-js/issues/7172 + const alwaysShowText = textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || iconOptional); + const alwaysShowIcon = iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || textOptional); + + if (!bucket.collisionArrays && collisionBoxArray) { + bucket.deserializeCollisionBoxes(collisionBoxArray); + } + + const placeSymbol = (symbolInstance: SymbolInstance, collisionArrays: CollisionArrays) => { + if (seenCrossTileIDs[symbolInstance.crossTileID]) return; + if (holdingForFade) { + // Mark all symbols from this tile as "not placed", but don't add to seenCrossTileIDs, because we don't + // know yet if we have a duplicate in a parent tile that _should_ be placed. + this.placements[symbolInstance.crossTileID] = new JointPlacement(false, false, false); + return; + } + + let placeText = false; + let placeIcon = false; + let offscreen = true; + let shift = null; + + let placed = {box: null, offscreen: null}; + let placedVerticalText = {box: null, offscreen: null}; + + let placedGlyphBoxes = null; + let placedGlyphCircles = null; + let placedIconBoxes = null; + let textFeatureIndex = 0; + let verticalTextFeatureIndex = 0; + let iconFeatureIndex = 0; + + if (collisionArrays.textFeatureIndex) { + textFeatureIndex = collisionArrays.textFeatureIndex; + } else if (symbolInstance.useRuntimeCollisionCircles) { + textFeatureIndex = symbolInstance.featureIndex; + } + if (collisionArrays.verticalTextFeatureIndex) { + verticalTextFeatureIndex = collisionArrays.verticalTextFeatureIndex; + } + + const textBox = collisionArrays.textBox; + if (textBox) { + + const updatePreviousOrientationIfNotPlaced = (isPlaced) => { + let previousOrientation = WritingMode.horizontal; + if (bucket.allowVerticalPlacement && !isPlaced && this.prevPlacement) { + const prevPlacedOrientation = this.prevPlacement.placedOrientations[symbolInstance.crossTileID]; + if (prevPlacedOrientation) { + this.placedOrientations[symbolInstance.crossTileID] = prevPlacedOrientation; + previousOrientation = prevPlacedOrientation; + this.markUsedOrientation(bucket, previousOrientation, symbolInstance); + } + } + return previousOrientation; + }; + + const placeTextForPlacementModes = (placeHorizontalFn, placeVerticalFn) => { + if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && collisionArrays.verticalTextBox) { + for (const placementMode of bucket.writingModes) { + if (placementMode === WritingMode.vertical) { + placed = placeVerticalFn(); + placedVerticalText = placed; + } else { + placed = placeHorizontalFn(); + } + if (placed && placed.box && placed.box.length) break; + } + } else { + placed = placeHorizontalFn(); + } + }; + + if (!layout.get('text-variable-anchor')) { + const placeBox = (collisionTextBox, orientation) => { + const placedFeature = this.collisionIndex.placeCollisionBox(collisionTextBox, textAllowOverlap, + textPixelRatio, posMatrix, collisionGroup.predicate); + if (placedFeature && placedFeature.box && placedFeature.box.length) { + this.markUsedOrientation(bucket, orientation, symbolInstance); + this.placedOrientations[symbolInstance.crossTileID] = orientation; + } + return placedFeature; + }; + + const placeHorizontal = () => { + return placeBox(textBox, WritingMode.horizontal); + }; + + const placeVertical = () => { + const verticalTextBox = collisionArrays.verticalTextBox; + if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) { + return placeBox(verticalTextBox, WritingMode.vertical); + } + return {box: null, offscreen: null}; + }; + + placeTextForPlacementModes(placeHorizontal, placeVertical); + updatePreviousOrientationIfNotPlaced(placed && placed.box && placed.box.length); + + } else { + let anchors = layout.get('text-variable-anchor'); + + // If this symbol was in the last placement, shift the previously used + // anchor to the front of the anchor list, only if the previous anchor + // is still in the anchor list + if (this.prevPlacement && this.prevPlacement.variableOffsets[symbolInstance.crossTileID]) { + const prevOffsets = this.prevPlacement.variableOffsets[symbolInstance.crossTileID]; + if (anchors.indexOf(prevOffsets.anchor) > 0) { + anchors = anchors.filter(anchor => anchor !== prevOffsets.anchor); + anchors.unshift(prevOffsets.anchor); + } + } + + const placeBoxForVariableAnchors = (collisionTextBox, collisionIconBox, orientation) => { + const width = collisionTextBox.x2 - collisionTextBox.x1; + const height = collisionTextBox.y2 - collisionTextBox.y1; + const textBoxScale = symbolInstance.textBoxScale; + + const variableIconBox = hasIconTextFit && !iconAllowOverlap ? collisionIconBox : null; + + let placedBox: ?{ box: Array, offscreen: boolean } = {box: [], offscreen: false}; + const placementAttempts = textAllowOverlap ? anchors.length * 2 : anchors.length; + for (let i = 0; i < placementAttempts; ++i) { + const anchor = anchors[i % anchors.length]; + const allowOverlap = (i >= anchors.length); + const result = this.attemptAnchorPlacement( + anchor, collisionTextBox, width, height, + textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix, + collisionGroup, allowOverlap, symbolInstance, bucket, orientation, variableIconBox); + + if (result) { + placedBox = result.placedGlyphBoxes; + if (placedBox && placedBox.box && placedBox.box.length) { + placeText = true; + shift = result.shift; + break; + } + } + } + + return placedBox; + }; + + const placeHorizontal = () => { + return placeBoxForVariableAnchors(textBox, collisionArrays.iconBox, WritingMode.horizontal); + }; + + const placeVertical = () => { + const verticalTextBox = collisionArrays.verticalTextBox; + const wasPlaced = placed && placed.box && placed.box.length; + if (bucket.allowVerticalPlacement && !wasPlaced && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) { + return placeBoxForVariableAnchors(verticalTextBox, collisionArrays.verticalIconBox, WritingMode.vertical); + } + return {box: null, offscreen: null}; + }; + + placeTextForPlacementModes(placeHorizontal, placeVertical); + + if (placed) { + placeText = placed.box; + offscreen = placed.offscreen; + } + + const prevOrientation = updatePreviousOrientationIfNotPlaced(placed && placed.box); + + // If we didn't get placed, we still need to copy our position from the last placement for + // fade animations + if (!placeText && this.prevPlacement) { + const prevOffset = this.prevPlacement.variableOffsets[symbolInstance.crossTileID]; + if (prevOffset) { + this.variableOffsets[symbolInstance.crossTileID] = prevOffset; + this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, prevOrientation); + } + } + + } + } + + placedGlyphBoxes = placed; + placeText = placedGlyphBoxes && placedGlyphBoxes.box && placedGlyphBoxes.box.length > 0; + + offscreen = placedGlyphBoxes && placedGlyphBoxes.offscreen; + + if (symbolInstance.useRuntimeCollisionCircles) { + const placedSymbol = bucket.text.placedSymbolArray.get(symbolInstance.centerJustifiedTextSymbolIndex); + const fontSize = symbolSize.evaluateSizeForFeature(bucket.textSizeData, partiallyEvaluatedTextSize, placedSymbol); + + const textPixelPadding = layout.get('text-padding'); + const circlePixelDiameter = symbolInstance.collisionCircleDiameter; + + placedGlyphCircles = this.collisionIndex.placeCollisionCircles(textAllowOverlap, + placedSymbol, + bucket.lineVertexArray, + bucket.glyphOffsetArray, + fontSize, + posMatrix, + textLabelPlaneMatrix, + labelToScreenMatrix, + showCollisionBoxes, + pitchWithMap, + collisionGroup.predicate, + circlePixelDiameter, + textPixelPadding); + + assert(!placedGlyphCircles.circles.length || (!placedGlyphCircles.collisionDetected || showCollisionBoxes)); + // If text-allow-overlap is set, force "placedCircles" to true + // In theory there should always be at least one circle placed + // in this case, but for now quirks in text-anchor + // and text-offset may prevent that from being true. + placeText = textAllowOverlap || (placedGlyphCircles.circles.length > 0 && !placedGlyphCircles.collisionDetected); + offscreen = offscreen && placedGlyphCircles.offscreen; + } + + if (collisionArrays.iconFeatureIndex) { + iconFeatureIndex = collisionArrays.iconFeatureIndex; + } + + if (collisionArrays.iconBox) { + + const placeIconFeature = iconBox => { + const shiftedIconBox = hasIconTextFit && shift ? + shiftVariableCollisionBox( + iconBox, shift.x, shift.y, + rotateWithMap, pitchWithMap, this.transform.angle) : + iconBox; + return this.collisionIndex.placeCollisionBox(shiftedIconBox, + iconAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate); + }; + + if (placedVerticalText && placedVerticalText.box && placedVerticalText.box.length && collisionArrays.verticalIconBox) { + placedIconBoxes = placeIconFeature(collisionArrays.verticalIconBox); + placeIcon = placedIconBoxes.box.length > 0; + } else { + placedIconBoxes = placeIconFeature(collisionArrays.iconBox); + placeIcon = placedIconBoxes.box.length > 0; + } + offscreen = offscreen && placedIconBoxes.offscreen; + } + + const iconWithoutText = textOptional || + (symbolInstance.numHorizontalGlyphVertices === 0 && symbolInstance.numVerticalGlyphVertices === 0); + const textWithoutIcon = iconOptional || symbolInstance.numIconVertices === 0; + + // Combine the scales for icons and text. + if (!iconWithoutText && !textWithoutIcon) { + placeIcon = placeText = placeIcon && placeText; + } else if (!textWithoutIcon) { + placeText = placeIcon && placeText; + } else if (!iconWithoutText) { + placeIcon = placeIcon && placeText; + } + + if (placeText && placedGlyphBoxes && placedGlyphBoxes.box) { + if (placedVerticalText && placedVerticalText.box && verticalTextFeatureIndex) { + this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, layout.get('text-ignore-placement'), + bucket.bucketInstanceId, verticalTextFeatureIndex, collisionGroup.ID); + } else { + this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, layout.get('text-ignore-placement'), + bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID); + } + + } + if (placeIcon && placedIconBoxes) { + this.collisionIndex.insertCollisionBox(placedIconBoxes.box, layout.get('icon-ignore-placement'), + bucket.bucketInstanceId, iconFeatureIndex, collisionGroup.ID); + } + if (placedGlyphCircles) { + if (placeText) { + this.collisionIndex.insertCollisionCircles(placedGlyphCircles.circles, layout.get('text-ignore-placement'), + bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID); + } + + if (showCollisionBoxes) { + const id = bucket.bucketInstanceId; + let circleArray = this.collisionCircleArrays[id]; + + // Group collision circles together by bucket. Circles can't be pushed forward for rendering yet as the symbol placement + // for a bucket is not guaranteed to be complete before the commit-function has been called + if (circleArray === undefined) + circleArray = this.collisionCircleArrays[id] = new CollisionCircleArray(); + + for (let i = 0; i < placedGlyphCircles.circles.length; i += 4) { + circleArray.circles.push(placedGlyphCircles.circles[i + 0]); // x + circleArray.circles.push(placedGlyphCircles.circles[i + 1]); // y + circleArray.circles.push(placedGlyphCircles.circles[i + 2]); // radius + circleArray.circles.push(placedGlyphCircles.collisionDetected ? 1 : 0); // collisionDetected-flag + } + } + } + + assert(symbolInstance.crossTileID !== 0); + assert(bucket.bucketInstanceId !== 0); + + this.placements[symbolInstance.crossTileID] = new JointPlacement(placeText || alwaysShowText, placeIcon || alwaysShowIcon, offscreen || bucket.justReloaded); + seenCrossTileIDs[symbolInstance.crossTileID] = true; + }; + + if (zOrderByViewportY) { + assert(bucketPart.symbolInstanceStart === 0); + const symbolIndexes = bucket.getSortedSymbolIndexes(this.transform.angle); + for (let i = symbolIndexes.length - 1; i >= 0; --i) { + const symbolIndex = symbolIndexes[i]; + placeSymbol(bucket.symbolInstances.get(symbolIndex), bucket.collisionArrays[symbolIndex]); + } + } else { + for (let i = bucketPart.symbolInstanceStart; i < bucketPart.symbolInstanceEnd; i++) { + placeSymbol(bucket.symbolInstances.get(i), bucket.collisionArrays[i]); + } + } + + if (showCollisionBoxes && bucket.bucketInstanceId in this.collisionCircleArrays) { + const circleArray = this.collisionCircleArrays[bucket.bucketInstanceId]; + + // Store viewport and inverse projection matrices per bucket + mat4.invert(circleArray.invProjMatrix, posMatrix); + circleArray.viewportMatrix = this.collisionIndex.getViewportMatrix(); + } + + bucket.justReloaded = false; + } + + markUsedJustification(bucket: SymbolBucket, placedAnchor: TextAnchor, symbolInstance: SymbolInstance, orientation: number) { + const justifications = { + "left": symbolInstance.leftJustifiedTextSymbolIndex, + "center": symbolInstance.centerJustifiedTextSymbolIndex, + "right": symbolInstance.rightJustifiedTextSymbolIndex + }; + + let autoIndex; + if (orientation === WritingMode.vertical) { + autoIndex = symbolInstance.verticalPlacedTextSymbolIndex; + } else { + autoIndex = justifications[getAnchorJustification(placedAnchor)]; + } + + const indexes = [ + symbolInstance.leftJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.rightJustifiedTextSymbolIndex, + symbolInstance.verticalPlacedTextSymbolIndex + ]; + + for (const index of indexes) { + if (index >= 0) { + if (autoIndex >= 0 && index !== autoIndex) { + // There are multiple justifications and this one isn't it: shift offscreen + bucket.text.placedSymbolArray.get(index).crossTileID = 0; + } else { + // Either this is the chosen justification or the justification is hardwired: use this one + bucket.text.placedSymbolArray.get(index).crossTileID = symbolInstance.crossTileID; + } + } + } + } + + markUsedOrientation(bucket: SymbolBucket, orientation: number, symbolInstance: SymbolInstance) { + const horizontal = (orientation === WritingMode.horizontal || orientation === WritingMode.horizontalOnly) ? orientation : 0; + const vertical = orientation === WritingMode.vertical ? orientation : 0; + + const horizontalIndexes = [ + symbolInstance.leftJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.rightJustifiedTextSymbolIndex + ]; + + for (const index of horizontalIndexes) { + bucket.text.placedSymbolArray.get(index).placedOrientation = horizontal; + } + + if (symbolInstance.verticalPlacedTextSymbolIndex) { + bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).placedOrientation = vertical; + } + } + + commit(now: number): void { + this.commitTime = now; + this.zoomAtLastRecencyCheck = this.transform.zoom; + + const prevPlacement = this.prevPlacement; + let placementChanged = false; + + this.prevZoomAdjustment = prevPlacement ? prevPlacement.zoomAdjustment(this.transform.zoom) : 0; + const increment = prevPlacement ? prevPlacement.symbolFadeChange(now) : 1; + + const prevOpacities = prevPlacement ? prevPlacement.opacities : {}; + const prevOffsets = prevPlacement ? prevPlacement.variableOffsets : {}; + const prevOrientations = prevPlacement ? prevPlacement.placedOrientations : {}; + + // add the opacities from the current placement, and copy their current values from the previous placement + for (const crossTileID in this.placements) { + const jointPlacement = this.placements[crossTileID]; + const prevOpacity = prevOpacities[crossTileID]; + if (prevOpacity) { + this.opacities[crossTileID] = new JointOpacityState(prevOpacity, increment, jointPlacement.text, jointPlacement.icon); + placementChanged = placementChanged || + jointPlacement.text !== prevOpacity.text.placed || + jointPlacement.icon !== prevOpacity.icon.placed; + } else { + this.opacities[crossTileID] = new JointOpacityState(null, increment, jointPlacement.text, jointPlacement.icon, jointPlacement.skipFade); + placementChanged = placementChanged || jointPlacement.text || jointPlacement.icon; + } + } + + // copy and update values from the previous placement that aren't in the current placement but haven't finished fading + for (const crossTileID in prevOpacities) { + const prevOpacity = prevOpacities[crossTileID]; + if (!this.opacities[crossTileID]) { + const jointOpacity = new JointOpacityState(prevOpacity, increment, false, false); + if (!jointOpacity.isHidden()) { + this.opacities[crossTileID] = jointOpacity; + placementChanged = placementChanged || prevOpacity.text.placed || prevOpacity.icon.placed; + } + } + } + for (const crossTileID in prevOffsets) { + if (!this.variableOffsets[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) { + this.variableOffsets[crossTileID] = prevOffsets[crossTileID]; + } + } + + for (const crossTileID in prevOrientations) { + if (!this.placedOrientations[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) { + this.placedOrientations[crossTileID] = prevOrientations[crossTileID]; + } + } + + // this.lastPlacementChangeTime is the time of the last commit() that + // resulted in a placement change -- in other words, the start time of + // the last symbol fade animation + assert(!prevPlacement || prevPlacement.lastPlacementChangeTime !== undefined); + if (placementChanged) { + this.lastPlacementChangeTime = now; + } else if (typeof this.lastPlacementChangeTime !== 'number') { + this.lastPlacementChangeTime = prevPlacement ? prevPlacement.lastPlacementChangeTime : now; + } + } + + updateLayerOpacities(styleLayer: StyleLayer, tiles: Array) { + const seenCrossTileIDs = {}; + for (const tile of tiles) { + const symbolBucket = ((tile.getBucket(styleLayer): any): SymbolBucket); + if (symbolBucket && tile.latestFeatureIndex && styleLayer.id === symbolBucket.layerIds[0]) { + this.updateBucketOpacities(symbolBucket, seenCrossTileIDs, tile.collisionBoxArray); + } + } + } + + updateBucketOpacities(bucket: SymbolBucket, seenCrossTileIDs: { [string | number]: boolean }, collisionBoxArray: ?CollisionBoxArray) { + if (bucket.hasTextData()) bucket.text.opacityVertexArray.clear(); + if (bucket.hasIconData()) bucket.icon.opacityVertexArray.clear(); + if (bucket.hasIconCollisionBoxData()) bucket.iconCollisionBox.collisionVertexArray.clear(); + if (bucket.hasTextCollisionBoxData()) bucket.textCollisionBox.collisionVertexArray.clear(); + + const layout = bucket.layers[0].layout; + const duplicateOpacityState = new JointOpacityState(null, 0, false, false, true); + const textAllowOverlap = layout.get('text-allow-overlap'); + const iconAllowOverlap = layout.get('icon-allow-overlap'); + const variablePlacement = layout.get('text-variable-anchor'); + const rotateWithMap = layout.get('text-rotation-alignment') === 'map'; + const pitchWithMap = layout.get('text-pitch-alignment') === 'map'; + const hasIconTextFit = layout.get('icon-text-fit') !== 'none'; + // If allow-overlap is true, we can show symbols before placement runs on them + // But we have to wait for placement if we potentially depend on a paired icon/text + // with allow-overlap: false. + // See https://github.com/mapbox/mapbox-gl-js/issues/7032 + const defaultOpacityState = new JointOpacityState(null, 0, + textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || layout.get('icon-optional')), + iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || layout.get('text-optional')), + true); + + if (!bucket.collisionArrays && collisionBoxArray && ((bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()))) { + bucket.deserializeCollisionBoxes(collisionBoxArray); + } + + const addOpacities = (iconOrText, numVertices: number, opacity: number) => { + for (let i = 0; i < numVertices / 4; i++) { + iconOrText.opacityVertexArray.emplaceBack(opacity); + } + }; + + for (let s = 0; s < bucket.symbolInstances.length; s++) { + const symbolInstance = bucket.symbolInstances.get(s); + const { + numHorizontalGlyphVertices, + numVerticalGlyphVertices, + crossTileID + } = symbolInstance; + + const isDuplicate = seenCrossTileIDs[crossTileID]; + + let opacityState = this.opacities[crossTileID]; + if (isDuplicate) { + opacityState = duplicateOpacityState; + } else if (!opacityState) { + opacityState = defaultOpacityState; + // store the state so that future placements use it as a starting point + this.opacities[crossTileID] = opacityState; + } + + seenCrossTileIDs[crossTileID] = true; + + const hasText = numHorizontalGlyphVertices > 0 || numVerticalGlyphVertices > 0; + const hasIcon = symbolInstance.numIconVertices > 0; + + const placedOrientation = this.placedOrientations[symbolInstance.crossTileID]; + const horizontalHidden = placedOrientation === WritingMode.vertical; + const verticalHidden = placedOrientation === WritingMode.horizontal || placedOrientation === WritingMode.horizontalOnly; + + if (hasText) { + const packedOpacity = packOpacity(opacityState.text); + // Vertical text fades in/out on collision the same way as corresponding + // horizontal text. Switch between vertical/horizontal should be instantaneous + const horizontalOpacity = horizontalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity; + addOpacities(bucket.text, numHorizontalGlyphVertices, horizontalOpacity); + const verticalOpacity = verticalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity; + addOpacities(bucket.text, numVerticalGlyphVertices, verticalOpacity); + + // If this label is completely faded, mark it so that we don't have to calculate + // its position at render time. If this layer has variable placement, shift the various + // symbol instances appropriately so that symbols from buckets that have yet to be placed + // offset appropriately. + const symbolHidden = opacityState.text.isHidden(); + [ + symbolInstance.rightJustifiedTextSymbolIndex, + symbolInstance.centerJustifiedTextSymbolIndex, + symbolInstance.leftJustifiedTextSymbolIndex + ].forEach(index => { + if (index >= 0) { + bucket.text.placedSymbolArray.get(index).hidden = symbolHidden || horizontalHidden ? 1 : 0; + } + }); + + if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) { + bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).hidden = symbolHidden || verticalHidden ? 1 : 0; + } + + const prevOffset = this.variableOffsets[symbolInstance.crossTileID]; + if (prevOffset) { + this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, placedOrientation); + } + + const prevOrientation = this.placedOrientations[symbolInstance.crossTileID]; + if (prevOrientation) { + this.markUsedJustification(bucket, 'left', symbolInstance, prevOrientation); + this.markUsedOrientation(bucket, prevOrientation, symbolInstance); + } + } + + if (hasIcon) { + const packedOpacity = packOpacity(opacityState.icon); + + const useHorizontal = !(hasIconTextFit && symbolInstance.verticalPlacedIconSymbolIndex && horizontalHidden); + + if (symbolInstance.placedIconSymbolIndex >= 0) { + const horizontalOpacity = useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY; + addOpacities(bucket.icon, symbolInstance.numIconVertices, horizontalOpacity); + bucket.icon.placedSymbolArray.get(symbolInstance.placedIconSymbolIndex).hidden = + (opacityState.icon.isHidden(): any); + } + + if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) { + const verticalOpacity = !useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY; + addOpacities(bucket.icon, symbolInstance.numVerticalIconVertices, verticalOpacity); + bucket.icon.placedSymbolArray.get(symbolInstance.verticalPlacedIconSymbolIndex).hidden = + (opacityState.icon.isHidden(): any); + } + } + + if (bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()) { + const collisionArrays = bucket.collisionArrays[s]; + if (collisionArrays) { + let shift = new Point(0, 0); + if (collisionArrays.textBox || collisionArrays.verticalTextBox) { + let used = true; + if (variablePlacement) { + const variableOffset = this.variableOffsets[crossTileID]; + if (variableOffset) { + // This will show either the currently placed position or the last + // successfully placed position (so you can visualize what collision + // just made the symbol disappear, and the most likely place for the + // symbol to come back) + shift = calculateVariableLayoutShift(variableOffset.anchor, + variableOffset.width, + variableOffset.height, + variableOffset.textOffset, + variableOffset.textBoxScale); + if (rotateWithMap) { + shift._rotate(pitchWithMap ? this.transform.angle : -this.transform.angle); + } + } else { + // No offset -> this symbol hasn't been placed since coming on-screen + // No single box is particularly meaningful and all of them would be too noisy + // Use the center box just to show something's there, but mark it "not used" + used = false; + } + } + + if (collisionArrays.textBox) { + updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || horizontalHidden, shift.x, shift.y); + } + if (collisionArrays.verticalTextBox) { + updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || verticalHidden, shift.x, shift.y); + } + } + + const verticalIconUsed = Boolean(!verticalHidden && collisionArrays.verticalIconBox); + + if (collisionArrays.iconBox) { + updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, verticalIconUsed, + hasIconTextFit ? shift.x : 0, + hasIconTextFit ? shift.y : 0); + } + + if (collisionArrays.verticalIconBox) { + updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, !verticalIconUsed, + hasIconTextFit ? shift.x : 0, + hasIconTextFit ? shift.y : 0); + } + } + } + } + + bucket.sortFeatures(this.transform.angle); + if (this.retainedQueryData[bucket.bucketInstanceId]) { + this.retainedQueryData[bucket.bucketInstanceId].featureSortOrder = bucket.featureSortOrder; + } + + if (bucket.hasTextData() && bucket.text.opacityVertexBuffer) { + bucket.text.opacityVertexBuffer.updateData(bucket.text.opacityVertexArray); + } + if (bucket.hasIconData() && bucket.icon.opacityVertexBuffer) { + bucket.icon.opacityVertexBuffer.updateData(bucket.icon.opacityVertexArray); + } + if (bucket.hasIconCollisionBoxData() && bucket.iconCollisionBox.collisionVertexBuffer) { + bucket.iconCollisionBox.collisionVertexBuffer.updateData(bucket.iconCollisionBox.collisionVertexArray); + } + if (bucket.hasTextCollisionBoxData() && bucket.textCollisionBox.collisionVertexBuffer) { + bucket.textCollisionBox.collisionVertexBuffer.updateData(bucket.textCollisionBox.collisionVertexArray); + } + + assert(bucket.text.opacityVertexArray.length === bucket.text.layoutVertexArray.length / 4); + assert(bucket.icon.opacityVertexArray.length === bucket.icon.layoutVertexArray.length / 4); + + // Push generated collision circles to the bucket for debug rendering + if (bucket.bucketInstanceId in this.collisionCircleArrays) { + const instance = this.collisionCircleArrays[bucket.bucketInstanceId]; + + bucket.placementInvProjMatrix = instance.invProjMatrix; + bucket.placementViewportMatrix = instance.viewportMatrix; + bucket.collisionCircleArray = instance.circles; + + delete this.collisionCircleArrays[bucket.bucketInstanceId]; + } + } + + symbolFadeChange(now: number) { + return this.fadeDuration === 0 ? + 1 : + ((now - this.commitTime) / this.fadeDuration + this.prevZoomAdjustment); + } + + zoomAdjustment(zoom: number) { + // When zooming out quickly, labels can overlap each other. This + // adjustment is used to reduce the interval between placement calculations + // and to reduce the fade duration when zooming out quickly. Discovering the + // collisions more quickly and fading them more quickly reduces the unwanted effect. + return Math.max(0, (this.transform.zoom - zoom) / 1.5); + } + + hasTransitions(now: number) { + return this.stale || + now - this.lastPlacementChangeTime < this.fadeDuration; + } + + stillRecent(now: number, zoom: number) { + // The adjustment makes placement more frequent when zooming. + // This condition applies the adjustment only after the map has + // stopped zooming. This avoids adding extra jank while zooming. + const durationAdjustment = this.zoomAtLastRecencyCheck === zoom ? + (1 - this.zoomAdjustment(zoom)) : + 1; + this.zoomAtLastRecencyCheck = zoom; + + return this.commitTime + this.fadeDuration * durationAdjustment > now; + } + + setStale() { + this.stale = true; + } +} + +function updateCollisionVertices(collisionVertexArray: CollisionVertexArray, placed: boolean, notUsed: boolean | number, shiftX?: number, shiftY?: number) { + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0); + collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0); +} + +// All four vertices for a glyph will have the same opacity state +// So we pack the opacity into a uint8, and then repeat it four times +// to make a single uint32 that we can upload for each glyph in the +// label. +const shift25 = Math.pow(2, 25); +const shift24 = Math.pow(2, 24); +const shift17 = Math.pow(2, 17); +const shift16 = Math.pow(2, 16); +const shift9 = Math.pow(2, 9); +const shift8 = Math.pow(2, 8); +const shift1 = Math.pow(2, 1); +function packOpacity(opacityState: OpacityState): number { + if (opacityState.opacity === 0 && !opacityState.placed) { + return 0; + } else if (opacityState.opacity === 1 && opacityState.placed) { + return 4294967295; + } + const targetBit = opacityState.placed ? 1 : 0; + const opacityBits = Math.floor(opacityState.opacity * 127); + return opacityBits * shift25 + targetBit * shift24 + + opacityBits * shift17 + targetBit * shift16 + + opacityBits * shift9 + targetBit * shift8 + + opacityBits * shift1 + targetBit; +} + +const PACKED_HIDDEN_OPACITY = 0; diff --git a/node_modules/mapbox-gl/src/symbol/projection.js b/node_modules/mapbox-gl/src/symbol/projection.js new file mode 100644 index 0000000000000000000000000000000000000000..e0c16142989ea56523dfde39d1cab52964ed7327 --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/projection.js @@ -0,0 +1,451 @@ +// @flow + +import Point from '@mapbox/point-geometry'; + +import {mat4, vec4} from 'gl-matrix'; +import * as symbolSize from './symbol_size'; +import {addDynamicAttributes} from '../data/bucket/symbol_bucket'; + +import type Painter from '../render/painter'; +import type Transform from '../geo/transform'; +import type SymbolBucket from '../data/bucket/symbol_bucket'; +import type { + GlyphOffsetArray, + SymbolLineVertexArray, + SymbolDynamicLayoutArray +} from '../data/array_types'; +import {WritingMode} from '../symbol/shaping'; + +export {updateLineLabels, hideGlyphs, getLabelPlaneMatrix, getGlCoordMatrix, project, getPerspectiveRatio, placeFirstAndLastGlyph, placeGlyphAlongLine, xyTransformMat4}; + +/* + * # Overview of coordinate spaces + * + * ## Tile coordinate spaces + * Each label has an anchor. Some labels have corresponding line geometries. + * The points for both anchors and lines are stored in tile units. Each tile has it's own + * coordinate space going from (0, 0) at the top left to (EXTENT, EXTENT) at the bottom right. + * + * ## GL coordinate space + * At the end of everything, the vertex shader needs to produce a position in GL coordinate space, + * which is (-1, 1) at the top left and (1, -1) in the bottom right. + * + * ## Map pixel coordinate spaces + * Each tile has a pixel coordinate space. It's just the tile units scaled so that one unit is + * whatever counts as 1 pixel at the current zoom. + * This space is used for pitch-alignment=map, rotation-alignment=map + * + * ## Rotated map pixel coordinate spaces + * Like the above, but rotated so axis of the space are aligned with the viewport instead of the tile. + * This space is used for pitch-alignment=map, rotation-alignment=viewport + * + * ## Viewport pixel coordinate space + * (0, 0) is at the top left of the canvas and (pixelWidth, pixelHeight) is at the bottom right corner + * of the canvas. This space is used for pitch-alignment=viewport + * + * + * # Vertex projection + * It goes roughly like this: + * 1. project the anchor and line from tile units into the correct label coordinate space + * - map pixel space pitch-alignment=map rotation-alignment=map + * - rotated map pixel space pitch-alignment=map rotation-alignment=viewport + * - viewport pixel space pitch-alignment=viewport rotation-alignment=* + * 2. if the label follows a line, find the point along the line that is the correct distance from the anchor. + * 3. add the glyph's corner offset to the point from step 3 + * 4. convert from the label coordinate space to gl coordinates + * + * For horizontal labels we want to do step 1 in the shader for performance reasons (no cpu work). + * This is what `u_label_plane_matrix` is used for. + * For labels aligned with lines we have to steps 1 and 2 on the cpu since we need access to the line geometry. + * This is what `updateLineLabels(...)` does. + * Since the conversion is handled on the cpu we just set `u_label_plane_matrix` to an identity matrix. + * + * Steps 3 and 4 are done in the shaders for all labels. + */ + +/* + * Returns a matrix for converting from tile units to the correct label coordinate space. + */ +function getLabelPlaneMatrix(posMatrix: mat4, + pitchWithMap: boolean, + rotateWithMap: boolean, + transform: Transform, + pixelsToTileUnits: number) { + const m = mat4.create(); + if (pitchWithMap) { + mat4.scale(m, m, [1 / pixelsToTileUnits, 1 / pixelsToTileUnits, 1]); + if (!rotateWithMap) { + mat4.rotateZ(m, m, transform.angle); + } + } else { + mat4.multiply(m, transform.labelPlaneMatrix, posMatrix); + } + return m; +} + +/* + * Returns a matrix for converting from the correct label coordinate space to gl coords. + */ +function getGlCoordMatrix(posMatrix: mat4, + pitchWithMap: boolean, + rotateWithMap: boolean, + transform: Transform, + pixelsToTileUnits: number) { + if (pitchWithMap) { + const m = mat4.clone(posMatrix); + mat4.scale(m, m, [pixelsToTileUnits, pixelsToTileUnits, 1]); + if (!rotateWithMap) { + mat4.rotateZ(m, m, -transform.angle); + } + return m; + } else { + return transform.glCoordMatrix; + } +} + +function project(point: Point, matrix: mat4) { + const pos = [point.x, point.y, 0, 1]; + xyTransformMat4(pos, pos, matrix); + const w = pos[3]; + return { + point: new Point(pos[0] / w, pos[1] / w), + signedDistanceFromCamera: w + }; +} + +function getPerspectiveRatio(cameraToCenterDistance: number, signedDistanceFromCamera: number): number { + return 0.5 + 0.5 * (cameraToCenterDistance / signedDistanceFromCamera); +} + +function isVisible(anchorPos: [number, number, number, number], + clippingBuffer: [number, number]) { + const x = anchorPos[0] / anchorPos[3]; + const y = anchorPos[1] / anchorPos[3]; + const inPaddedViewport = ( + x >= -clippingBuffer[0] && + x <= clippingBuffer[0] && + y >= -clippingBuffer[1] && + y <= clippingBuffer[1]); + return inPaddedViewport; +} + +/* + * Update the `dynamicLayoutVertexBuffer` for the buffer with the correct glyph positions for the current map view. + * This is only run on labels that are aligned with lines. Horizontal labels are handled entirely in the shader. + */ +function updateLineLabels(bucket: SymbolBucket, + posMatrix: mat4, + painter: Painter, + isText: boolean, + labelPlaneMatrix: mat4, + glCoordMatrix: mat4, + pitchWithMap: boolean, + keepUpright: boolean) { + + const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData; + const partiallyEvaluatedSize = symbolSize.evaluateSizeForZoom(sizeData, painter.transform.zoom); + + const clippingBuffer = [256 / painter.width * 2 + 1, 256 / painter.height * 2 + 1]; + + const dynamicLayoutVertexArray = isText ? + bucket.text.dynamicLayoutVertexArray : + bucket.icon.dynamicLayoutVertexArray; + dynamicLayoutVertexArray.clear(); + + const lineVertexArray = bucket.lineVertexArray; + const placedSymbols = isText ? bucket.text.placedSymbolArray : bucket.icon.placedSymbolArray; + + const aspectRatio = painter.transform.width / painter.transform.height; + + let useVertical = false; + + for (let s = 0; s < placedSymbols.length; s++) { + const symbol: any = placedSymbols.get(s); + + // Don't do calculations for vertical glyphs unless the previous symbol was horizontal + // and we determined that vertical glyphs were necessary. + // Also don't do calculations for symbols that are collided and fully faded out + if (symbol.hidden || symbol.writingMode === WritingMode.vertical && !useVertical) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + continue; + } + // Awkward... but we're counting on the paired "vertical" symbol coming immediately after its horizontal counterpart + useVertical = false; + + const anchorPos = [symbol.anchorX, symbol.anchorY, 0, 1]; + vec4.transformMat4(anchorPos, anchorPos, posMatrix); + + // Don't bother calculating the correct point for invisible labels. + if (!isVisible(anchorPos, clippingBuffer)) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + continue; + } + + const cameraToAnchorDistance = anchorPos[3]; + const perspectiveRatio = getPerspectiveRatio(painter.transform.cameraToCenterDistance, cameraToAnchorDistance); + + const fontSize = symbolSize.evaluateSizeForFeature(sizeData, partiallyEvaluatedSize, symbol); + const pitchScaledFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio; + + const tileAnchorPoint = new Point(symbol.anchorX, symbol.anchorY); + const anchorPoint = project(tileAnchorPoint, labelPlaneMatrix).point; + const projectionCache = {}; + + const placeUnflipped: any = placeGlyphsAlongLine(symbol, pitchScaledFontSize, false /*unflipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, + bucket.glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio); + + useVertical = placeUnflipped.useVertical; + + if (placeUnflipped.notEnoughRoom || useVertical || + (placeUnflipped.needsFlipping && + placeGlyphsAlongLine(symbol, pitchScaledFontSize, true /*flipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, + bucket.glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio).notEnoughRoom)) { + hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray); + } + } + + if (isText) { + bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray); + } else { + bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray); + } +} + +function placeFirstAndLastGlyph(fontScale: number, glyphOffsetArray: GlyphOffsetArray, lineOffsetX: number, lineOffsetY: number, flip: boolean, anchorPoint: Point, tileAnchorPoint: Point, symbol: any, lineVertexArray: SymbolLineVertexArray, labelPlaneMatrix: mat4, projectionCache: any) { + const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs; + const lineStartIndex = symbol.lineStartIndex; + const lineEndIndex = symbol.lineStartIndex + symbol.lineLength; + + const firstGlyphOffset = glyphOffsetArray.getoffsetX(symbol.glyphStartIndex); + const lastGlyphOffset = glyphOffsetArray.getoffsetX(glyphEndIndex - 1); + + const firstPlacedGlyph = placeGlyphAlongLine(fontScale * firstGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment, + lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache); + if (!firstPlacedGlyph) + return null; + + const lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment, + lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache); + if (!lastPlacedGlyph) + return null; + + return {first: firstPlacedGlyph, last: lastPlacedGlyph}; +} + +function requiresOrientationChange(writingMode, firstPoint, lastPoint, aspectRatio) { + if (writingMode === WritingMode.horizontal) { + // On top of choosing whether to flip, choose whether to render this version of the glyphs or the alternate + // vertical glyphs. We can't just filter out vertical glyphs in the horizontal range because the horizontal + // and vertical versions can have slightly different projections which could lead to angles where both or + // neither showed. + const rise = Math.abs(lastPoint.y - firstPoint.y); + const run = Math.abs(lastPoint.x - firstPoint.x) * aspectRatio; + if (rise > run) { + return {useVertical: true}; + } + } + + if (writingMode === WritingMode.vertical ? firstPoint.y < lastPoint.y : firstPoint.x > lastPoint.x) { + // Includes "horizontalOnly" case for labels without vertical glyphs + return {needsFlipping: true}; + } + + return null; +} + +function placeGlyphsAlongLine(symbol, fontSize, flip, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio) { + const fontScale = fontSize / 24; + const lineOffsetX = symbol.lineOffsetX * fontScale; + const lineOffsetY = symbol.lineOffsetY * fontScale; + + let placedGlyphs; + if (symbol.numGlyphs > 1) { + const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs; + const lineStartIndex = symbol.lineStartIndex; + const lineEndIndex = symbol.lineStartIndex + symbol.lineLength; + + // Place the first and the last glyph in the label first, so we can figure out + // the overall orientation of the label and determine whether it needs to be flipped in keepUpright mode + const firstAndLastGlyph = placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol, lineVertexArray, labelPlaneMatrix, projectionCache); + if (!firstAndLastGlyph) { + return {notEnoughRoom: true}; + } + const firstPoint = project(firstAndLastGlyph.first.point, glCoordMatrix).point; + const lastPoint = project(firstAndLastGlyph.last.point, glCoordMatrix).point; + + if (keepUpright && !flip) { + const orientationChange = requiresOrientationChange(symbol.writingMode, firstPoint, lastPoint, aspectRatio); + if (orientationChange) { + return orientationChange; + } + } + + placedGlyphs = [firstAndLastGlyph.first]; + for (let glyphIndex = symbol.glyphStartIndex + 1; glyphIndex < glyphEndIndex - 1; glyphIndex++) { + // Since first and last glyph fit on the line, we're sure that the rest of the glyphs can be placed + // $FlowFixMe + placedGlyphs.push(placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(glyphIndex), lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment, + lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache)); + } + placedGlyphs.push(firstAndLastGlyph.last); + } else { + // Only a single glyph to place + // So, determine whether to flip based on projected angle of the line segment it's on + if (keepUpright && !flip) { + const a = project(tileAnchorPoint, posMatrix).point; + const tileVertexIndex = (symbol.lineStartIndex + symbol.segment + 1); + // $FlowFixMe + const tileSegmentEnd = new Point(lineVertexArray.getx(tileVertexIndex), lineVertexArray.gety(tileVertexIndex)); + const projectedVertex = project(tileSegmentEnd, posMatrix); + // We know the anchor will be in the viewport, but the end of the line segment may be + // behind the plane of the camera, in which case we can use a point at any arbitrary (closer) + // point on the segment. + const b = (projectedVertex.signedDistanceFromCamera > 0) ? + projectedVertex.point : + projectTruncatedLineSegment(tileAnchorPoint, tileSegmentEnd, a, 1, posMatrix); + + const orientationChange = requiresOrientationChange(symbol.writingMode, a, b, aspectRatio); + if (orientationChange) { + return orientationChange; + } + } + // $FlowFixMe + const singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(symbol.glyphStartIndex), lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment, + symbol.lineStartIndex, symbol.lineStartIndex + symbol.lineLength, lineVertexArray, labelPlaneMatrix, projectionCache); + if (!singleGlyph) + return {notEnoughRoom: true}; + + placedGlyphs = [singleGlyph]; + } + + for (const glyph: any of placedGlyphs) { + addDynamicAttributes(dynamicLayoutVertexArray, glyph.point, glyph.angle); + } + return {}; +} + +function projectTruncatedLineSegment(previousTilePoint: Point, currentTilePoint: Point, previousProjectedPoint: Point, minimumLength: number, projectionMatrix: mat4) { + // We are assuming "previousTilePoint" won't project to a point within one unit of the camera plane + // If it did, that would mean our label extended all the way out from within the viewport to a (very distant) + // point near the plane of the camera. We wouldn't be able to render the label anyway once it crossed the + // plane of the camera. + const projectedUnitVertex = project(previousTilePoint.add(previousTilePoint.sub(currentTilePoint)._unit()), projectionMatrix).point; + const projectedUnitSegment = previousProjectedPoint.sub(projectedUnitVertex); + + return previousProjectedPoint.add(projectedUnitSegment._mult(minimumLength / projectedUnitSegment.mag())); +} + +function placeGlyphAlongLine(offsetX: number, + lineOffsetX: number, + lineOffsetY: number, + flip: boolean, + anchorPoint: Point, + tileAnchorPoint: Point, + anchorSegment: number, + lineStartIndex: number, + lineEndIndex: number, + lineVertexArray: SymbolLineVertexArray, + labelPlaneMatrix: mat4, + projectionCache: {[_: number]: Point}) { + + const combinedOffsetX = flip ? + offsetX - lineOffsetX : + offsetX + lineOffsetX; + + let dir = combinedOffsetX > 0 ? 1 : -1; + + let angle = 0; + if (flip) { + // The label needs to be flipped to keep text upright. + // Iterate in the reverse direction. + dir *= -1; + angle = Math.PI; + } + + if (dir < 0) angle += Math.PI; + + let currentIndex = dir > 0 ? + lineStartIndex + anchorSegment : + lineStartIndex + anchorSegment + 1; + + let current = anchorPoint; + let prev = anchorPoint; + let distanceToPrev = 0; + let currentSegmentDistance = 0; + const absOffsetX = Math.abs(combinedOffsetX); + const pathVertices = []; + + while (distanceToPrev + currentSegmentDistance <= absOffsetX) { + currentIndex += dir; + + // offset does not fit on the projected line + if (currentIndex < lineStartIndex || currentIndex >= lineEndIndex) + return null; + + prev = current; + pathVertices.push(current); + + current = projectionCache[currentIndex]; + if (current === undefined) { + const currentVertex = new Point(lineVertexArray.getx(currentIndex), lineVertexArray.gety(currentIndex)); + const projection = project(currentVertex, labelPlaneMatrix); + if (projection.signedDistanceFromCamera > 0) { + current = projectionCache[currentIndex] = projection.point; + } else { + // The vertex is behind the plane of the camera, so we can't project it + // Instead, we'll create a vertex along the line that's far enough to include the glyph + const previousLineVertexIndex = currentIndex - dir; + const previousTilePoint = distanceToPrev === 0 ? + tileAnchorPoint : + new Point(lineVertexArray.getx(previousLineVertexIndex), lineVertexArray.gety(previousLineVertexIndex)); + // Don't cache because the new vertex might not be far enough out for future glyphs on the same segment + current = projectTruncatedLineSegment(previousTilePoint, currentVertex, prev, absOffsetX - distanceToPrev + 1, labelPlaneMatrix); + } + } + + distanceToPrev += currentSegmentDistance; + currentSegmentDistance = prev.dist(current); + } + + // The point is on the current segment. Interpolate to find it. + const segmentInterpolationT = (absOffsetX - distanceToPrev) / currentSegmentDistance; + const prevToCurrent = current.sub(prev); + const p = prevToCurrent.mult(segmentInterpolationT)._add(prev); + + // offset the point from the line to text-offset and icon-offset + p._add(prevToCurrent._unit()._perp()._mult(lineOffsetY * dir)); + + const segmentAngle = angle + Math.atan2(current.y - prev.y, current.x - prev.x); + + pathVertices.push(p); + + return { + point: p, + angle: segmentAngle, + path: pathVertices + }; +} + +const hiddenGlyphAttributes = new Float32Array([-Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0]); + +// Hide them by moving them offscreen. We still need to add them to the buffer +// because the dynamic buffer is paired with a static buffer that doesn't get updated. +function hideGlyphs(num: number, dynamicLayoutVertexArray: SymbolDynamicLayoutArray) { + for (let i = 0; i < num; i++) { + const offset = dynamicLayoutVertexArray.length; + dynamicLayoutVertexArray.resize(offset + 4); + // Since all hidden glyphs have the same attributes, we can build up the array faster with a single call to Float32Array.set + // for each set of four vertices, instead of calling addDynamicAttributes for each vertex. + dynamicLayoutVertexArray.float32.set(hiddenGlyphAttributes, offset * 3); + } +} + +// For line label layout, we're not using z output and our w input is always 1 +// This custom matrix transformation ignores those components to make projection faster +function xyTransformMat4(out: vec4, a: vec4, m: mat4) { + const x = a[0], y = a[1]; + out[0] = m[0] * x + m[4] * y + m[12]; + out[1] = m[1] * x + m[5] * y + m[13]; + out[3] = m[3] * x + m[7] * y + m[15]; + return out; +} diff --git a/node_modules/mapbox-gl/src/symbol/quads.js b/node_modules/mapbox-gl/src/symbol/quads.js new file mode 100644 index 0000000000000000000000000000000000000000..9b1c100620e71b92fc7c804ad975874600766262 --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/quads.js @@ -0,0 +1,334 @@ +// @flow + +import Point from '@mapbox/point-geometry'; + +import {GLYPH_PBF_BORDER} from '../style/parse_glyph_pbf'; + +import type Anchor from './anchor'; +import type {PositionedIcon, Shaping} from './shaping'; +import {SHAPING_DEFAULT_OFFSET} from './shaping'; +import {IMAGE_PADDING} from '../render/image_atlas'; +import type SymbolStyleLayer from '../style/style_layer/symbol_style_layer'; +import type {Feature} from '../style-spec/expression'; +import type {StyleImage} from '../style/style_image'; +import ONE_EM from './one_em'; + +/** + * A textured quad for rendering a single icon or glyph. + * + * The zoom range the glyph can be shown is defined by minScale and maxScale. + * + * @param tl The offset of the top left corner from the anchor. + * @param tr The offset of the top right corner from the anchor. + * @param bl The offset of the bottom left corner from the anchor. + * @param br The offset of the bottom right corner from the anchor. + * @param tex The texture coordinates. + * + * @private + */ +export type SymbolQuad = { + tl: Point, + tr: Point, + bl: Point, + br: Point, + tex: { + x: number, + y: number, + w: number, + h: number + }, + pixelOffsetTL: Point, + pixelOffsetBR: Point, + writingMode: any | void, + glyphOffset: [number, number], + sectionIndex: number, + isSDF: boolean, + minFontScaleX: number, + minFontScaleY: number +}; + +// If you have a 10px icon that isn't perfectly aligned to the pixel grid it will cover 11 actual +// pixels. The quad needs to be padded to account for this, otherwise they'll look slightly clipped +// on one edge in some cases. +const border = IMAGE_PADDING; + +/** + * Create the quads used for rendering an icon. + * @private + */ +export function getIconQuads( + shapedIcon: PositionedIcon, + iconRotate: number, + isSDFIcon: boolean, + hasIconTextFit: boolean): Array { + const quads = []; + + const image = shapedIcon.image; + const pixelRatio = image.pixelRatio; + const imageWidth = image.paddedRect.w - 2 * border; + const imageHeight = image.paddedRect.h - 2 * border; + + const iconWidth = shapedIcon.right - shapedIcon.left; + const iconHeight = shapedIcon.bottom - shapedIcon.top; + + const stretchX = image.stretchX || [[0, imageWidth]]; + const stretchY = image.stretchY || [[0, imageHeight]]; + + const reduceRanges = (sum, range) => sum + range[1] - range[0]; + const stretchWidth = stretchX.reduce(reduceRanges, 0); + const stretchHeight = stretchY.reduce(reduceRanges, 0); + const fixedWidth = imageWidth - stretchWidth; + const fixedHeight = imageHeight - stretchHeight; + + let stretchOffsetX = 0; + let stretchContentWidth = stretchWidth; + let stretchOffsetY = 0; + let stretchContentHeight = stretchHeight; + let fixedOffsetX = 0; + let fixedContentWidth = fixedWidth; + let fixedOffsetY = 0; + let fixedContentHeight = fixedHeight; + + if (image.content && hasIconTextFit) { + const content = image.content; + stretchOffsetX = sumWithinRange(stretchX, 0, content[0]); + stretchOffsetY = sumWithinRange(stretchY, 0, content[1]); + stretchContentWidth = sumWithinRange(stretchX, content[0], content[2]); + stretchContentHeight = sumWithinRange(stretchY, content[1], content[3]); + fixedOffsetX = content[0] - stretchOffsetX; + fixedOffsetY = content[1] - stretchOffsetY; + fixedContentWidth = content[2] - content[0] - stretchContentWidth; + fixedContentHeight = content[3] - content[1] - stretchContentHeight; + } + + const makeBox = (left, top, right, bottom) => { + + const leftEm = getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left); + const leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth); + + const topEm = getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top); + const topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight); + + const rightEm = getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left); + const rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth); + + const bottomEm = getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top); + const bottomPx = getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight); + + const tl = new Point(leftEm, topEm); + const tr = new Point(rightEm, topEm); + const br = new Point(rightEm, bottomEm); + const bl = new Point(leftEm, bottomEm); + const pixelOffsetTL = new Point(leftPx / pixelRatio, topPx / pixelRatio); + const pixelOffsetBR = new Point(rightPx / pixelRatio, bottomPx / pixelRatio); + + const angle = iconRotate * Math.PI / 180; + + if (angle) { + const sin = Math.sin(angle), + cos = Math.cos(angle), + matrix = [cos, -sin, sin, cos]; + + tl._matMult(matrix); + tr._matMult(matrix); + bl._matMult(matrix); + br._matMult(matrix); + } + + const x1 = left.stretch + left.fixed; + const x2 = right.stretch + right.fixed; + const y1 = top.stretch + top.fixed; + const y2 = bottom.stretch + bottom.fixed; + + const subRect = { + x: image.paddedRect.x + border + x1, + y: image.paddedRect.y + border + y1, + w: x2 - x1, + h: y2 - y1 + }; + + const minFontScaleX = fixedContentWidth / pixelRatio / iconWidth; + const minFontScaleY = fixedContentHeight / pixelRatio / iconHeight; + + // Icon quad is padded, so texture coordinates also need to be padded. + return {tl, tr, bl, br, tex: subRect, writingMode: undefined, glyphOffset: [0, 0], sectionIndex: 0, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, isSDF: isSDFIcon}; + }; + + if (!hasIconTextFit || (!image.stretchX && !image.stretchY)) { + quads.push(makeBox( + {fixed: 0, stretch: -1}, + {fixed: 0, stretch: -1}, + {fixed: 0, stretch: imageWidth + 1}, + {fixed: 0, stretch: imageHeight + 1})); + } else { + const xCuts = stretchZonesToCuts(stretchX, fixedWidth, stretchWidth); + const yCuts = stretchZonesToCuts(stretchY, fixedHeight, stretchHeight); + + for (let xi = 0; xi < xCuts.length - 1; xi++) { + const x1 = xCuts[xi]; + const x2 = xCuts[xi + 1]; + for (let yi = 0; yi < yCuts.length - 1; yi++) { + const y1 = yCuts[yi]; + const y2 = yCuts[yi + 1]; + quads.push(makeBox(x1, y1, x2, y2)); + } + } + } + + return quads; +} + +function sumWithinRange(ranges, min, max) { + let sum = 0; + for (const range of ranges) { + sum += Math.max(min, Math.min(max, range[1])) - Math.max(min, Math.min(max, range[0])); + } + return sum; +} + +function stretchZonesToCuts(stretchZones, fixedSize, stretchSize) { + const cuts = [{fixed: -border, stretch: 0}]; + + for (const [c1, c2] of stretchZones) { + const last = cuts[cuts.length - 1]; + cuts.push({ + fixed: c1 - last.stretch, + stretch: last.stretch + }); + cuts.push({ + fixed: c1 - last.stretch, + stretch: last.stretch + (c2 - c1) + }); + } + cuts.push({ + fixed: fixedSize + border, + stretch: stretchSize + }); + return cuts; +} + +function getEmOffset(stretchOffset, stretchSize, iconSize, iconOffset) { + return stretchOffset / stretchSize * iconSize + iconOffset; +} + +function getPxOffset(fixedOffset, fixedSize, stretchOffset, stretchSize) { + return fixedOffset - fixedSize * stretchOffset / stretchSize; +} + +/** + * Create the quads used for rendering a text label. + * @private + */ +export function getGlyphQuads(anchor: Anchor, + shaping: Shaping, + textOffset: [number, number], + layer: SymbolStyleLayer, + alongLine: boolean, + feature: Feature, + imageMap: {[_: string]: StyleImage}, + allowVerticalPlacement: boolean): Array { + + const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}) * Math.PI / 180; + const quads = []; + + for (const line of shaping.positionedLines) { + for (const positionedGlyph of line.positionedGlyphs) { + if (!positionedGlyph.rect) continue; + const textureRect = positionedGlyph.rect || {}; + + // The rects have an additional buffer that is not included in their size. + const glyphPadding = 1.0; + let rectBuffer = GLYPH_PBF_BORDER + glyphPadding; + let isSDF = true; + let pixelRatio = 1.0; + let lineOffset = 0.0; + + const rotateVerticalGlyph = (alongLine || allowVerticalPlacement) && positionedGlyph.vertical; + const halfAdvance = positionedGlyph.metrics.advance * positionedGlyph.scale / 2; + + // Align images and scaled glyphs in the middle of a vertical line. + if (allowVerticalPlacement && shaping.verticalizable) { + const scaledGlyphOffset = (positionedGlyph.scale - 1) * ONE_EM; + const imageOffset = (ONE_EM - positionedGlyph.metrics.width * positionedGlyph.scale) / 2; + lineOffset = line.lineOffset / 2 - (positionedGlyph.imageName ? -imageOffset : scaledGlyphOffset); + } + + if (positionedGlyph.imageName) { + const image = imageMap[positionedGlyph.imageName]; + isSDF = image.sdf; + pixelRatio = image.pixelRatio; + rectBuffer = IMAGE_PADDING / pixelRatio; + } + + const glyphOffset = alongLine ? + [positionedGlyph.x + halfAdvance, positionedGlyph.y] : + [0, 0]; + + let builtInOffset = alongLine ? + [0, 0] : + [positionedGlyph.x + halfAdvance + textOffset[0], positionedGlyph.y + textOffset[1] - lineOffset]; + + let verticalizedLabelOffset = [0, 0]; + if (rotateVerticalGlyph) { + // Vertical POI labels that are rotated 90deg CW and whose glyphs must preserve upright orientation + // need to be rotated 90deg CCW. After a quad is rotated, it is translated to the original built-in offset. + verticalizedLabelOffset = builtInOffset; + builtInOffset = [0, 0]; + } + + const x1 = (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset[0]; + const y1 = (-positionedGlyph.metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset[1]; + const x2 = x1 + textureRect.w * positionedGlyph.scale / pixelRatio; + const y2 = y1 + textureRect.h * positionedGlyph.scale / pixelRatio; + + const tl = new Point(x1, y1); + const tr = new Point(x2, y1); + const bl = new Point(x1, y2); + const br = new Point(x2, y2); + + if (rotateVerticalGlyph) { + // Vertical-supporting glyphs are laid out in 24x24 point boxes (1 square em) + // In horizontal orientation, the y values for glyphs are below the midline + // and we use a "yOffset" of -17 to pull them up to the middle. + // By rotating counter-clockwise around the point at the center of the left + // edge of a 24x24 layout box centered below the midline, we align the center + // of the glyphs with the horizontal midline, so the yOffset is no longer + // necessary, but we also pull the glyph to the left along the x axis. + // The y coordinate includes baseline yOffset, thus needs to be accounted + // for when glyph is rotated and translated. + const center = new Point(-halfAdvance, halfAdvance - SHAPING_DEFAULT_OFFSET); + const verticalRotation = -Math.PI / 2; + + // xHalfWidthOffsetCorrection is a difference between full-width and half-width + // advance, should be 0 for full-width glyphs and will pull up half-width glyphs. + const xHalfWidthOffsetCorrection = ONE_EM / 2 - halfAdvance; + const yImageOffsetCorrection = positionedGlyph.imageName ? xHalfWidthOffsetCorrection : 0.0; + const halfWidthOffsetCorrection = new Point(5 - SHAPING_DEFAULT_OFFSET - xHalfWidthOffsetCorrection, -yImageOffsetCorrection); + const verticalOffsetCorrection = new Point(...verticalizedLabelOffset); + tl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + tr._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + bl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + br._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); + } + + if (textRotate) { + const sin = Math.sin(textRotate), + cos = Math.cos(textRotate), + matrix = [cos, -sin, sin, cos]; + + tl._matMult(matrix); + tr._matMult(matrix); + bl._matMult(matrix); + br._matMult(matrix); + } + + const pixelOffsetTL = new Point(0, 0); + const pixelOffsetBR = new Point(0, 0); + const minFontScaleX = 0; + const minFontScaleY = 0; + quads.push({tl, tr, bl, br, tex: textureRect, writingMode: shaping.writingMode, glyphOffset, sectionIndex: positionedGlyph.sectionIndex, isSDF, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY}); + } + } + + return quads; +} diff --git a/node_modules/mapbox-gl/src/symbol/shaping.js b/node_modules/mapbox-gl/src/symbol/shaping.js new file mode 100644 index 0000000000000000000000000000000000000000..dafdd6ecfacfe10793765a6fe0ec00b74e747aec --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/shaping.js @@ -0,0 +1,816 @@ +// @flow + +import assert from 'assert'; +import { + charHasUprightVerticalOrientation, + charAllowsIdeographicBreaking, + charInComplexShapingScript +} from '../util/script_detection'; +import verticalizePunctuation from '../util/verticalize_punctuation'; +import {plugin as rtlTextPlugin} from '../source/rtl_text_plugin'; +import ONE_EM from './one_em'; +import {warnOnce} from '../util/util'; + +import type {StyleGlyph, GlyphMetrics} from '../style/style_glyph'; +import {GLYPH_PBF_BORDER} from '../style/parse_glyph_pbf'; +import type {ImagePosition} from '../render/image_atlas'; +import {IMAGE_PADDING} from '../render/image_atlas'; +import type {Rect, GlyphPosition} from '../render/glyph_atlas'; +import Formatted, {FormattedSection} from '../style-spec/expression/types/formatted'; + +const WritingMode = { + horizontal: 1, + vertical: 2, + horizontalOnly: 3 +}; + +const SHAPING_DEFAULT_OFFSET = -17; +export {shapeText, shapeIcon, fitIconToText, getAnchorAlignment, WritingMode, SHAPING_DEFAULT_OFFSET}; + +// The position of a glyph relative to the text's anchor point. +export type PositionedGlyph = { + glyph: number, + imageName: string | null, + x: number, + y: number, + vertical: boolean, + scale: number, + fontStack: string, + sectionIndex: number, + metrics: GlyphMetrics, + rect: Rect | null +}; + +export type PositionedLine = { + positionedGlyphs: Array, + lineOffset: number +}; + +// A collection of positioned glyphs and some metadata +export type Shaping = { + positionedLines: Array, + top: number, + bottom: number, + left: number, + right: number, + writingMode: 1 | 2, + text: string, + iconsInText: boolean, + verticalizable: boolean +}; + +function isEmpty(positionedLines: Array) { + for (const line of positionedLines) { + if (line.positionedGlyphs.length !== 0) { + return false; + } + } + return true; +} + +export type SymbolAnchor = 'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; +export type TextJustify = 'left' | 'center' | 'right'; + +// Max number of images in label is 6401 U+E000–U+F8FF that covers +// Basic Multilingual Plane Unicode Private Use Area (PUA). +const PUAbegin = 0xE000; +const PUAend = 0xF8FF; + +class SectionOptions { + // Text options + scale: number; + fontStack: string; + // Image options + imageName: string | null; + + constructor() { + this.scale = 1.0; + this.fontStack = ""; + this.imageName = null; + } + + static forText(scale: number | null, fontStack: string) { + const textOptions = new SectionOptions(); + textOptions.scale = scale || 1; + textOptions.fontStack = fontStack; + return textOptions; + } + + static forImage(imageName: string) { + const imageOptions = new SectionOptions(); + imageOptions.imageName = imageName; + return imageOptions; + } + +} + +class TaggedString { + text: string; + sectionIndex: Array // maps each character in 'text' to its corresponding entry in 'sections' + sections: Array + imageSectionID: number | null; + + constructor() { + this.text = ""; + this.sectionIndex = []; + this.sections = []; + this.imageSectionID = null; + } + + static fromFeature(text: Formatted, defaultFontStack: string) { + const result = new TaggedString(); + for (let i = 0; i < text.sections.length; i++) { + const section = text.sections[i]; + if (!section.image) { + result.addTextSection(section, defaultFontStack); + } else { + result.addImageSection(section); + } + } + return result; + } + + length(): number { + return this.text.length; + } + + getSection(index: number): SectionOptions { + return this.sections[this.sectionIndex[index]]; + } + + getSectionIndex(index: number): number { + return this.sectionIndex[index]; + } + + getCharCode(index: number): number { + return this.text.charCodeAt(index); + } + + verticalizePunctuation() { + this.text = verticalizePunctuation(this.text); + } + + trim() { + let beginningWhitespace = 0; + for (let i = 0; + i < this.text.length && whitespace[this.text.charCodeAt(i)]; + i++) { + beginningWhitespace++; + } + let trailingWhitespace = this.text.length; + for (let i = this.text.length - 1; + i >= 0 && i >= beginningWhitespace && whitespace[this.text.charCodeAt(i)]; + i--) { + trailingWhitespace--; + } + this.text = this.text.substring(beginningWhitespace, trailingWhitespace); + this.sectionIndex = this.sectionIndex.slice(beginningWhitespace, trailingWhitespace); + } + + substring(start: number, end: number): TaggedString { + const substring = new TaggedString(); + substring.text = this.text.substring(start, end); + substring.sectionIndex = this.sectionIndex.slice(start, end); + substring.sections = this.sections; + return substring; + } + + toString(): string { + return this.text; + } + + getMaxScale() { + return this.sectionIndex.reduce((max, index) => Math.max(max, this.sections[index].scale), 0); + } + + addTextSection(section: FormattedSection, defaultFontStack: string) { + this.text += section.text; + this.sections.push(SectionOptions.forText(section.scale, section.fontStack || defaultFontStack)); + const index = this.sections.length - 1; + for (let i = 0; i < section.text.length; ++i) { + this.sectionIndex.push(index); + } + } + + addImageSection(section: FormattedSection) { + const imageName = section.image ? section.image.name : ''; + if (imageName.length === 0) { + warnOnce(`Can't add FormattedSection with an empty image.`); + return; + } + + const nextImageSectionCharCode = this.getNextImageSectionCharCode(); + if (!nextImageSectionCharCode) { + warnOnce(`Reached maximum number of images ${PUAend - PUAbegin + 2}`); + return; + } + + this.text += String.fromCharCode(nextImageSectionCharCode); + this.sections.push(SectionOptions.forImage(imageName)); + this.sectionIndex.push(this.sections.length - 1); + } + + getNextImageSectionCharCode(): number | null { + if (!this.imageSectionID) { + this.imageSectionID = PUAbegin; + return this.imageSectionID; + } + + if (this.imageSectionID >= PUAend) return null; + return ++this.imageSectionID; + } +} + +function breakLines(input: TaggedString, lineBreakPoints: Array): Array { + const lines = []; + const text = input.text; + let start = 0; + for (const lineBreak of lineBreakPoints) { + lines.push(input.substring(start, lineBreak)); + start = lineBreak; + } + + if (start < text.length) { + lines.push(input.substring(start, text.length)); + } + return lines; +} + +function shapeText(text: Formatted, + glyphMap: {[_: string]: {[_: number]: ?StyleGlyph}}, + glyphPositions: {[_: string]: {[_: number]: GlyphPosition}}, + imagePositions: {[_: string]: ImagePosition}, + defaultFontStack: string, + maxWidth: number, + lineHeight: number, + textAnchor: SymbolAnchor, + textJustify: TextJustify, + spacing: number, + translate: [number, number], + writingMode: 1 | 2, + allowVerticalPlacement: boolean, + symbolPlacement: string, + layoutTextSize: number, + layoutTextSizeThisZoom: number): Shaping | false { + const logicalInput = TaggedString.fromFeature(text, defaultFontStack); + + if (writingMode === WritingMode.vertical) { + logicalInput.verticalizePunctuation(); + } + + let lines: Array; + + const {processBidirectionalText, processStyledBidirectionalText} = rtlTextPlugin; + if (processBidirectionalText && logicalInput.sections.length === 1) { + // Bidi doesn't have to be style-aware + lines = []; + const untaggedLines = + processBidirectionalText(logicalInput.toString(), + determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, symbolPlacement, layoutTextSize)); + for (const line of untaggedLines) { + const taggedLine = new TaggedString(); + taggedLine.text = line; + taggedLine.sections = logicalInput.sections; + for (let i = 0; i < line.length; i++) { + taggedLine.sectionIndex.push(0); + } + lines.push(taggedLine); + } + } else if (processStyledBidirectionalText) { + // Need version of mapbox-gl-rtl-text with style support for combining RTL text + // with formatting + lines = []; + const processedLines = + processStyledBidirectionalText(logicalInput.text, + logicalInput.sectionIndex, + determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, symbolPlacement, layoutTextSize)); + for (const line of processedLines) { + const taggedLine = new TaggedString(); + taggedLine.text = line[0]; + taggedLine.sectionIndex = line[1]; + taggedLine.sections = logicalInput.sections; + lines.push(taggedLine); + } + } else { + lines = breakLines(logicalInput, determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, symbolPlacement, layoutTextSize)); + } + + const positionedLines = []; + const shaping = { + positionedLines, + text: logicalInput.toString(), + top: translate[1], + bottom: translate[1], + left: translate[0], + right: translate[0], + writingMode, + iconsInText: false, + verticalizable: false + }; + + shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom); + if (isEmpty(positionedLines)) return false; + + return shaping; +} + +// using computed properties due to https://github.com/facebook/flow/issues/380 +/* eslint no-useless-computed-key: 0 */ + +const whitespace: {[_: number]: boolean} = { + [0x09]: true, // tab + [0x0a]: true, // newline + [0x0b]: true, // vertical tab + [0x0c]: true, // form feed + [0x0d]: true, // carriage return + [0x20]: true, // space +}; + +const breakable: {[_: number]: boolean} = { + [0x0a]: true, // newline + [0x20]: true, // space + [0x26]: true, // ampersand + [0x28]: true, // left parenthesis + [0x29]: true, // right parenthesis + [0x2b]: true, // plus sign + [0x2d]: true, // hyphen-minus + [0x2f]: true, // solidus + [0xad]: true, // soft hyphen + [0xb7]: true, // middle dot + [0x200b]: true, // zero-width space + [0x2010]: true, // hyphen + [0x2013]: true, // en dash + [0x2027]: true // interpunct + // Many other characters may be reasonable breakpoints + // Consider "neutral orientation" characters at scriptDetection.charHasNeutralVerticalOrientation + // See https://github.com/mapbox/mapbox-gl-js/issues/3658 +}; + +function getGlyphAdvance(codePoint: number, + section: SectionOptions, + glyphMap: {[_: string]: {[_: number]: ?StyleGlyph}}, + imagePositions: {[_: string]: ImagePosition}, + spacing: number, + layoutTextSize: number): number { + if (!section.imageName) { + const positions = glyphMap[section.fontStack]; + const glyph = positions && positions[codePoint]; + if (!glyph) return 0; + return glyph.metrics.advance * section.scale + spacing; + } else { + const imagePosition = imagePositions[section.imageName]; + if (!imagePosition) return 0; + return imagePosition.displaySize[0] * section.scale * ONE_EM / layoutTextSize + spacing; + } +} + +function determineAverageLineWidth(logicalInput: TaggedString, + spacing: number, + maxWidth: number, + glyphMap: {[_: string]: {[_: number]: ?StyleGlyph}}, + imagePositions: {[_: string]: ImagePosition}, + layoutTextSize: number) { + let totalWidth = 0; + + for (let index = 0; index < logicalInput.length(); index++) { + const section = logicalInput.getSection(index); + totalWidth += getGlyphAdvance(logicalInput.getCharCode(index), section, glyphMap, imagePositions, spacing, layoutTextSize); + } + + const lineCount = Math.max(1, Math.ceil(totalWidth / maxWidth)); + return totalWidth / lineCount; +} + +function calculateBadness(lineWidth: number, + targetWidth: number, + penalty: number, + isLastBreak: boolean) { + const raggedness = Math.pow(lineWidth - targetWidth, 2); + if (isLastBreak) { + // Favor finals lines shorter than average over longer than average + if (lineWidth < targetWidth) { + return raggedness / 2; + } else { + return raggedness * 2; + } + } + + return raggedness + Math.abs(penalty) * penalty; +} + +function calculatePenalty(codePoint: number, nextCodePoint: number, penalizableIdeographicBreak: boolean) { + let penalty = 0; + // Force break on newline + if (codePoint === 0x0a) { + penalty -= 10000; + } + // Penalize breaks between characters that allow ideographic breaking because + // they are less preferable than breaks at spaces (or zero width spaces). + if (penalizableIdeographicBreak) { + penalty += 150; + } + + // Penalize open parenthesis at end of line + if (codePoint === 0x28 || codePoint === 0xff08) { + penalty += 50; + } + + // Penalize close parenthesis at beginning of line + if (nextCodePoint === 0x29 || nextCodePoint === 0xff09) { + penalty += 50; + } + return penalty; +} + +type Break = { + index: number, + x: number, + priorBreak: ?Break, + badness: number +}; + +function evaluateBreak(breakIndex: number, + breakX: number, + targetWidth: number, + potentialBreaks: Array, + penalty: number, + isLastBreak: boolean): Break { + // We could skip evaluating breaks where the line length (breakX - priorBreak.x) > maxWidth + // ...but in fact we allow lines longer than maxWidth (if there's no break points) + // ...and when targetWidth and maxWidth are close, strictly enforcing maxWidth can give + // more lopsided results. + + let bestPriorBreak: ?Break = null; + let bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak); + + for (const potentialBreak of potentialBreaks) { + const lineWidth = breakX - potentialBreak.x; + const breakBadness = + calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness; + if (breakBadness <= bestBreakBadness) { + bestPriorBreak = potentialBreak; + bestBreakBadness = breakBadness; + } + } + + return { + index: breakIndex, + x: breakX, + priorBreak: bestPriorBreak, + badness: bestBreakBadness + }; +} + +function leastBadBreaks(lastLineBreak: ?Break): Array { + if (!lastLineBreak) { + return []; + } + return leastBadBreaks(lastLineBreak.priorBreak).concat(lastLineBreak.index); +} + +function determineLineBreaks(logicalInput: TaggedString, + spacing: number, + maxWidth: number, + glyphMap: {[_: string]: {[_: number]: ?StyleGlyph}}, + imagePositions: {[_: string]: ImagePosition}, + symbolPlacement: string, + layoutTextSize: number): Array { + if (symbolPlacement !== 'point') + return []; + + if (!logicalInput) + return []; + + const potentialLineBreaks = []; + const targetWidth = determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize); + + const hasServerSuggestedBreakpoints = logicalInput.text.indexOf("\u200b") >= 0; + + let currentX = 0; + + for (let i = 0; i < logicalInput.length(); i++) { + const section = logicalInput.getSection(i); + const codePoint = logicalInput.getCharCode(i); + if (!whitespace[codePoint]) currentX += getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize); + + // Ideographic characters, spaces, and word-breaking punctuation that often appear without + // surrounding spaces. + if ((i < logicalInput.length() - 1)) { + const ideographicBreak = charAllowsIdeographicBreaking(codePoint); + if (breakable[codePoint] || ideographicBreak || section.imageName) { + + potentialLineBreaks.push( + evaluateBreak( + i + 1, + currentX, + targetWidth, + potentialLineBreaks, + calculatePenalty(codePoint, logicalInput.getCharCode(i + 1), ideographicBreak && hasServerSuggestedBreakpoints), + false)); + } + } + } + + return leastBadBreaks( + evaluateBreak( + logicalInput.length(), + currentX, + targetWidth, + potentialLineBreaks, + 0, + true)); +} + +function getAnchorAlignment(anchor: SymbolAnchor) { + let horizontalAlign = 0.5, verticalAlign = 0.5; + + switch (anchor) { + case 'right': + case 'top-right': + case 'bottom-right': + horizontalAlign = 1; + break; + case 'left': + case 'top-left': + case 'bottom-left': + horizontalAlign = 0; + break; + } + + switch (anchor) { + case 'bottom': + case 'bottom-right': + case 'bottom-left': + verticalAlign = 1; + break; + case 'top': + case 'top-right': + case 'top-left': + verticalAlign = 0; + break; + } + + return {horizontalAlign, verticalAlign}; +} + +function shapeLines(shaping: Shaping, + glyphMap: {[_: string]: {[_: number]: ?StyleGlyph}}, + glyphPositions: {[_: string]: {[_: number]: GlyphPosition}}, + imagePositions: {[_: string]: ImagePosition}, + lines: Array, + lineHeight: number, + textAnchor: SymbolAnchor, + textJustify: TextJustify, + writingMode: 1 | 2, + spacing: number, + allowVerticalPlacement: boolean, + layoutTextSizeThisZoom: number) { + + let x = 0; + let y = SHAPING_DEFAULT_OFFSET; + + let maxLineLength = 0; + let maxLineHeight = 0; + + const justify = + textJustify === 'right' ? 1 : + textJustify === 'left' ? 0 : 0.5; + + let lineIndex = 0; + for (const line of lines) { + line.trim(); + + const lineMaxScale = line.getMaxScale(); + const maxLineOffset = (lineMaxScale - 1) * ONE_EM; + const positionedLine = {positionedGlyphs: [], lineOffset: 0}; + shaping.positionedLines[lineIndex] = positionedLine; + const positionedGlyphs = positionedLine.positionedGlyphs; + let lineOffset = 0.0; + + if (!line.length()) { + y += lineHeight; // Still need a line feed after empty line + ++lineIndex; + continue; + } + + for (let i = 0; i < line.length(); i++) { + const section = line.getSection(i); + const sectionIndex = line.getSectionIndex(i); + const codePoint = line.getCharCode(i); + let baselineOffset = 0.0; + let metrics = null; + let rect = null; + let imageName = null; + let verticalAdvance = ONE_EM; + const vertical = !(writingMode === WritingMode.horizontal || + // Don't verticalize glyphs that have no upright orientation if vertical placement is disabled. + (!allowVerticalPlacement && !charHasUprightVerticalOrientation(codePoint)) || + // If vertical placement is enabled, don't verticalize glyphs that + // are from complex text layout script, or whitespaces. + (allowVerticalPlacement && (whitespace[codePoint] || charInComplexShapingScript(codePoint)))); + + if (!section.imageName) { + const positions = glyphPositions[section.fontStack]; + const glyphPosition = positions && positions[codePoint]; + if (glyphPosition && glyphPosition.rect) { + rect = glyphPosition.rect; + metrics = glyphPosition.metrics; + } else { + const glyphs = glyphMap[section.fontStack]; + const glyph = glyphs && glyphs[codePoint]; + if (!glyph) continue; + metrics = glyph.metrics; + } + + // We don't know the baseline, but since we're laying out + // at 24 points, we can calculate how much it will move when + // we scale up or down. + baselineOffset = (lineMaxScale - section.scale) * ONE_EM; + } else { + const imagePosition = imagePositions[section.imageName]; + if (!imagePosition) continue; + imageName = section.imageName; + shaping.iconsInText = shaping.iconsInText || true; + rect = imagePosition.paddedRect; + const size = imagePosition.displaySize; + // If needed, allow to set scale factor for an image using + // alias "image-scale" that could be alias for "font-scale" + // when FormattedSection is an image section. + section.scale = section.scale * ONE_EM / layoutTextSizeThisZoom; + + metrics = {width: size[0], + height: size[1], + left: IMAGE_PADDING, + top: -GLYPH_PBF_BORDER, + advance: vertical ? size[1] : size[0]}; + + // Difference between one EM and an image size. + // Aligns bottom of an image to a baseline level. + const imageOffset = ONE_EM - size[1] * section.scale; + baselineOffset = maxLineOffset + imageOffset; + verticalAdvance = metrics.advance; + + // Difference between height of an image and one EM at max line scale. + // Pushes current line down if an image size is over 1 EM at max line scale. + const offset = vertical ? size[0] * section.scale - ONE_EM * lineMaxScale : + size[1] * section.scale - ONE_EM * lineMaxScale; + if (offset > 0 && offset > lineOffset) { + lineOffset = offset; + } + } + + if (!vertical) { + positionedGlyphs.push({glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect}); + x += metrics.advance * section.scale + spacing; + } else { + shaping.verticalizable = true; + positionedGlyphs.push({glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect}); + x += verticalAdvance * section.scale + spacing; + } + } + + // Only justify if we placed at least one glyph + if (positionedGlyphs.length !== 0) { + const lineLength = x - spacing; + maxLineLength = Math.max(lineLength, maxLineLength); + justifyLine(positionedGlyphs, 0, positionedGlyphs.length - 1, justify, lineOffset); + } + + x = 0; + const currentLineHeight = lineHeight * lineMaxScale + lineOffset; + positionedLine.lineOffset = Math.max(lineOffset, maxLineOffset); + y += currentLineHeight; + maxLineHeight = Math.max(currentLineHeight, maxLineHeight); + ++lineIndex; + } + + // Calculate the bounding box and justify / align text block. + const height = y - SHAPING_DEFAULT_OFFSET; + const {horizontalAlign, verticalAlign} = getAnchorAlignment(textAnchor); + align(shaping.positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, height, lines.length); + + shaping.top += -verticalAlign * height; + shaping.bottom = shaping.top + height; + shaping.left += -horizontalAlign * maxLineLength; + shaping.right = shaping.left + maxLineLength; +} + +// justify right = 1, left = 0, center = 0.5 +function justifyLine(positionedGlyphs: Array, + start: number, + end: number, + justify: 1 | 0 | 0.5, + lineOffset: number) { + if (!justify && !lineOffset) + return; + + const lastPositionedGlyph = positionedGlyphs[end]; + const lastAdvance = lastPositionedGlyph.metrics.advance * lastPositionedGlyph.scale; + const lineIndent = (positionedGlyphs[end].x + lastAdvance) * justify; + + for (let j = start; j <= end; j++) { + positionedGlyphs[j].x -= lineIndent; + positionedGlyphs[j].y += lineOffset; + } +} + +function align(positionedLines: Array, + justify: number, + horizontalAlign: number, + verticalAlign: number, + maxLineLength: number, + maxLineHeight: number, + lineHeight: number, + blockHeight: number, + lineCount: number) { + const shiftX = (justify - horizontalAlign) * maxLineLength; + let shiftY = 0; + + if (maxLineHeight !== lineHeight) { + shiftY = -blockHeight * verticalAlign - SHAPING_DEFAULT_OFFSET; + } else { + shiftY = (-verticalAlign * lineCount + 0.5) * lineHeight; + } + + for (const line of positionedLines) { + for (const positionedGlyph of line.positionedGlyphs) { + positionedGlyph.x += shiftX; + positionedGlyph.y += shiftY; + } + } +} + +export type PositionedIcon = { + image: ImagePosition, + top: number, + bottom: number, + left: number, + right: number, + collisionPadding?: [number, number, number, number] +}; + +function shapeIcon(image: ImagePosition, iconOffset: [number, number], iconAnchor: SymbolAnchor): PositionedIcon { + const {horizontalAlign, verticalAlign} = getAnchorAlignment(iconAnchor); + const dx = iconOffset[0]; + const dy = iconOffset[1]; + const x1 = dx - image.displaySize[0] * horizontalAlign; + const x2 = x1 + image.displaySize[0]; + const y1 = dy - image.displaySize[1] * verticalAlign; + const y2 = y1 + image.displaySize[1]; + return {image, top: y1, bottom: y2, left: x1, right: x2}; +} + +function fitIconToText(shapedIcon: PositionedIcon, shapedText: Shaping, + textFit: string, + padding: [ number, number, number, number ], + iconOffset: [ number, number ], fontScale: number): PositionedIcon { + assert(textFit !== 'none'); + assert(Array.isArray(padding) && padding.length === 4); + assert(Array.isArray(iconOffset) && iconOffset.length === 2); + + const image = shapedIcon.image; + + let collisionPadding; + if (image.content) { + const content = image.content; + const pixelRatio = image.pixelRatio || 1; + collisionPadding = [ + content[0] / pixelRatio, + content[1] / pixelRatio, + image.displaySize[0] - content[2] / pixelRatio, + image.displaySize[1] - content[3] / pixelRatio + ]; + } + + // We don't respect the icon-anchor, because icon-text-fit is set. Instead, + // the icon will be centered on the text, then stretched in the given + // dimensions. + + const textLeft = shapedText.left * fontScale; + const textRight = shapedText.right * fontScale; + + let top, right, bottom, left; + if (textFit === 'width' || textFit === 'both') { + // Stretched horizontally to the text width + left = iconOffset[0] + textLeft - padding[3]; + right = iconOffset[0] + textRight + padding[1]; + } else { + // Centered on the text + left = iconOffset[0] + (textLeft + textRight - image.displaySize[0]) / 2; + right = left + image.displaySize[0]; + } + + const textTop = shapedText.top * fontScale; + const textBottom = shapedText.bottom * fontScale; + if (textFit === 'height' || textFit === 'both') { + // Stretched vertically to the text height + top = iconOffset[1] + textTop - padding[0]; + bottom = iconOffset[1] + textBottom + padding[2]; + } else { + // Centered on the text + top = iconOffset[1] + (textTop + textBottom - image.displaySize[1]) / 2; + bottom = top + image.displaySize[1]; + } + + return {image, top, right, bottom, left, collisionPadding}; +} diff --git a/node_modules/mapbox-gl/src/symbol/symbol_layout.js b/node_modules/mapbox-gl/src/symbol/symbol_layout.js new file mode 100644 index 0000000000000000000000000000000000000000..990c8417282fdb341346d1d31cb1e1465c5f57d3 --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/symbol_layout.js @@ -0,0 +1,796 @@ +// @flow + +import Anchor from './anchor'; + +import {getAnchors, getCenterAnchor} from './get_anchors'; +import clipLine from './clip_line'; +import {shapeText, shapeIcon, WritingMode, fitIconToText} from './shaping'; +import {getGlyphQuads, getIconQuads} from './quads'; +import CollisionFeature from './collision_feature'; +import {warnOnce} from '../util/util'; +import { + allowsVerticalWritingMode, + allowsLetterSpacing +} from '../util/script_detection'; +import findPoleOfInaccessibility from '../util/find_pole_of_inaccessibility'; +import classifyRings from '../util/classify_rings'; +import EXTENT from '../data/extent'; +import SymbolBucket from '../data/bucket/symbol_bucket'; +import EvaluationParameters from '../style/evaluation_parameters'; +import {SIZE_PACK_FACTOR} from './symbol_size'; +import ONE_EM from './one_em'; +import type {CanonicalTileID} from '../source/tile_id'; +import type {Shaping, PositionedIcon, TextJustify} from './shaping'; +import type {CollisionBoxArray} from '../data/array_types'; +import type {SymbolFeature} from '../data/bucket/symbol_bucket'; +import type {StyleImage} from '../style/style_image'; +import type {StyleGlyph} from '../style/style_glyph'; +import type SymbolStyleLayer from '../style/style_layer/symbol_style_layer'; +import type {ImagePosition} from '../render/image_atlas'; +import type {GlyphPosition} from '../render/glyph_atlas'; +import type {PossiblyEvaluatedPropertyValue} from '../style/properties'; + +import Point from '@mapbox/point-geometry'; +import murmur3 from 'murmurhash-js'; + +// The symbol layout process needs `text-size` evaluated at up to five different zoom levels, and +// `icon-size` at up to three: +// +// 1. `text-size` at the zoom level of the bucket. Used to calculate a per-feature size for source `text-size` +// expressions, and to calculate the box dimensions for icon-text-fit. +// 2. `icon-size` at the zoom level of the bucket. Used to calculate a per-feature size for source `icon-size` +// expressions. +// 3. `text-size` and `icon-size` at the zoom level of the bucket, plus one. Used to calculate collision boxes. +// 4. `text-size` at zoom level 18. Used for something line-symbol-placement-related. +// 5. For composite `*-size` expressions: two zoom levels of curve stops that "cover" the zoom level of the +// bucket. These go into a vertex buffer and are used by the shader to interpolate the size at render time. +// +// (1) and (2) are stored in `bucket.layers[0].layout`. The remainder are below. +// +type Sizes = { + layoutTextSize: PossiblyEvaluatedPropertyValue, // (3) + layoutIconSize: PossiblyEvaluatedPropertyValue, // (3) + textMaxSize: PossiblyEvaluatedPropertyValue, // (4) + compositeTextSizes: [PossiblyEvaluatedPropertyValue, PossiblyEvaluatedPropertyValue], // (5) + compositeIconSizes: [PossiblyEvaluatedPropertyValue, PossiblyEvaluatedPropertyValue], // (5) +}; + +export type TextAnchor = 'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; + +// The radial offset is to the edge of the text box +// In the horizontal direction, the edge of the text box is where glyphs start +// But in the vertical direction, the glyphs appear to "start" at the baseline +// We don't actually load baseline data, but we assume an offset of ONE_EM - 17 +// (see "yOffset" in shaping.js) +const baselineOffset = 7; +const INVALID_TEXT_OFFSET = Number.POSITIVE_INFINITY; + +export function evaluateVariableOffset(anchor: TextAnchor, offset: [number, number]) { + + function fromRadialOffset(anchor: TextAnchor, radialOffset: number) { + let x = 0, y = 0; + if (radialOffset < 0) radialOffset = 0; // Ignore negative offset. + // solve for r where r^2 + r^2 = radialOffset^2 + const hypotenuse = radialOffset / Math.sqrt(2); + switch (anchor) { + case 'top-right': + case 'top-left': + y = hypotenuse - baselineOffset; + break; + case 'bottom-right': + case 'bottom-left': + y = -hypotenuse + baselineOffset; + break; + case 'bottom': + y = -radialOffset + baselineOffset; + break; + case 'top': + y = radialOffset - baselineOffset; + break; + } + + switch (anchor) { + case 'top-right': + case 'bottom-right': + x = -hypotenuse; + break; + case 'top-left': + case 'bottom-left': + x = hypotenuse; + break; + case 'left': + x = radialOffset; + break; + case 'right': + x = -radialOffset; + break; + } + + return [x, y]; + } + + function fromTextOffset(anchor: TextAnchor, offsetX: number, offsetY: number) { + let x = 0, y = 0; + // Use absolute offset values. + offsetX = Math.abs(offsetX); + offsetY = Math.abs(offsetY); + + switch (anchor) { + case 'top-right': + case 'top-left': + case 'top': + y = offsetY - baselineOffset; + break; + case 'bottom-right': + case 'bottom-left': + case 'bottom': + y = -offsetY + baselineOffset; + break; + } + + switch (anchor) { + case 'top-right': + case 'bottom-right': + case 'right': + x = -offsetX; + break; + case 'top-left': + case 'bottom-left': + case 'left': + x = offsetX; + break; + } + + return [x, y]; + } + + return (offset[1] !== INVALID_TEXT_OFFSET) ? fromTextOffset(anchor, offset[0], offset[1]) : fromRadialOffset(anchor, offset[0]); +} + +export function performSymbolLayout(bucket: SymbolBucket, + glyphMap: {[_: string]: {[number]: ?StyleGlyph}}, + glyphPositions: {[_: string]: {[number]: GlyphPosition}}, + imageMap: {[_: string]: StyleImage}, + imagePositions: {[_: string]: ImagePosition}, + showCollisionBoxes: boolean, + canonical: CanonicalTileID) { + bucket.createArrays(); + + const tileSize = 512 * bucket.overscaling; + bucket.tilePixelRatio = EXTENT / tileSize; + bucket.compareText = {}; + bucket.iconsNeedLinear = false; + + const layout = bucket.layers[0].layout; + const unevaluatedLayoutValues = bucket.layers[0]._unevaluatedLayout._values; + + const sizes = {}; + + if (bucket.textSizeData.kind === 'composite') { + const {minZoom, maxZoom} = bucket.textSizeData; + sizes.compositeTextSizes = [ + unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(minZoom), canonical), + unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), canonical) + ]; + } + + if (bucket.iconSizeData.kind === 'composite') { + const {minZoom, maxZoom} = bucket.iconSizeData; + sizes.compositeIconSizes = [ + unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(minZoom), canonical), + unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), canonical) + ]; + } + + sizes.layoutTextSize = unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(bucket.zoom + 1), canonical); + sizes.layoutIconSize = unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(bucket.zoom + 1), canonical); + sizes.textMaxSize = unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(18)); + + const lineHeight = layout.get('text-line-height') * ONE_EM; + const textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point'; + const keepUpright = layout.get('text-keep-upright'); + const textSize = layout.get('text-size'); + + for (const feature of bucket.features) { + const fontstack = layout.get('text-font').evaluate(feature, {}, canonical).join(','); + const layoutTextSizeThisZoom = textSize.evaluate(feature, {}, canonical); + const layoutTextSize = sizes.layoutTextSize.evaluate(feature, {}, canonical); + const layoutIconSize = sizes.layoutIconSize.evaluate(feature, {}, canonical); + + const shapedTextOrientations = { + horizontal: {}, + vertical: undefined + }; + const text = feature.text; + let textOffset: [number, number] = [0, 0]; + if (text) { + const unformattedText = text.toString(); + const spacing = layout.get('text-letter-spacing').evaluate(feature, {}, canonical) * ONE_EM; + const spacingIfAllowed = allowsLetterSpacing(unformattedText) ? spacing : 0; + + const textAnchor = layout.get('text-anchor').evaluate(feature, {}, canonical); + const variableTextAnchor = layout.get('text-variable-anchor'); + + if (!variableTextAnchor) { + const radialOffset = layout.get('text-radial-offset').evaluate(feature, {}, canonical); + // Layers with variable anchors use the `text-radial-offset` property and the [x, y] offset vector + // is calculated at placement time instead of layout time + if (radialOffset) { + // The style spec says don't use `text-offset` and `text-radial-offset` together + // but doesn't actually specify what happens if you use both. We go with the radial offset. + textOffset = evaluateVariableOffset(textAnchor, [radialOffset * ONE_EM, INVALID_TEXT_OFFSET]); + } else { + textOffset = (layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM): any); + } + } + + let textJustify = textAlongLine ? + "center" : + layout.get('text-justify').evaluate(feature, {}, canonical); + + const symbolPlacement = layout.get('symbol-placement'); + const maxWidth = symbolPlacement === 'point' ? + layout.get('text-max-width').evaluate(feature, {}, canonical) * ONE_EM : + 0; + + const addVerticalShapingForPointLabelIfNeeded = () => { + if (bucket.allowVerticalPlacement && allowsVerticalWritingMode(unformattedText)) { + // Vertical POI label placement is meant to be used for scripts that support vertical + // writing mode, thus, default left justification is used. If Latin + // scripts would need to be supported, this should take into account other justifications. + shapedTextOrientations.vertical = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, + 'left', spacingIfAllowed, textOffset, WritingMode.vertical, true, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom); + } + }; + + // If this layer uses text-variable-anchor, generate shapings for all justification possibilities. + if (!textAlongLine && variableTextAnchor) { + const justifications = textJustify === "auto" ? + variableTextAnchor.map(a => getAnchorJustification(a)) : + [textJustify]; + + let singleLine = false; + for (let i = 0; i < justifications.length; i++) { + const justification: TextJustify = justifications[i]; + if (shapedTextOrientations.horizontal[justification]) continue; + if (singleLine) { + // If the shaping for the first justification was only a single line, we + // can re-use it for the other justifications + shapedTextOrientations.horizontal[justification] = shapedTextOrientations.horizontal[0]; + } else { + // If using text-variable-anchor for the layer, we use a center anchor for all shapings and apply + // the offsets for the anchor in the placement step. + const shaping = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, 'center', + justification, spacingIfAllowed, textOffset, WritingMode.horizontal, false, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom); + if (shaping) { + shapedTextOrientations.horizontal[justification] = shaping; + singleLine = shaping.positionedLines.length === 1; + } + } + } + + addVerticalShapingForPointLabelIfNeeded(); + } else { + if (textJustify === "auto") { + textJustify = getAnchorJustification(textAnchor); + } + + // Horizontal point or line label. + const shaping = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, + textOffset, WritingMode.horizontal, false, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom); + if (shaping) shapedTextOrientations.horizontal[textJustify] = shaping; + + // Vertical point label (if allowVerticalPlacement is enabled). + addVerticalShapingForPointLabelIfNeeded(); + + // Verticalized line label. + if (allowsVerticalWritingMode(unformattedText) && textAlongLine && keepUpright) { + shapedTextOrientations.vertical = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, + spacingIfAllowed, textOffset, WritingMode.vertical, false, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom); + } + } + } + + let shapedIcon; + let isSDFIcon = false; + if (feature.icon && feature.icon.name) { + const image = imageMap[feature.icon.name]; + if (image) { + shapedIcon = shapeIcon( + imagePositions[feature.icon.name], + layout.get('icon-offset').evaluate(feature, {}, canonical), + layout.get('icon-anchor').evaluate(feature, {}, canonical)); + isSDFIcon = image.sdf; + if (bucket.sdfIcons === undefined) { + bucket.sdfIcons = image.sdf; + } else if (bucket.sdfIcons !== image.sdf) { + warnOnce('Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer'); + } + if (image.pixelRatio !== bucket.pixelRatio) { + bucket.iconsNeedLinear = true; + } else if (layout.get('icon-rotate').constantOr(1) !== 0) { + bucket.iconsNeedLinear = true; + } + } + } + + const shapedText = getDefaultHorizontalShaping(shapedTextOrientations.horizontal) || shapedTextOrientations.vertical; + bucket.iconsInText = shapedText ? shapedText.iconsInText : false; + if (shapedText || shapedIcon) { + addFeature(bucket, feature, shapedTextOrientations, shapedIcon, imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, canonical); + } + } + + if (showCollisionBoxes) { + bucket.generateCollisionDebugBuffers(); + } +} + +// Choose the justification that matches the direction of the TextAnchor +export function getAnchorJustification(anchor: TextAnchor): TextJustify { + switch (anchor) { + case 'right': + case 'top-right': + case 'bottom-right': + return 'right'; + case 'left': + case 'top-left': + case 'bottom-left': + return 'left'; + } + return 'center'; +} + +/** + * Given a feature and its shaped text and icon data, add a 'symbol + * instance' for each _possible_ placement of the symbol feature. + * (At render timePlaceSymbols#place() selects which of these instances to + * show or hide based on collisions with symbols in other layers.) + * @private + */ +function addFeature(bucket: SymbolBucket, + feature: SymbolFeature, + shapedTextOrientations: any, + shapedIcon: PositionedIcon | void, + imageMap: {[_: string]: StyleImage}, + sizes: Sizes, + layoutTextSize: number, + layoutIconSize: number, + textOffset: [number, number], + isSDFIcon: boolean, canonical: CanonicalTileID) { + // To reduce the number of labels that jump around when zooming we need + // to use a text-size value that is the same for all zoom levels. + // bucket calculates text-size at a high zoom level so that all tiles can + // use the same value when calculating anchor positions. + let textMaxSize = sizes.textMaxSize.evaluate(feature, {}); + if (textMaxSize === undefined) { + textMaxSize = layoutTextSize; + } + const layout = bucket.layers[0].layout; + const iconOffset = layout.get('icon-offset').evaluate(feature, {}, canonical); + const defaultHorizontalShaping = getDefaultHorizontalShaping(shapedTextOrientations.horizontal); + const glyphSize = 24, + fontScale = layoutTextSize / glyphSize, + textBoxScale = bucket.tilePixelRatio * fontScale, + textMaxBoxScale = bucket.tilePixelRatio * textMaxSize / glyphSize, + iconBoxScale = bucket.tilePixelRatio * layoutIconSize, + symbolMinDistance = bucket.tilePixelRatio * layout.get('symbol-spacing'), + textPadding = layout.get('text-padding') * bucket.tilePixelRatio, + iconPadding = layout.get('icon-padding') * bucket.tilePixelRatio, + textMaxAngle = layout.get('text-max-angle') / 180 * Math.PI, + textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point', + iconAlongLine = layout.get('icon-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point', + symbolPlacement = layout.get('symbol-placement'), + textRepeatDistance = symbolMinDistance / 2; + + const iconTextFit = layout.get('icon-text-fit'); + let verticallyShapedIcon; + // Adjust shaped icon size when icon-text-fit is used. + if (shapedIcon && iconTextFit !== 'none') { + if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) { + verticallyShapedIcon = fitIconToText(shapedIcon, shapedTextOrientations.vertical, iconTextFit, + layout.get('icon-text-fit-padding'), iconOffset, fontScale); + } + if (defaultHorizontalShaping) { + shapedIcon = fitIconToText(shapedIcon, defaultHorizontalShaping, iconTextFit, + layout.get('icon-text-fit-padding'), iconOffset, fontScale); + } + } + + const addSymbolAtAnchor = (line, anchor) => { + if (anchor.x < 0 || anchor.x >= EXTENT || anchor.y < 0 || anchor.y >= EXTENT) { + // Symbol layers are drawn across tile boundaries, We filter out symbols + // outside our tile boundaries (which may be included in vector tile buffers) + // to prevent double-drawing symbols. + return; + } + + addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, bucket.layers[0], + bucket.collisionBoxArray, feature.index, feature.sourceLayerIndex, bucket.index, + textBoxScale, textPadding, textAlongLine, textOffset, + iconBoxScale, iconPadding, iconAlongLine, iconOffset, + feature, sizes, isSDFIcon, canonical, layoutTextSize); + }; + + if (symbolPlacement === 'line') { + for (const line of clipLine(feature.geometry, 0, 0, EXTENT, EXTENT)) { + const anchors = getAnchors( + line, + symbolMinDistance, + textMaxAngle, + shapedTextOrientations.vertical || defaultHorizontalShaping, + shapedIcon, + glyphSize, + textMaxBoxScale, + bucket.overscaling, + EXTENT + ); + for (const anchor of anchors) { + const shapedText = defaultHorizontalShaping; + if (!shapedText || !anchorIsTooClose(bucket, shapedText.text, textRepeatDistance, anchor)) { + addSymbolAtAnchor(line, anchor); + } + } + } + } else if (symbolPlacement === 'line-center') { + // No clipping, multiple lines per feature are allowed + // "lines" with only one point are ignored as in clipLines + for (const line of feature.geometry) { + if (line.length > 1) { + const anchor = getCenterAnchor( + line, + textMaxAngle, + shapedTextOrientations.vertical || defaultHorizontalShaping, + shapedIcon, + glyphSize, + textMaxBoxScale); + if (anchor) { + addSymbolAtAnchor(line, anchor); + } + } + } + } else if (feature.type === 'Polygon') { + for (const polygon of classifyRings(feature.geometry, 0)) { + // 16 here represents 2 pixels + const poi = findPoleOfInaccessibility(polygon, 16); + addSymbolAtAnchor(polygon[0], new Anchor(poi.x, poi.y, 0)); + } + } else if (feature.type === 'LineString') { + // https://github.com/mapbox/mapbox-gl-js/issues/3808 + for (const line of feature.geometry) { + addSymbolAtAnchor(line, new Anchor(line[0].x, line[0].y, 0)); + } + } else if (feature.type === 'Point') { + for (const points of feature.geometry) { + for (const point of points) { + addSymbolAtAnchor([point], new Anchor(point.x, point.y, 0)); + } + } + } +} + +const MAX_GLYPH_ICON_SIZE = 255; +const MAX_PACKED_SIZE = MAX_GLYPH_ICON_SIZE * SIZE_PACK_FACTOR; +export {MAX_PACKED_SIZE}; + +function addTextVertices(bucket: SymbolBucket, + anchor: Point, + shapedText: Shaping, + imageMap: {[_: string]: StyleImage}, + layer: SymbolStyleLayer, + textAlongLine: boolean, + feature: SymbolFeature, + textOffset: [number, number], + lineArray: {lineStartIndex: number, lineLength: number}, + writingMode: number, + placementTypes: Array<'vertical' | 'center' | 'left' | 'right'>, + placedTextSymbolIndices: {[_: string]: number}, + placedIconIndex: number, + sizes: Sizes, + canonical: CanonicalTileID) { + const glyphQuads = getGlyphQuads(anchor, shapedText, textOffset, + layer, textAlongLine, feature, imageMap, bucket.allowVerticalPlacement); + + const sizeData = bucket.textSizeData; + let textSizeData = null; + + if (sizeData.kind === 'source') { + textSizeData = [ + SIZE_PACK_FACTOR * layer.layout.get('text-size').evaluate(feature, {}) + ]; + if (textSizeData[0] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`); + } + } else if (sizeData.kind === 'composite') { + textSizeData = [ + SIZE_PACK_FACTOR * sizes.compositeTextSizes[0].evaluate(feature, {}, canonical), + SIZE_PACK_FACTOR * sizes.compositeTextSizes[1].evaluate(feature, {}, canonical) + ]; + if (textSizeData[0] > MAX_PACKED_SIZE || textSizeData[1] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "text-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "text-size".`); + } + } + + bucket.addSymbols( + bucket.text, + glyphQuads, + textSizeData, + textOffset, + textAlongLine, + feature, + writingMode, + anchor, + lineArray.lineStartIndex, + lineArray.lineLength, + placedIconIndex, + canonical); + + // The placedSymbolArray is used at render time in drawTileSymbols + // These indices allow access to the array at collision detection time + for (const placementType of placementTypes) { + placedTextSymbolIndices[placementType] = bucket.text.placedSymbolArray.length - 1; + } + + return glyphQuads.length * 4; +} + +function getDefaultHorizontalShaping(horizontalShaping: {[_: TextJustify]: Shaping}): Shaping | null { + // We don't care which shaping we get because this is used for collision purposes + // and all the justifications have the same collision box + for (const justification: any in horizontalShaping) { + return horizontalShaping[justification]; + } + return null; +} + +/** + * Add a single label & icon placement. + * + * @private + */ +function addSymbol(bucket: SymbolBucket, + anchor: Anchor, + line: Array, + shapedTextOrientations: any, + shapedIcon: PositionedIcon | void, + imageMap: {[_: string]: StyleImage}, + verticallyShapedIcon: PositionedIcon | void, + layer: SymbolStyleLayer, + collisionBoxArray: CollisionBoxArray, + featureIndex: number, + sourceLayerIndex: number, + bucketIndex: number, + textBoxScale: number, + textPadding: number, + textAlongLine: boolean, + textOffset: [number, number], + iconBoxScale: number, + iconPadding: number, + iconAlongLine: boolean, + iconOffset: [number, number], + feature: SymbolFeature, + sizes: Sizes, + isSDFIcon: boolean, + canonical: CanonicalTileID, + layoutTextSize: number) { + const lineArray = bucket.addToLineVertexArray(anchor, line); + + let textCollisionFeature, iconCollisionFeature, verticalTextCollisionFeature, verticalIconCollisionFeature; + + let numIconVertices = 0; + let numVerticalIconVertices = 0; + let numHorizontalGlyphVertices = 0; + let numVerticalGlyphVertices = 0; + let placedIconSymbolIndex = -1; + let verticalPlacedIconSymbolIndex = -1; + const placedTextSymbolIndices = {}; + let key = murmur3(''); + + let textOffset0 = 0; + let textOffset1 = 0; + if (layer._unevaluatedLayout.getValue('text-radial-offset') === undefined) { + [textOffset0, textOffset1] = (layer.layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM): any); + } else { + textOffset0 = layer.layout.get('text-radial-offset').evaluate(feature, {}, canonical) * ONE_EM; + textOffset1 = INVALID_TEXT_OFFSET; + } + + if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) { + const textRotation = layer.layout.get('text-rotate').evaluate(feature, {}, canonical); + const verticalTextRotation = textRotation + 90.0; + const verticalShaping = shapedTextOrientations.vertical; + verticalTextCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textBoxScale, textPadding, textAlongLine, verticalTextRotation); + + if (verticallyShapedIcon) { + verticalIconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticallyShapedIcon, iconBoxScale, iconPadding, textAlongLine, verticalTextRotation); + } + } + + //Place icon first, so text can have a reference to its index in the placed symbol array. + //Text symbols can lazily shift at render-time because of variable anchor placement. + //If the style specifies an `icon-text-fit` then the icon would have to shift along with it. + // For more info check `updateVariableAnchors` in `draw_symbol.js` . + if (shapedIcon) { + const iconRotate = layer.layout.get('icon-rotate').evaluate(feature, {}); + const hasIconTextFit = layer.layout.get('icon-text-fit') !== 'none'; + const iconQuads = getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit); + const verticalIconQuads = verticallyShapedIcon ? getIconQuads(verticallyShapedIcon, iconRotate, isSDFIcon, hasIconTextFit) : undefined; + iconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconBoxScale, iconPadding, /*align boxes to line*/false, iconRotate); + + numIconVertices = iconQuads.length * 4; + + const sizeData = bucket.iconSizeData; + let iconSizeData = null; + + if (sizeData.kind === 'source') { + iconSizeData = [ + SIZE_PACK_FACTOR * layer.layout.get('icon-size').evaluate(feature, {}) + ]; + if (iconSizeData[0] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`); + } + } else if (sizeData.kind === 'composite') { + iconSizeData = [ + SIZE_PACK_FACTOR * sizes.compositeIconSizes[0].evaluate(feature, {}, canonical), + SIZE_PACK_FACTOR * sizes.compositeIconSizes[1].evaluate(feature, {}, canonical) + ]; + if (iconSizeData[0] > MAX_PACKED_SIZE || iconSizeData[1] > MAX_PACKED_SIZE) { + warnOnce(`${bucket.layerIds[0]}: Value for "icon-size" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your "icon-size".`); + } + } + + bucket.addSymbols( + bucket.icon, + iconQuads, + iconSizeData, + iconOffset, + iconAlongLine, + feature, + false, + anchor, + lineArray.lineStartIndex, + lineArray.lineLength, + // The icon itself does not have an associated symbol since the text isnt placed yet + -1, canonical); + + placedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1; + + if (verticalIconQuads) { + numVerticalIconVertices = verticalIconQuads.length * 4; + + bucket.addSymbols( + bucket.icon, + verticalIconQuads, + iconSizeData, + iconOffset, + iconAlongLine, + feature, + WritingMode.vertical, + anchor, + lineArray.lineStartIndex, + lineArray.lineLength, + // The icon itself does not have an associated symbol since the text isnt placed yet + -1, canonical); + + verticalPlacedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1; + } + } + + for (const justification: any in shapedTextOrientations.horizontal) { + const shaping = shapedTextOrientations.horizontal[justification]; + + if (!textCollisionFeature) { + key = murmur3(shaping.text); + const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}, canonical); + // As a collision approximation, we can use either the vertical or any of the horizontal versions of the feature + // We're counting on all versions having similar dimensions + textCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textBoxScale, textPadding, textAlongLine, textRotate); + } + + const singleLine = shaping.positionedLines.length === 1; + numHorizontalGlyphVertices += addTextVertices( + bucket, anchor, shaping, imageMap, layer, textAlongLine, feature, textOffset, lineArray, + shapedTextOrientations.vertical ? WritingMode.horizontal : WritingMode.horizontalOnly, + singleLine ? (Object.keys(shapedTextOrientations.horizontal): any) : [justification], + placedTextSymbolIndices, placedIconSymbolIndex, sizes, canonical); + + if (singleLine) { + break; + } + } + + if (shapedTextOrientations.vertical) { + numVerticalGlyphVertices += addTextVertices( + bucket, anchor, shapedTextOrientations.vertical, imageMap, layer, textAlongLine, feature, + textOffset, lineArray, WritingMode.vertical, ['vertical'], placedTextSymbolIndices, verticalPlacedIconSymbolIndex, sizes, canonical); + } + + const textBoxStartIndex = textCollisionFeature ? textCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const textBoxEndIndex = textCollisionFeature ? textCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + + const verticalTextBoxStartIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const verticalTextBoxEndIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + + const iconBoxStartIndex = iconCollisionFeature ? iconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const iconBoxEndIndex = iconCollisionFeature ? iconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + + const verticalIconBoxStartIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length; + const verticalIconBoxEndIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length; + + // Check if runtime collision circles should be used for any of the collision features. + // It is enough to choose the tallest feature shape as circles are always placed on a line. + // All measurements are in glyph metrics and later converted into pixels using proper font size "layoutTextSize" + let collisionCircleDiameter = -1; + + const getCollisionCircleHeight = (feature: ?CollisionFeature, prevHeight: number): number => { + if (feature && feature.circleDiameter) + return Math.max(feature.circleDiameter, prevHeight); + return prevHeight; + }; + + collisionCircleDiameter = getCollisionCircleHeight(textCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(verticalTextCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(iconCollisionFeature, collisionCircleDiameter); + collisionCircleDiameter = getCollisionCircleHeight(verticalIconCollisionFeature, collisionCircleDiameter); + const useRuntimeCollisionCircles = (collisionCircleDiameter > -1) ? 1 : 0; + + // Convert circle collision height into pixels + if (useRuntimeCollisionCircles) + collisionCircleDiameter *= layoutTextSize / ONE_EM; + + if (bucket.glyphOffsetArray.length >= SymbolBucket.MAX_GLYPHS) warnOnce( + "Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907" + ); + + if (feature.sortKey !== undefined) { + bucket.addToSortKeyRanges(bucket.symbolInstances.length, feature.sortKey); + } + + bucket.symbolInstances.emplaceBack( + anchor.x, + anchor.y, + placedTextSymbolIndices.right >= 0 ? placedTextSymbolIndices.right : -1, + placedTextSymbolIndices.center >= 0 ? placedTextSymbolIndices.center : -1, + placedTextSymbolIndices.left >= 0 ? placedTextSymbolIndices.left : -1, + placedTextSymbolIndices.vertical || -1, + placedIconSymbolIndex, + verticalPlacedIconSymbolIndex, + key, + textBoxStartIndex, + textBoxEndIndex, + verticalTextBoxStartIndex, + verticalTextBoxEndIndex, + iconBoxStartIndex, + iconBoxEndIndex, + verticalIconBoxStartIndex, + verticalIconBoxEndIndex, + featureIndex, + numHorizontalGlyphVertices, + numVerticalGlyphVertices, + numIconVertices, + numVerticalIconVertices, + useRuntimeCollisionCircles, + 0, + textBoxScale, + textOffset0, + textOffset1, + collisionCircleDiameter); +} + +function anchorIsTooClose(bucket: any, text: string, repeatDistance: number, anchor: Point) { + const compareText = bucket.compareText; + if (!(text in compareText)) { + compareText[text] = []; + } else { + const otherAnchors = compareText[text]; + for (let k = otherAnchors.length - 1; k >= 0; k--) { + if (anchor.dist(otherAnchors[k]) < repeatDistance) { + // If it's within repeatDistance of one anchor, stop looking + return true; + } + } + } + // If anchor is not within repeatDistance of any other anchor, add to array + compareText[text].push(anchor); + return false; +} diff --git a/node_modules/mapbox-gl/src/symbol/symbol_size.js b/node_modules/mapbox-gl/src/symbol/symbol_size.js new file mode 100644 index 0000000000000000000000000000000000000000..dab8f4b898974f47d2d103e1a80d03545db20120 --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/symbol_size.js @@ -0,0 +1,113 @@ +// @flow + +import {number as interpolate} from '../style-spec/util/interpolate'; +import Interpolate from '../style-spec/expression/definitions/interpolate'; +import {clamp} from '../util/util'; +import EvaluationParameters from '../style/evaluation_parameters'; + +import type {PropertyValue, PossiblyEvaluatedPropertyValue} from '../style/properties'; +import type {InterpolationType} from '../style-spec/expression/definitions/interpolate'; + +const SIZE_PACK_FACTOR = 128; + +export {getSizeData, evaluateSizeForFeature, evaluateSizeForZoom, SIZE_PACK_FACTOR}; + +export type SizeData = { + kind: 'constant', + layoutSize: number +} | { + kind: 'source' +} | { + kind: 'camera', + minZoom: number, + maxZoom: number, + minSize: number, + maxSize: number, + interpolationType: ?InterpolationType +} | { + kind: 'composite', + minZoom: number, + maxZoom: number, + interpolationType: ?InterpolationType +}; + +// For {text,icon}-size, get the bucket-level data that will be needed by +// the painter to set symbol-size-related uniforms +function getSizeData(tileZoom: number, value: PropertyValue>): SizeData { + const {expression} = value; + + if (expression.kind === 'constant') { + const layoutSize = expression.evaluate(new EvaluationParameters(tileZoom + 1)); + return {kind: 'constant', layoutSize}; + + } else if (expression.kind === 'source') { + return {kind: 'source'}; + + } else { + const {zoomStops, interpolationType} = expression; + + // calculate covering zoom stops for zoom-dependent values + let lower = 0; + while (lower < zoomStops.length && zoomStops[lower] <= tileZoom) lower++; + lower = Math.max(0, lower - 1); + let upper = lower; + while (upper < zoomStops.length && zoomStops[upper] < tileZoom + 1) upper++; + upper = Math.min(zoomStops.length - 1, upper); + + const minZoom = zoomStops[lower]; + const maxZoom = zoomStops[upper]; + + // We'd like to be able to use CameraExpression or CompositeExpression in these + // return types rather than ExpressionSpecification, but the former are not + // transferrable across Web Worker boundaries. + if (expression.kind === 'composite') { + return {kind: 'composite', minZoom, maxZoom, interpolationType}; + } + + // for camera functions, also save off the function values + // evaluated at the covering zoom levels + const minSize = expression.evaluate(new EvaluationParameters(minZoom)); + const maxSize = expression.evaluate(new EvaluationParameters(maxZoom)); + + return {kind: 'camera', minZoom, maxZoom, minSize, maxSize, interpolationType}; + } +} + +function evaluateSizeForFeature(sizeData: SizeData, + {uSize, uSizeT}: { uSize: number, uSizeT: number }, + {lowerSize, upperSize}: { lowerSize: number, upperSize: number}) { + if (sizeData.kind === 'source') { + return lowerSize / SIZE_PACK_FACTOR; + } else if (sizeData.kind === 'composite') { + return interpolate(lowerSize / SIZE_PACK_FACTOR, upperSize / SIZE_PACK_FACTOR, uSizeT); + } + return uSize; +} + +function evaluateSizeForZoom(sizeData: SizeData, zoom: number) { + let uSizeT = 0; + let uSize = 0; + + if (sizeData.kind === 'constant') { + uSize = sizeData.layoutSize; + + } else if (sizeData.kind !== 'source') { + const {interpolationType, minZoom, maxZoom} = sizeData; + + // Even though we could get the exact value of the camera function + // at z = tr.zoom, we intentionally do not: instead, we interpolate + // between the camera function values at a pair of zoom stops covering + // [tileZoom, tileZoom + 1] in order to be consistent with this + // restriction on composite functions + const t = !interpolationType ? 0 : clamp( + Interpolate.interpolationFactor(interpolationType, zoom, minZoom, maxZoom), 0, 1); + + if (sizeData.kind === 'camera') { + uSize = interpolate(sizeData.minSize, sizeData.maxSize, t); + } else { + uSizeT = t; + } + } + + return {uSizeT, uSize}; +} diff --git a/node_modules/mapbox-gl/src/symbol/transform_text.js b/node_modules/mapbox-gl/src/symbol/transform_text.js new file mode 100644 index 0000000000000000000000000000000000000000..c6d4c74671383c343c7b4a957275911c5185fc2d --- /dev/null +++ b/node_modules/mapbox-gl/src/symbol/transform_text.js @@ -0,0 +1,29 @@ +// @flow + +import {plugin as rtlTextPlugin} from '../source/rtl_text_plugin'; + +import type SymbolStyleLayer from '../style/style_layer/symbol_style_layer'; +import type {Feature} from '../style-spec/expression'; +import Formatted from '../style-spec/expression/types/formatted'; + +function transformText(text: string, layer: SymbolStyleLayer, feature: Feature) { + const transform = layer.layout.get('text-transform').evaluate(feature, {}); + if (transform === 'uppercase') { + text = text.toLocaleUpperCase(); + } else if (transform === 'lowercase') { + text = text.toLocaleLowerCase(); + } + + if (rtlTextPlugin.applyArabicShaping) { + text = rtlTextPlugin.applyArabicShaping(text); + } + + return text; +} + +export default function(text: Formatted, layer: SymbolStyleLayer, feature: Feature): Formatted { + text.sections.forEach(section => { + section.text = transformText(section.text, layer, feature); + }); + return text; +} diff --git a/node_modules/mapbox-gl/src/types/callback.js b/node_modules/mapbox-gl/src/types/callback.js new file mode 100644 index 0000000000000000000000000000000000000000..217eff73014f170575a6b370adf4076346d8c5fc --- /dev/null +++ b/node_modules/mapbox-gl/src/types/callback.js @@ -0,0 +1,17 @@ +// @flow strict + +// Flow can't perfectly type Node-style callbacks yet; it does not have a way to +// express that if the first parameter is null, the second is not, so for the time +// being, both parameters must be optional. Use the following convention when defining +// a callback: +// +// asyncFunction((error, result) => { +// if (error) { +// // handle error +// } else if (result) { +// // handle success +// } +// }); +// +// See https://github.com/facebook/flow/issues/2123 for more. +export type Callback = (error: ?Error, result: ?T) => void; diff --git a/node_modules/mapbox-gl/src/types/cancelable.js b/node_modules/mapbox-gl/src/types/cancelable.js new file mode 100644 index 0000000000000000000000000000000000000000..e155168ac003a502129ba0f079e65a476e7838fe --- /dev/null +++ b/node_modules/mapbox-gl/src/types/cancelable.js @@ -0,0 +1,3 @@ +// @flow strict + +export type Cancelable = { cancel: () => void }; diff --git a/node_modules/mapbox-gl/src/types/tilejson.js b/node_modules/mapbox-gl/src/types/tilejson.js new file mode 100644 index 0000000000000000000000000000000000000000..328f378e2a95d280152c3ae4b1c3519ff5d31867 --- /dev/null +++ b/node_modules/mapbox-gl/src/types/tilejson.js @@ -0,0 +1,17 @@ +// @flow + +export type TileJSON = {| + tilejson: '2.2.0' | '2.1.0' | '2.0.1' | '2.0.0' | '1.0.0', + name?: string, + description?: string, + version?: string, + attribution?: string, + template?: string, + tiles: Array, + grids?: Array, + data?: Array, + minzoom?: number, + maxzoom?: number, + bounds?: [number, number, number, number], + center?: [number, number, number] +|}; diff --git a/node_modules/mapbox-gl/src/types/transferable.js b/node_modules/mapbox-gl/src/types/transferable.js new file mode 100644 index 0000000000000000000000000000000000000000..0d57cc4c5017e7805ceefa85ed2ba1ed9f8d40e1 --- /dev/null +++ b/node_modules/mapbox-gl/src/types/transferable.js @@ -0,0 +1,3 @@ +// @flow + +export type Transferable = ArrayBuffer | MessagePort | ImageBitmap; diff --git a/node_modules/mapbox-gl/src/types/window.js b/node_modules/mapbox-gl/src/types/window.js new file mode 100644 index 0000000000000000000000000000000000000000..8957156fcc71016485f546a050f72003f4924066 --- /dev/null +++ b/node_modules/mapbox-gl/src/types/window.js @@ -0,0 +1,172 @@ +// @flow strict + +/* global EventTarget, IDBEnvironment */ + +export interface Window extends EventTarget, IDBEnvironment { + +caches: CacheStorage; + +clientInformation: Navigator; + +closed: boolean; + defaultStatus: string; + +devicePixelRatio: number; + +document: Document; + +doNotTrack: string; + +frameElement: Element; + +frames: Window; + +history: History; + +innerHeight: number; + +innerWidth: number; + +isSecureContext: boolean; + +length: number; + +location: Location; + +origin: string; + name: string; + +navigator: Navigator; + offscreenBuffering: string | boolean; + onabort: (ev: UIEvent) => ?boolean; + onafterprint: (ev: Event) => ?boolean; + onbeforeprint: (ev: Event) => ?boolean; + onbeforeunload: (ev: Event) => ?boolean; + onblur: (ev: FocusEvent) => ?boolean; + oncanplay: (ev: Event) => ?boolean; + oncanplaythrough: (ev: Event) => ?boolean; + onchange: (ev: Event) => ?boolean; + onclick: (ev: MouseEvent) => ?boolean; + oncompassneedscalibration: (ev: Event) => ?boolean; + oncontextmenu: (ev: Event) => ?boolean; + ondblclick: (ev: MouseEvent) => ?boolean; + ondevicelight: (ev: Event) => ?boolean; + ondevicemotion: (ev: Event) => ?boolean; + ondeviceorientation: (ev: Event) => ?boolean; + ondrag: (ev: DragEvent) => ?boolean; + ondragend: (ev: DragEvent) => ?boolean; + ondragenter: (ev: DragEvent) => ?boolean; + ondragleave: (ev: DragEvent) => ?boolean; + ondragover: (ev: DragEvent) => ?boolean; + ondragstart: (ev: DragEvent) => ?boolean; + ondrop: (ev: DragEvent) => ?boolean; + ondurationchange: (ev: Event) => ?boolean; + onemptied: (ev: Event) => ?boolean; + onended: (ev: Event) => ?boolean; + onerror: (ev: Event) => ?boolean; + onfocus: (ev: FocusEvent) => ?boolean; + onhashchange: (ev: Event) => ?boolean; + oninput: (ev: Event) => ?boolean; + oninvalid: (ev: Event) => ?boolean; + onkeydown: (ev: KeyboardEvent) => ?boolean; + onkeypress: (ev: KeyboardEvent) => ?boolean; + onkeyup: (ev: KeyboardEvent) => ?boolean; + onload: (ev: Event) => ?boolean; + onloadeddata: (ev: Event) => ?boolean; + onloadedmetadata: (ev: Event) => ?boolean; + onloadstart: (ev: Event) => ?boolean; + onmessage: (ev: MessageEvent) => ?boolean; + onmousedown: (ev: MouseEvent) => ?boolean; + onmouseenter: (ev: MouseEvent) => ?boolean; + onmouseleave: (ev: MouseEvent) => ?boolean; + onmousemove: (ev: MouseEvent) => ?boolean; + onmouseout: (ev: MouseEvent) => ?boolean; + onmouseover: (ev: MouseEvent) => ?boolean; + onmouseup: (ev: MouseEvent) => ?boolean; + onmousewheel: (ev: WheelEvent) => ?boolean; + onoffline: (ev: Event) => ?boolean; + ononline: (ev: Event) => ?boolean; + onorientationchange: (ev: Event) => ?boolean; + onpagehide: (ev: Event) => ?boolean; + onpageshow: (ev: Event) => ?boolean; + onpause: (ev: Event) => ?boolean; + onplay: (ev: Event) => ?boolean; + onplaying: (ev: Event) => ?boolean; + onpopstate: (ev: Event) => ?boolean; + onprogress: (ev: ProgressEvent) => ?boolean; + onratechange: (ev: Event) => ?boolean; + onreadystatechange: (ev: ProgressEvent) => ?boolean; + onreset: (ev: Event) => ?boolean; + onresize: (ev: UIEvent) => ?boolean; + onscroll: (ev: UIEvent) => ?boolean; + onseeked: (ev: Event) => ?boolean; + onseeking: (ev: Event) => ?boolean; + onselect: (ev: UIEvent) => ?boolean; + onstalled: (ev: Event) => ?boolean; + onstorage: (ev: Event) => ?boolean; + onsubmit: (ev: Event) => ?boolean; + onsuspend: (ev: Event) => ?boolean; + ontimeupdate: (ev: Event) => ?boolean; + ontouchcancel: (ev: TouchEvent) => ?boolean; + ontouchend: (ev: TouchEvent) => ?boolean; + ontouchmove: (ev: TouchEvent) => ?boolean; + ontouchstart: (ev: TouchEvent) => ?boolean; + onunload: (ev: Event) => ?boolean; + onvolumechange: (ev: Event) => ?boolean; + onwaiting: (ev: Event) => ?boolean; + opener: Window; + orientation: string | number; + +outerHeight: number; + +outerWidth: number; + +pageXOffset: number; + +pageYOffset: number; + +parent: Window; + +performance: Performance; + +screen: Screen; + +screenLeft: number; + +screenTop: number; + +screenX: number; + +screenY: number; + +scrollX: number; + +scrollY: number; + +self: Window; + status: string; + +top: Window; + +window: Window; + + Blob: typeof Blob; + HTMLImageElement: typeof HTMLImageElement; + HTMLElement: typeof HTMLElement; + HTMLVideoElement: typeof HTMLVideoElement; + HTMLCanvasElement: typeof HTMLCanvasElement; + Image: typeof Image; + ImageData: typeof ImageData; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + WebGLFramebuffer: typeof WebGLFramebuffer; + WheelEvent: typeof WheelEvent; + Worker: typeof Worker; + XMLHttpRequest: typeof XMLHttpRequest; + Request: typeof Request; + AbortController: typeof AbortController; + + alert(message?: string): void; + blur(): void; + captureEvents(): void; + close(): void; + confirm(message?: string): boolean; + focus(): void; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; + getSelection(): Selection; + moveBy(x?: number, y?: number): void; + moveTo(x?: number, y?: number): void; + msWriteProfilerMark(profilerMarkName: string): void; + open(url?: string, target?: string, features?: string, replace?: boolean): Window; + postMessage(message: mixed, targetOrigin: string, transfer?: ArrayBuffer[]): void; + print(): void; + prompt(message?: string, _default?: string): string | null; + releaseEvents(): void; + resizeBy(x?: number, y?: number): void; + resizeTo(x?: number, y?: number): void; + scroll(x?: number, y?: number): void; + scrollBy(x?: number, y?: number): void; + scrollTo(x?: number, y?: number): void; + stop(): void; + + clearInterval(intervalId?: number): void; + clearTimeout(timeoutId?: number): void; + setTimeout(callback: () => void, ms?: number): number; + setInterval(callback: () => void, ms?: number): number; + + requestAnimationFrame(callback: (timestamp: number) => void): number; + cancelAnimationFrame(handle: number): void; + msRequestAnimationFrame(callback: (timestamp: number) => void): number; + msCancelAnimationFrame(handle: number): void; + webkitRequestAnimationFrame(callback: (timestamp: number) => void): number; + webkitCancelAnimationFrame(handle: number): void; +} diff --git a/node_modules/mapbox-gl/src/ui/anchor.js b/node_modules/mapbox-gl/src/ui/anchor.js new file mode 100644 index 0000000000000000000000000000000000000000..78b2bc2b99fb072ffd64b1461bd3cb7ccb0e64d4 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/anchor.js @@ -0,0 +1,32 @@ +// @flow + +export type Anchor = + | 'center' + | 'top' + | 'bottom' + | 'left' + | 'right' + | 'top-left' + | 'top-right' + | 'bottom-left' + | 'bottom-right'; + +export const anchorTranslate: {[_: Anchor]: string} = { + 'center': 'translate(-50%,-50%)', + 'top': 'translate(-50%,0)', + 'top-left': 'translate(0,0)', + 'top-right': 'translate(-100%,0)', + 'bottom': 'translate(-50%,-100%)', + 'bottom-left': 'translate(0,-100%)', + 'bottom-right': 'translate(-100%,-100%)', + 'left': 'translate(0,-50%)', + 'right': 'translate(-100%,-50%)' +}; + +export function applyAnchorClass(element: HTMLElement, anchor: Anchor, prefix: string) { + const classList = element.classList; + for (const key in anchorTranslate) { + classList.remove(`mapboxgl-${prefix}-anchor-${key}`); + } + classList.add(`mapboxgl-${prefix}-anchor-${anchor}`); +} diff --git a/node_modules/mapbox-gl/src/ui/camera.js b/node_modules/mapbox-gl/src/ui/camera.js new file mode 100644 index 0000000000000000000000000000000000000000..f0a922acb8a623a961385225ab72c143df112703 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/camera.js @@ -0,0 +1,1277 @@ +// @flow + +import { + bindAll, + extend, + warnOnce, + clamp, + wrap, + ease as defaultEasing, + pick +} from '../util/util'; +import {number as interpolate} from '../style-spec/util/interpolate'; +import browser from '../util/browser'; +import LngLat from '../geo/lng_lat'; +import LngLatBounds from '../geo/lng_lat_bounds'; +import Point from '@mapbox/point-geometry'; +import {Event, Evented} from '../util/evented'; +import assert from 'assert'; +import {Debug} from '../util/debug'; + +import type Transform from '../geo/transform'; +import type {LngLatLike} from '../geo/lng_lat'; +import type {LngLatBoundsLike} from '../geo/lng_lat_bounds'; +import type {TaskID} from '../util/task_queue'; +import type {PointLike} from '@mapbox/point-geometry'; +import type {PaddingOptions} from '../geo/edge_insets'; + +/** + * Options common to {@link Map#jumpTo}, {@link Map#easeTo}, and {@link Map#flyTo}, controlling the desired location, + * zoom, bearing, and pitch of the camera. All properties are optional, and when a property is omitted, the current + * camera value for that property will remain unchanged. + * + * @typedef {Object} CameraOptions + * @property {LngLatLike} center The desired center. + * @property {number} zoom The desired zoom level. + * @property {number} bearing The desired bearing in degrees. The bearing is the compass direction that + * is "up". For example, `bearing: 90` orients the map so that east is up. + * @property {number} pitch The desired pitch in degrees. The pitch is the angle towards the horizon + * measured in degrees with a range between 0 and 60 degrees. For example, pitch: 0 provides the appearance + * of looking straight down at the map, while pitch: 60 tilts the user's perspective towards the horizon. + * Increasing the pitch value is often used to display 3D objects. + * @property {LngLatLike} around If `zoom` is specified, `around` determines the point around which the zoom is centered. + * @property {PaddingOptions} padding Dimensions in pixels applied on each side of the viewport for shifting the vanishing point. + * @example + * // set the map's initial perspective with CameraOptions + * var map = new mapboxgl.Map({ + * container: 'map', + * style: 'mapbox://styles/mapbox/streets-v11', + * center: [-73.5804, 45.53483], + * pitch: 60, + * bearing: -60, + * zoom: 10 + * }); + * @see [Set pitch and bearing](https://docs.mapbox.com/mapbox-gl-js/example/set-perspective/) + * @see [Jump to a series of locations](https://docs.mapbox.com/mapbox-gl-js/example/jump-to/) + * @see [Fly to a location](https://docs.mapbox.com/mapbox-gl-js/example/flyto/) + * @see [Display buildings in 3D](https://docs.mapbox.com/mapbox-gl-js/example/3d-buildings/) + */ +export type CameraOptions = { + center?: LngLatLike, + zoom?: number, + bearing?: number, + pitch?: number, + around?: LngLatLike, + padding?: PaddingOptions +}; + +/** + * Options common to map movement methods that involve animation, such as {@link Map#panBy} and + * {@link Map#easeTo}, controlling the duration and easing function of the animation. All properties + * are optional. + * + * @typedef {Object} AnimationOptions + * @property {number} duration The animation's duration, measured in milliseconds. + * @property {Function} easing A function taking a time in the range 0..1 and returning a number where 0 is + * the initial state and 1 is the final state. + * @property {PointLike} offset of the target center relative to real map container center at the end of animation. + * @property {boolean} animate If `false`, no animation will occur. + * @property {boolean} essential If `true`, then the animation is considered essential and will not be affected by + * [`prefers-reduced-motion`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion). + */ +export type AnimationOptions = { + duration?: number, + easing?: (_: number) => number, + offset?: PointLike, + animate?: boolean, + essential?: boolean +}; + +/** + * Options for setting padding on calls to methods such as {@link Map#fitBounds}, {@link Map#fitScreenCoordinates}, and {@link Map#setPadding}. Adjust these options to set the amount of padding in pixels added to the edges of the canvas. Set a uniform padding on all edges or individual values for each edge. All properties of this object must be + * non-negative integers. + * + * @typedef {Object} PaddingOptions + * @property {number} top Padding in pixels from the top of the map canvas. + * @property {number} bottom Padding in pixels from the bottom of the map canvas. + * @property {number} left Padding in pixels from the left of the map canvas. + * @property {number} right Padding in pixels from the right of the map canvas. + * + * @example + * var bbox = [[-79, 43], [-73, 45]]; + * map.fitBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * + * @example + * var bbox = [[-79, 43], [-73, 45]]; + * map.fitBounds(bbox, { + * padding: 20 + * }); + * @see [Fit to the bounds of a LineString](https://docs.mapbox.com/mapbox-gl-js/example/zoomto-linestring/) + * @see [Fit a map to a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/fitbounds/) + */ + +class Camera extends Evented { + transform: Transform; + _moving: boolean; + _zooming: boolean; + _rotating: boolean; + _pitching: boolean; + _padding: boolean; + + _bearingSnap: number; + _easeStart: number; + _easeOptions: {duration: number, easing: (_: number) => number}; + _easeId: string | void; + + _onEaseFrame: (_: number) => void; + _onEaseEnd: (easeId?: string) => void; + _easeFrameId: ?TaskID; + + +_requestRenderFrame: (() => void) => TaskID; + +_cancelRenderFrame: (_: TaskID) => void; + + constructor(transform: Transform, options: {bearingSnap: number}) { + super(); + this._moving = false; + this._zooming = false; + this.transform = transform; + this._bearingSnap = options.bearingSnap; + + bindAll(['_renderFrameCallback'], this); + + //addAssertions(this); + } + + /** + * Returns the map's geographical centerpoint. + * + * @memberof Map# + * @returns The map's geographical centerpoint. + * @example + * // return a LngLat object such as {lng: 0, lat: 0} + * var center = map.getCenter(); + * // access longitude and latitude values directly + * var {longitude, latitude} = map.getCenter(); + * @see Tutorial: [Use Mapbox GL JS in a React app](https://docs.mapbox.com/help/tutorials/use-mapbox-gl-js-with-react/#store-the-new-coordinates) + */ + getCenter(): LngLat { return new LngLat(this.transform.center.lng, this.transform.center.lat); } + + /** + * Sets the map's geographical centerpoint. Equivalent to `jumpTo({center: center})`. + * + * @memberof Map# + * @param center The centerpoint to set. + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + * @example + * map.setCenter([-74, 38]); + */ + setCenter(center: LngLatLike, eventData?: Object) { + return this.jumpTo({center}, eventData); + } + + /** + * Pans the map by the specified offset. + * + * @memberof Map# + * @param offset `x` and `y` coordinates by which to pan the map. + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/) + */ + panBy(offset: PointLike, options?: AnimationOptions, eventData?: Object) { + offset = Point.convert(offset).mult(-1); + return this.panTo(this.transform.center, extend({offset}, options), eventData); + } + + /** + * Pans the map to the specified location with an animated transition. + * + * @memberof Map# + * @param lnglat The location to pan the map to. + * @param options Options describing the destination and animation of the transition. + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + * @example + * map.panTo([-74, 38]); + * @example + * // Specify that the panTo animation should last 5000 milliseconds. + * map.panTo([-74, 38], {duration: 5000}); + * @see [Update a feature in realtime](https://docs.mapbox.com/mapbox-gl-js/example/live-update-feature/) + */ + panTo(lnglat: LngLatLike, options?: AnimationOptions, eventData?: Object) { + return this.easeTo(extend({ + center: lnglat + }, options), eventData); + } + + /** + * Returns the map's current zoom level. + * + * @memberof Map# + * @returns The map's current zoom level. + * @example + * map.getZoom(); + */ + getZoom(): number { return this.transform.zoom; } + + /** + * Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`. + * + * @memberof Map# + * @param zoom The zoom level to set (0-20). + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires zoomstart + * @fires move + * @fires zoom + * @fires moveend + * @fires zoomend + * @returns {Map} `this` + * @example + * // Zoom to the zoom level 5 without an animated transition + * map.setZoom(5); + */ + setZoom(zoom: number, eventData?: Object) { + this.jumpTo({zoom}, eventData); + return this; + } + + /** + * Zooms the map to the specified zoom level, with an animated transition. + * + * @memberof Map# + * @param zoom The zoom level to transition to. + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires zoomstart + * @fires move + * @fires zoom + * @fires moveend + * @fires zoomend + * @returns {Map} `this` + * @example + * // Zoom to the zoom level 5 without an animated transition + * map.zoomTo(5); + * // Zoom to the zoom level 8 with an animated transition + * map.zoomTo(8, { + * duration: 2000, + * offset: [100, 50] + * }); + */ + zoomTo(zoom: number, options: ? AnimationOptions, eventData?: Object) { + return this.easeTo(extend({ + zoom + }, options), eventData); + } + + /** + * Increases the map's zoom level by 1. + * + * @memberof Map# + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires zoomstart + * @fires move + * @fires zoom + * @fires moveend + * @fires zoomend + * @returns {Map} `this` + * @example + * // zoom the map in one level with a custom animation duration + * map.zoomIn({duration: 1000}); + */ + zoomIn(options?: AnimationOptions, eventData?: Object) { + this.zoomTo(this.getZoom() + 1, options, eventData); + return this; + } + + /** + * Decreases the map's zoom level by 1. + * + * @memberof Map# + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires zoomstart + * @fires move + * @fires zoom + * @fires moveend + * @fires zoomend + * @returns {Map} `this` + * @example + * // zoom the map out one level with a custom animation offset + * map.zoomOut({offset: [80, 60]}); + */ + zoomOut(options?: AnimationOptions, eventData?: Object) { + this.zoomTo(this.getZoom() - 1, options, eventData); + return this; + } + + /** + * Returns the map's current bearing. The bearing is the compass direction that is "up"; for example, a bearing + * of 90° orients the map so that east is up. + * + * @memberof Map# + * @returns The map's current bearing. + * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/) + */ + getBearing(): number { return this.transform.bearing; } + + /** + * Sets the map's bearing (rotation). The bearing is the compass direction that is "up"; for example, a bearing + * of 90° orients the map so that east is up. + * + * Equivalent to `jumpTo({bearing: bearing})`. + * + * @memberof Map# + * @param bearing The desired bearing. + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + * @example + * // rotate the map to 90 degrees + * map.setBearing(90); + */ + setBearing(bearing: number, eventData?: Object) { + this.jumpTo({bearing}, eventData); + return this; + } + + /** + * Returns the current padding applied around the map viewport. + * + * @memberof Map# + * @returns The current padding around the map viewport. + */ + getPadding(): PaddingOptions { return this.transform.padding; } + + /** + * Sets the padding in pixels around the viewport. + * + * Equivalent to `jumpTo({padding: padding})`. + * + * @memberof Map# + * @param padding The desired padding. Format: { left: number, right: number, top: number, bottom: number } + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + * @example + * // Sets a left padding of 300px, and a top padding of 50px + * map.setPadding({ left: 300, top: 50 }); + */ + setPadding(padding: PaddingOptions, eventData?: Object) { + this.jumpTo({padding}, eventData); + return this; + } + + /** + * Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction + * that is \"up\"; for example, a bearing of 90° orients the map so that east is up. + * + * @memberof Map# + * @param bearing The desired bearing. + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + */ + rotateTo(bearing: number, options?: AnimationOptions, eventData?: Object) { + return this.easeTo(extend({ + bearing + }, options), eventData); + } + + /** + * Rotates the map so that north is up (0° bearing), with an animated transition. + * + * @memberof Map# + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + */ + resetNorth(options?: AnimationOptions, eventData?: Object) { + this.rotateTo(0, extend({duration: 1000}, options), eventData); + return this; + } + + /** + * Rotates and pitches the map so that north is up (0° bearing) and pitch is 0°, with an animated transition. + * + * @memberof Map# + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + */ + resetNorthPitch(options?: AnimationOptions, eventData?: Object) { + this.easeTo(extend({ + bearing: 0, + pitch: 0, + duration: 1000 + }, options), eventData); + return this; + } + + /** + * Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the + * `bearingSnap` threshold). + * + * @memberof Map# + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + */ + snapToNorth(options?: AnimationOptions, eventData?: Object) { + if (Math.abs(this.getBearing()) < this._bearingSnap) { + return this.resetNorth(options, eventData); + } + return this; + } + + /** + * Returns the map's current pitch (tilt). + * + * @memberof Map# + * @returns The map's current pitch, measured in degrees away from the plane of the screen. + */ + getPitch(): number { return this.transform.pitch; } + + /** + * Sets the map's pitch (tilt). Equivalent to `jumpTo({pitch: pitch})`. + * + * @memberof Map# + * @param pitch The pitch to set, measured in degrees away from the plane of the screen (0-60). + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires pitchstart + * @fires movestart + * @fires moveend + * @returns {Map} `this` + */ + setPitch(pitch: number, eventData?: Object) { + this.jumpTo({pitch}, eventData); + return this; + } + + /** + * @memberof Map# + * @param {LngLatBoundsLike} bounds Calculate the center for these bounds in the viewport and use + * the highest zoom level up to and including `Map#getMaxZoom()` that fits + * in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0. + * @param options Options object + * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds. + * @param {number} [options.bearing=0] Desired map bearing at end of animation, in degrees. + * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels. + * @param {number} [options.maxZoom] The maximum zoom level to allow when the camera would transition to the specified bounds. + * @returns {CameraOptions | void} If map is able to fit to provided bounds, returns `CameraOptions` with + * `center`, `zoom`, and `bearing`. If map is unable to fit, method will warn and return undefined. + * @example + * var bbox = [[-79, 43], [-73, 45]]; + * var newCameraTransform = map.cameraForBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + */ + cameraForBounds(bounds: LngLatBoundsLike, options?: CameraOptions): void | CameraOptions & AnimationOptions { + bounds = LngLatBounds.convert(bounds); + const bearing = options && options.bearing || 0; + return this._cameraForBoxAndBearing(bounds.getNorthWest(), bounds.getSouthEast(), bearing, options); + } + + /** + * Calculate the center of these two points in the viewport and use + * the highest zoom level up to and including `Map#getMaxZoom()` that fits + * the points in the viewport at the specified bearing. + * @memberof Map# + * @param {LngLatLike} p0 First point + * @param {LngLatLike} p1 Second point + * @param bearing Desired map bearing at end of animation, in degrees + * @param options + * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds. + * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels. + * @param {number} [options.maxZoom] The maximum zoom level to allow when the camera would transition to the specified bounds. + * @returns {CameraOptions | void} If map is able to fit to provided bounds, returns `CameraOptions` with + * `center`, `zoom`, and `bearing`. If map is unable to fit, method will warn and return undefined. + * @private + * @example + * var p0 = [-79, 43]; + * var p1 = [-73, 45]; + * var bearing = 90; + * var newCameraTransform = map._cameraForBoxAndBearing(p0, p1, bearing, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + */ + _cameraForBoxAndBearing(p0: LngLatLike, p1: LngLatLike, bearing: number, options?: CameraOptions): void | CameraOptions & AnimationOptions { + const defaultPadding = { + top: 0, + bottom: 0, + right: 0, + left: 0 + }; + options = extend({ + padding: defaultPadding, + offset: [0, 0], + maxZoom: this.transform.maxZoom + }, options); + + if (typeof options.padding === 'number') { + const p = options.padding; + options.padding = { + top: p, + bottom: p, + right: p, + left: p + }; + } + + options.padding = extend(defaultPadding, options.padding); + const tr = this.transform; + const edgePadding = tr.padding; + + // We want to calculate the upper right and lower left of the box defined by p0 and p1 + // in a coordinate system rotate to match the destination bearing. + const p0world = tr.project(LngLat.convert(p0)); + const p1world = tr.project(LngLat.convert(p1)); + const p0rotated = p0world.rotate(-bearing * Math.PI / 180); + const p1rotated = p1world.rotate(-bearing * Math.PI / 180); + + const upperRight = new Point(Math.max(p0rotated.x, p1rotated.x), Math.max(p0rotated.y, p1rotated.y)); + const lowerLeft = new Point(Math.min(p0rotated.x, p1rotated.x), Math.min(p0rotated.y, p1rotated.y)); + + // Calculate zoom: consider the original bbox and padding. + const size = upperRight.sub(lowerLeft); + const scaleX = (tr.width - (edgePadding.left + edgePadding.right + options.padding.left + options.padding.right)) / size.x; + const scaleY = (tr.height - (edgePadding.top + edgePadding.bottom + options.padding.top + options.padding.bottom)) / size.y; + + if (scaleY < 0 || scaleX < 0) { + warnOnce( + 'Map cannot fit within canvas with the given bounds, padding, and/or offset.' + ); + return; + } + + const zoom = Math.min(tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY)), options.maxZoom); + + // Calculate center: apply the zoom, the configured offset, as well as offset that exists as a result of padding. + const offset = (typeof options.offset.x === 'number') ? new Point(options.offset.x, options.offset.y) : Point.convert(options.offset); + const paddingOffsetX = (options.padding.left - options.padding.right) / 2; + const paddingOffsetY = (options.padding.top - options.padding.bottom) / 2; + const paddingOffset = new Point(paddingOffsetX, paddingOffsetY); + const rotatedPaddingOffset = paddingOffset.rotate(bearing * Math.PI / 180); + const offsetAtInitialZoom = offset.add(rotatedPaddingOffset); + const offsetAtFinalZoom = offsetAtInitialZoom.mult(tr.scale / tr.zoomScale(zoom)); + + const center = tr.unproject(p0world.add(p1world).div(2).sub(offsetAtFinalZoom)); + + return { + center, + zoom, + bearing + }; + } + + /** + * Pans and zooms the map to contain its visible area within the specified geographical bounds. + * This function will also reset the map's bearing to 0 if bearing is nonzero. + * + * @memberof Map# + * @param bounds Center these bounds in the viewport and use the highest + * zoom level up to and including `Map#getMaxZoom()` that fits them in the viewport. + * @param {Object} [options] Options supports all properties from {@link AnimationOptions} and {@link CameraOptions} in addition to the fields below. + * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds. + * @param {boolean} [options.linear=false] If `true`, the map transitions using + * {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}. See + * those functions and {@link AnimationOptions} for information about options available. + * @param {Function} [options.easing] An easing function for the animated transition. See {@link AnimationOptions}. + * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels. + * @param {number} [options.maxZoom] The maximum zoom level to allow when the map view transitions to the specified bounds. + * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + * @example + * var bbox = [[-79, 43], [-73, 45]]; + * map.fitBounds(bbox, { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * @see [Fit a map to a bounding box](https://www.mapbox.com/mapbox-gl-js/example/fitbounds/) + */ + fitBounds(bounds: LngLatBoundsLike, options?: AnimationOptions & CameraOptions, eventData?: Object) { + return this._fitInternal( + this.cameraForBounds(bounds, options), + options, + eventData); + } + + /** + * Pans, rotates and zooms the map to to fit the box made by points p0 and p1 + * once the map is rotated to the specified bearing. To zoom without rotating, + * pass in the current map bearing. + * + * @memberof Map# + * @param p0 First point on screen, in pixel coordinates + * @param p1 Second point on screen, in pixel coordinates + * @param bearing Desired map bearing at end of animation, in degrees + * @param options Options object + * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds. + * @param {boolean} [options.linear=false] If `true`, the map transitions using + * {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}. See + * those functions and {@link AnimationOptions} for information about options available. + * @param {Function} [options.easing] An easing function for the animated transition. See {@link AnimationOptions}. + * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels. + * @param {number} [options.maxZoom] The maximum zoom level to allow when the map view transitions to the specified bounds. + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires moveend + * @returns {Map} `this` + * @example + * var p0 = [220, 400]; + * var p1 = [500, 900]; + * map.fitScreenCoordinates(p0, p1, map.getBearing(), { + * padding: {top: 10, bottom:25, left: 15, right: 5} + * }); + * @see Used by {@link BoxZoomHandler} + */ + fitScreenCoordinates(p0: PointLike, p1: PointLike, bearing: number, options?: AnimationOptions & CameraOptions, eventData?: Object) { + return this._fitInternal( + this._cameraForBoxAndBearing( + this.transform.pointLocation(Point.convert(p0)), + this.transform.pointLocation(Point.convert(p1)), + bearing, + options), + options, + eventData); + } + + _fitInternal(calculatedOptions?: CameraOptions & AnimationOptions, options?: AnimationOptions & CameraOptions, eventData?: Object) { + // cameraForBounds warns + returns undefined if unable to fit: + if (!calculatedOptions) return this; + + options = extend(calculatedOptions, options); + // Explictly remove the padding field because, calculatedOptions already accounts for padding by setting zoom and center accordingly. + delete options.padding; + + return options.linear ? + this.easeTo(options, eventData) : + this.flyTo(options, eventData); + } + + /** + * Changes any combination of center, zoom, bearing, and pitch, without + * an animated transition. The map will retain its current values for any + * details not specified in `options`. + * + * @memberof Map# + * @param options Options object + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires zoomstart + * @fires pitchstart + * @fires rotate + * @fires move + * @fires zoom + * @fires pitch + * @fires moveend + * @fires zoomend + * @fires pitchend + * @returns {Map} `this` + * @example + * // jump to coordinates at current zoom + * map.jumpTo({center: [0, 0]}); + * // jump with zoom, pitch, and bearing options + * map.jumpTo({ + * center: [0, 0], + * zoom: 8, + * pitch: 45, + * bearing: 90 + * }); + * @see [Jump to a series of locations](https://docs.mapbox.com/mapbox-gl-js/example/jump-to/) + * @see [Update a feature in realtime](https://docs.mapbox.com/mapbox-gl-js/example/live-update-feature/) + */ + jumpTo(options: CameraOptions, eventData?: Object) { + this.stop(); + + const tr = this.transform; + let zoomChanged = false, + bearingChanged = false, + pitchChanged = false; + + if ('zoom' in options && tr.zoom !== +options.zoom) { + zoomChanged = true; + tr.zoom = +options.zoom; + } + + if (options.center !== undefined) { + tr.center = LngLat.convert(options.center); + } + + if ('bearing' in options && tr.bearing !== +options.bearing) { + bearingChanged = true; + tr.bearing = +options.bearing; + } + + if ('pitch' in options && tr.pitch !== +options.pitch) { + pitchChanged = true; + tr.pitch = +options.pitch; + } + + if (options.padding != null && !tr.isPaddingEqual(options.padding)) { + tr.padding = options.padding; + } + + this.fire(new Event('movestart', eventData)) + .fire(new Event('move', eventData)); + + if (zoomChanged) { + this.fire(new Event('zoomstart', eventData)) + .fire(new Event('zoom', eventData)) + .fire(new Event('zoomend', eventData)); + } + + if (bearingChanged) { + this.fire(new Event('rotatestart', eventData)) + .fire(new Event('rotate', eventData)) + .fire(new Event('rotateend', eventData)); + } + + if (pitchChanged) { + this.fire(new Event('pitchstart', eventData)) + .fire(new Event('pitch', eventData)) + .fire(new Event('pitchend', eventData)); + } + + return this.fire(new Event('moveend', eventData)); + } + + /** + * Changes any combination of `center`, `zoom`, `bearing`, `pitch`, and `padding` with an animated transition + * between old and new values. The map will retain its current values for any + * details not specified in `options`. + * + * Note: The transition will happen instantly if the user has enabled + * the `reduced motion` accesibility feature enabled in their operating system, + * unless `options` includes `essential: true`. + * + * @memberof Map# + * @param options Options describing the destination and animation of the transition. + * Accepts {@link CameraOptions} and {@link AnimationOptions}. + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires zoomstart + * @fires pitchstart + * @fires rotate + * @fires move + * @fires zoom + * @fires pitch + * @fires moveend + * @fires zoomend + * @fires pitchend + * @returns {Map} `this` + * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/) + */ + easeTo(options: CameraOptions & AnimationOptions & {easeId?: string}, eventData?: Object) { + this._stop(false, options.easeId); + + options = extend({ + offset: [0, 0], + duration: 500, + easing: defaultEasing + }, options); + + if (options.animate === false || (!options.essential && browser.prefersReducedMotion)) options.duration = 0; + + const tr = this.transform, + startZoom = this.getZoom(), + startBearing = this.getBearing(), + startPitch = this.getPitch(), + startPadding = this.getPadding(), + + zoom = 'zoom' in options ? +options.zoom : startZoom, + bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing, + pitch = 'pitch' in options ? +options.pitch : startPitch, + padding = 'padding' in options ? options.padding : tr.padding; + + const offsetAsPoint = Point.convert(options.offset); + let pointAtOffset = tr.centerPoint.add(offsetAsPoint); + const locationAtOffset = tr.pointLocation(pointAtOffset); + const center = LngLat.convert(options.center || locationAtOffset); + this._normalizeCenter(center); + + const from = tr.project(locationAtOffset); + const delta = tr.project(center).sub(from); + const finalScale = tr.zoomScale(zoom - startZoom); + + let around, aroundPoint; + + if (options.around) { + around = LngLat.convert(options.around); + aroundPoint = tr.locationPoint(around); + } + + const currently = { + moving: this._moving, + zooming: this._zooming, + rotating: this._rotating, + pitching: this._pitching + }; + + this._zooming = this._zooming || (zoom !== startZoom); + this._rotating = this._rotating || (startBearing !== bearing); + this._pitching = this._pitching || (pitch !== startPitch); + this._padding = !tr.isPaddingEqual(padding); + + this._easeId = options.easeId; + this._prepareEase(eventData, options.noMoveStart, currently); + + this._ease((k) => { + if (this._zooming) { + tr.zoom = interpolate(startZoom, zoom, k); + } + if (this._rotating) { + tr.bearing = interpolate(startBearing, bearing, k); + } + if (this._pitching) { + tr.pitch = interpolate(startPitch, pitch, k); + } + if (this._padding) { + tr.interpolatePadding(startPadding, padding, k); + // When padding is being applied, Transform#centerPoint is changing continously, + // thus we need to recalculate offsetPoint every fra,e + pointAtOffset = tr.centerPoint.add(offsetAsPoint); + } + + if (around) { + tr.setLocationAtPoint(around, aroundPoint); + } else { + const scale = tr.zoomScale(tr.zoom - startZoom); + const base = zoom > startZoom ? + Math.min(2, finalScale) : + Math.max(0.5, finalScale); + const speedup = Math.pow(base, 1 - k); + const newCenter = tr.unproject(from.add(delta.mult(k * speedup)).mult(scale)); + tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset); + } + + this._fireMoveEvents(eventData); + + }, (interruptingEaseId?: string) => { + this._afterEase(eventData, interruptingEaseId); + }, options); + + return this; + } + + _prepareEase(eventData?: Object, noMoveStart: boolean, currently: Object = {}) { + this._moving = true; + + if (!noMoveStart && !currently.moving) { + this.fire(new Event('movestart', eventData)); + } + if (this._zooming && !currently.zooming) { + this.fire(new Event('zoomstart', eventData)); + } + if (this._rotating && !currently.rotating) { + this.fire(new Event('rotatestart', eventData)); + } + if (this._pitching && !currently.pitching) { + this.fire(new Event('pitchstart', eventData)); + } + } + + _fireMoveEvents(eventData?: Object) { + this.fire(new Event('move', eventData)); + if (this._zooming) { + this.fire(new Event('zoom', eventData)); + } + if (this._rotating) { + this.fire(new Event('rotate', eventData)); + } + if (this._pitching) { + this.fire(new Event('pitch', eventData)); + } + } + + _afterEase(eventData?: Object, easeId?: string) { + // if this easing is being stopped to start another easing with + // the same id then don't fire any events to avoid extra start/stop events + if (this._easeId && easeId && this._easeId === easeId) { + return; + } + delete this._easeId; + + const wasZooming = this._zooming; + const wasRotating = this._rotating; + const wasPitching = this._pitching; + this._moving = false; + this._zooming = false; + this._rotating = false; + this._pitching = false; + this._padding = false; + + if (wasZooming) { + this.fire(new Event('zoomend', eventData)); + } + if (wasRotating) { + this.fire(new Event('rotateend', eventData)); + } + if (wasPitching) { + this.fire(new Event('pitchend', eventData)); + } + this.fire(new Event('moveend', eventData)); + } + + /** + * Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that + * evokes flight. The animation seamlessly incorporates zooming and panning to help + * the user maintain her bearings even after traversing a great distance. + * + * Note: The animation will be skipped, and this will behave equivalently to `jumpTo` + * if the user has the `reduced motion` accesibility feature enabled in their operating system, + * unless 'options' includes `essential: true`. + * + * @memberof Map# + * @param {Object} options Options describing the destination and animation of the transition. + * Accepts {@link CameraOptions}, {@link AnimationOptions}, + * and the following additional options. + * @param {number} [options.curve=1.42] The zooming "curve" that will occur along the + * flight path. A high value maximizes zooming for an exaggerated animation, while a low + * value minimizes zooming for an effect closer to {@link Map#easeTo}. 1.42 is the average + * value selected by participants in the user study discussed in + * [van Wijk (2003)](https://www.win.tue.nl/~vanwijk/zoompan.pdf). A value of + * `Math.pow(6, 0.25)` would be equivalent to the root mean squared average velocity. A + * value of 1 would produce a circular motion. + * @param {number} [options.minZoom] The zero-based zoom level at the peak of the flight path. If + * `options.curve` is specified, this option is ignored. + * @param {number} [options.speed=1.2] The average speed of the animation defined in relation to + * `options.curve`. A speed of 1.2 means that the map appears to move along the flight path + * by 1.2 times `options.curve` screenfuls every second. A _screenful_ is the map's visible span. + * It does not correspond to a fixed physical distance, but varies by zoom level. + * @param {number} [options.screenSpeed] The average speed of the animation measured in screenfuls + * per second, assuming a linear timing curve. If `options.speed` is specified, this option is ignored. + * @param {number} [options.maxDuration] The animation's maximum duration, measured in milliseconds. + * If duration exceeds maximum duration, it resets to 0. + * @param eventData Additional properties to be added to event objects of events triggered by this method. + * @fires movestart + * @fires zoomstart + * @fires pitchstart + * @fires move + * @fires zoom + * @fires rotate + * @fires pitch + * @fires moveend + * @fires zoomend + * @fires pitchend + * @returns {Map} `this` + * @example + * // fly with default options to null island + * map.flyTo({center: [0, 0], zoom: 9}); + * // using flyTo options + * map.flyTo({ + * center: [0, 0], + * zoom: 9, + * speed: 0.2, + * curve: 1, + * easing(t) { + * return t; + * } + * }); + * @see [Fly to a location](https://www.mapbox.com/mapbox-gl-js/example/flyto/) + * @see [Slowly fly to a location](https://www.mapbox.com/mapbox-gl-js/example/flyto-options/) + * @see [Fly to a location based on scroll position](https://www.mapbox.com/mapbox-gl-js/example/scroll-fly-to/) + */ + flyTo(options: Object, eventData?: Object) { + // Fall through to jumpTo if user has set prefers-reduced-motion + if (!options.essential && browser.prefersReducedMotion) { + const coercedOptions = (pick(options, ['center', 'zoom', 'bearing', 'pitch', 'around']): CameraOptions); + return this.jumpTo(coercedOptions, eventData); + } + + // This method implements an “optimal path” animation, as detailed in: + // + // Van Wijk, Jarke J.; Nuij, Wim A. A. “Smooth and efficient zooming and panning.” INFOVIS + // ’03. pp. 15–22. . + // + // Where applicable, local variable documentation begins with the associated variable or + // function in van Wijk (2003). + + this.stop(); + + options = extend({ + offset: [0, 0], + speed: 1.2, + curve: 1.42, + easing: defaultEasing + }, options); + + const tr = this.transform, + startZoom = this.getZoom(), + startBearing = this.getBearing(), + startPitch = this.getPitch(), + startPadding = this.getPadding(); + + const zoom = 'zoom' in options ? clamp(+options.zoom, tr.minZoom, tr.maxZoom) : startZoom; + const bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing; + const pitch = 'pitch' in options ? +options.pitch : startPitch; + const padding = 'padding' in options ? options.padding : tr.padding; + + const scale = tr.zoomScale(zoom - startZoom); + const offsetAsPoint = Point.convert(options.offset); + let pointAtOffset = tr.centerPoint.add(offsetAsPoint); + const locationAtOffset = tr.pointLocation(pointAtOffset); + const center = LngLat.convert(options.center || locationAtOffset); + this._normalizeCenter(center); + + const from = tr.project(locationAtOffset); + const delta = tr.project(center).sub(from); + + let rho = options.curve; + + // w₀: Initial visible span, measured in pixels at the initial scale. + const w0 = Math.max(tr.width, tr.height), + // w₁: Final visible span, measured in pixels with respect to the initial scale. + w1 = w0 / scale, + // Length of the flight path as projected onto the ground plane, measured in pixels from + // the world image origin at the initial scale. + u1 = delta.mag(); + + if ('minZoom' in options) { + const minZoom = clamp(Math.min(options.minZoom, startZoom, zoom), tr.minZoom, tr.maxZoom); + // wm: Maximum visible span, measured in pixels with respect to the initial + // scale. + const wMax = w0 / tr.zoomScale(minZoom - startZoom); + rho = Math.sqrt(wMax / u1 * 2); + } + + // ρ² + const rho2 = rho * rho; + + /** + * rᵢ: Returns the zoom-out factor at one end of the animation. + * + * @param i 0 for the ascent or 1 for the descent. + * @private + */ + function r(i) { + const b = (w1 * w1 - w0 * w0 + (i ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (i ? w1 : w0) * rho2 * u1); + return Math.log(Math.sqrt(b * b + 1) - b); + } + + function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; } + function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; } + function tanh(n) { return sinh(n) / cosh(n); } + + // r₀: Zoom-out factor during ascent. + const r0 = r(0); + + // w(s): Returns the visible span on the ground, measured in pixels with respect to the + // initial scale. Assumes an angular field of view of 2 arctan ½ ≈ 53°. + let w: (_: number) => number = function (s) { + return (cosh(r0) / cosh(r0 + rho * s)); + }; + + // u(s): Returns the distance along the flight path as projected onto the ground plane, + // measured in pixels from the world image origin at the initial scale. + let u: (_: number) => number = function (s) { + return w0 * ((cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2) / u1; + }; + + // S: Total length of the flight path, measured in ρ-screenfuls. + let S = (r(1) - r0) / rho; + + // When u₀ = u₁, the optimal path doesn’t require both ascent and descent. + if (Math.abs(u1) < 0.000001 || !isFinite(S)) { + // Perform a more or less instantaneous transition if the path is too short. + if (Math.abs(w0 - w1) < 0.000001) return this.easeTo(options, eventData); + + const k = w1 < w0 ? -1 : 1; + S = Math.abs(Math.log(w1 / w0)) / rho; + + u = function() { return 0; }; + w = function(s) { return Math.exp(k * rho * s); }; + } + + if ('duration' in options) { + options.duration = +options.duration; + } else { + const V = 'screenSpeed' in options ? +options.screenSpeed / rho : +options.speed; + options.duration = 1000 * S / V; + } + + if (options.maxDuration && options.duration > options.maxDuration) { + options.duration = 0; + } + + this._zooming = true; + this._rotating = (startBearing !== bearing); + this._pitching = (pitch !== startPitch); + this._padding = !tr.isPaddingEqual(padding); + + this._prepareEase(eventData, false); + + this._ease((k) => { + // s: The distance traveled along the flight path, measured in ρ-screenfuls. + const s = k * S; + const scale = 1 / w(s); + tr.zoom = k === 1 ? zoom : startZoom + tr.scaleZoom(scale); + + if (this._rotating) { + tr.bearing = interpolate(startBearing, bearing, k); + } + if (this._pitching) { + tr.pitch = interpolate(startPitch, pitch, k); + } + if (this._padding) { + tr.interpolatePadding(startPadding, padding, k); + // When padding is being applied, Transform#centerPoint is changing continously, + // thus we need to recalculate offsetPoint every frame + pointAtOffset = tr.centerPoint.add(offsetAsPoint); + } + + const newCenter = k === 1 ? center : tr.unproject(from.add(delta.mult(u(s))).mult(scale)); + tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset); + + this._fireMoveEvents(eventData); + + }, () => this._afterEase(eventData), options); + + return this; + } + + isEasing() { + return !!this._easeFrameId; + } + + /** + * Stops any animated transition underway. + * + * @memberof Map# + * @returns {Map} `this` + */ + stop(): this { + return this._stop(); + } + + _stop(allowGestures?: boolean, easeId?: string): this { + if (this._easeFrameId) { + this._cancelRenderFrame(this._easeFrameId); + delete this._easeFrameId; + delete this._onEaseFrame; + } + + if (this._onEaseEnd) { + // The _onEaseEnd function might emit events which trigger new + // animation, which sets a new _onEaseEnd. Ensure we don't delete + // it unintentionally. + const onEaseEnd = this._onEaseEnd; + delete this._onEaseEnd; + onEaseEnd.call(this, easeId); + } + if (!allowGestures) { + const handlers = (this: any).handlers; + if (handlers) handlers.stop(false); + } + return this; + } + + _ease(frame: (_: number) => void, + finish: () => void, + options: {animate: boolean, duration: number, easing: (_: number) => number}) { + if (options.animate === false || options.duration === 0) { + frame(1); + finish(); + } else { + this._easeStart = browser.now(); + this._easeOptions = options; + this._onEaseFrame = frame; + this._onEaseEnd = finish; + this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback); + } + } + + // Callback for map._requestRenderFrame + _renderFrameCallback() { + const t = Math.min((browser.now() - this._easeStart) / this._easeOptions.duration, 1); + this._onEaseFrame(this._easeOptions.easing(t)); + if (t < 1) { + this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback); + } else { + this.stop(); + } + } + + // convert bearing so that it's numerically close to the current one so that it interpolates properly + _normalizeBearing(bearing: number, currentBearing: number) { + bearing = wrap(bearing, -180, 180); + const diff = Math.abs(bearing - currentBearing); + if (Math.abs(bearing - 360 - currentBearing) < diff) bearing -= 360; + if (Math.abs(bearing + 360 - currentBearing) < diff) bearing += 360; + return bearing; + } + + // If a path crossing the antimeridian would be shorter, extend the final coordinate so that + // interpolating between the two endpoints will cross it. + _normalizeCenter(center: LngLat) { + const tr = this.transform; + if (!tr.renderWorldCopies || tr.lngRange) return; + + const delta = center.lng - tr.center.lng; + center.lng += + delta > 180 ? -360 : + delta < -180 ? 360 : 0; + } +} + +// In debug builds, check that camera change events are fired in the correct order. +// - ___start events needs to be fired before ___ and ___end events +// - another ___start event can't be fired before a ___end event has been fired for the previous one +function addAssertions(camera: Camera) { //eslint-disable-line + Debug.run(() => { + const inProgress = {}; + + ['drag', 'zoom', 'rotate', 'pitch', 'move'].forEach(name => { + inProgress[name] = false; + + camera.on(`${name}start`, () => { + assert(!inProgress[name], `"${name}start" fired twice without a "${name}end"`); + inProgress[name] = true; + assert(inProgress.move); + }); + + camera.on(name, () => { + assert(inProgress[name]); + assert(inProgress.move); + }); + + camera.on(`${name}end`, () => { + assert(inProgress.move); + assert(inProgress[name]); + inProgress[name] = false; + }); + }); + + // Canary used to test whether this function is stripped in prod build + canary = 'canary debug run'; + }); +} + +let canary; //eslint-disable-line + +export default Camera; diff --git a/node_modules/mapbox-gl/src/ui/control/attribution_control.js b/node_modules/mapbox-gl/src/ui/control/attribution_control.js new file mode 100644 index 0000000000000000000000000000000000000000..21b6a289a718823863e5b5c967bb4fcdc03178a7 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/control/attribution_control.js @@ -0,0 +1,212 @@ +// @flow + +import DOM from '../../util/dom'; +import {bindAll} from '../../util/util'; +import config from '../../util/config'; + +import type Map from '../map'; + +type Options = { + compact?: boolean, + customAttribution?: string | Array +}; + +/** + * An `AttributionControl` control presents the map's [attribution information](https://docs.mapbox.com/help/how-mapbox-works/attribution/). + * + * @implements {IControl} + * @param {Object} [options] + * @param {boolean} [options.compact] If `true`, force a compact attribution that shows the full attribution on mouse hover. If `false`, force the full attribution control. The default is a responsive attribution that collapses when the map is less than 640 pixels wide. **Attribution should not be collapsed if it can comfortably fit on the map. `compact` should only be used to modify default attribution when map size makes it impossible to fit [default attribution](https://docs.mapbox.com/help/how-mapbox-works/attribution/) and when the automatic compact resizing for default settings are not sufficient.** + * @param {string | Array} [options.customAttribution] String or strings to show in addition to any other attributions. + * @example + * var map = new mapboxgl.Map({attributionControl: false}) + * .addControl(new mapboxgl.AttributionControl({ + * compact: true + * })); + */ +class AttributionControl { + options: Options; + _map: Map; + _container: HTMLElement; + _innerContainer: HTMLElement; + _compactButton: HTMLButtonElement; + _editLink: ?HTMLAnchorElement; + _attribHTML: string; + styleId: string; + styleOwner: string; + + constructor(options: Options = {}) { + this.options = options; + + bindAll([ + '_toggleAttribution', + '_updateEditLink', + '_updateData', + '_updateCompact' + ], this); + } + + getDefaultPosition() { + return 'bottom-right'; + } + + onAdd(map: Map) { + const compact = this.options && this.options.compact; + + this._map = map; + this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-attrib'); + this._compactButton = DOM.create('button', 'mapboxgl-ctrl-attrib-button', this._container); + this._compactButton.addEventListener('click', this._toggleAttribution); + this._setElementTitle(this._compactButton, 'ToggleAttribution'); + this._innerContainer = DOM.create('div', 'mapboxgl-ctrl-attrib-inner', this._container); + this._innerContainer.setAttribute('role', 'list'); + + if (compact) { + this._container.classList.add('mapboxgl-compact'); + } + + this._updateAttributions(); + this._updateEditLink(); + + this._map.on('styledata', this._updateData); + this._map.on('sourcedata', this._updateData); + this._map.on('moveend', this._updateEditLink); + + if (compact === undefined) { + this._map.on('resize', this._updateCompact); + this._updateCompact(); + } + + return this._container; + } + + onRemove() { + DOM.remove(this._container); + + this._map.off('styledata', this._updateData); + this._map.off('sourcedata', this._updateData); + this._map.off('moveend', this._updateEditLink); + this._map.off('resize', this._updateCompact); + + this._map = (undefined: any); + this._attribHTML = (undefined: any); + } + + _setElementTitle(element: HTMLElement, title: string) { + const str = this._map._getUIString(`AttributionControl.${title}`); + element.title = str; + element.setAttribute('aria-label', str); + } + + _toggleAttribution() { + if (this._container.classList.contains('mapboxgl-compact-show')) { + this._container.classList.remove('mapboxgl-compact-show'); + this._compactButton.setAttribute('aria-pressed', 'false'); + } else { + this._container.classList.add('mapboxgl-compact-show'); + this._compactButton.setAttribute('aria-pressed', 'true'); + } + } + + _updateEditLink() { + let editLink = this._editLink; + if (!editLink) { + editLink = this._editLink = (this._container.querySelector('.mapbox-improve-map'): any); + } + + const params = [ + {key: 'owner', value: this.styleOwner}, + {key: 'id', value: this.styleId}, + {key: 'access_token', value: this._map._requestManager._customAccessToken || config.ACCESS_TOKEN} + ]; + + if (editLink) { + const paramString = params.reduce((acc, next, i) => { + if (next.value) { + acc += `${next.key}=${next.value}${i < params.length - 1 ? '&' : ''}`; + } + return acc; + }, `?`); + editLink.href = `${config.FEEDBACK_URL}/${paramString}${this._map._hash ? this._map._hash.getHashString(true) : ''}`; + editLink.rel = 'noopener nofollow'; + this._setElementTitle(editLink, 'MapFeedback'); + } + } + + _updateData(e: any) { + if (e && (e.sourceDataType === 'metadata' || e.sourceDataType === 'visibility' || e.dataType === 'style')) { + this._updateAttributions(); + this._updateEditLink(); + } + } + + _updateAttributions() { + if (!this._map.style) return; + let attributions: Array = []; + if (this.options.customAttribution) { + if (Array.isArray(this.options.customAttribution)) { + attributions = attributions.concat( + this.options.customAttribution.map(attribution => { + if (typeof attribution !== 'string') return ''; + return attribution; + }) + ); + } else if (typeof this.options.customAttribution === 'string') { + attributions.push(this.options.customAttribution); + } + } + + if (this._map.style.stylesheet) { + const stylesheet: any = this._map.style.stylesheet; + this.styleOwner = stylesheet.owner; + this.styleId = stylesheet.id; + } + + const sourceCaches = this._map.style.sourceCaches; + for (const id in sourceCaches) { + const sourceCache = sourceCaches[id]; + if (sourceCache.used) { + const source = sourceCache.getSource(); + if (source.attribution && attributions.indexOf(source.attribution) < 0) { + attributions.push(source.attribution); + } + } + } + + // remove any entries that are substrings of another entry. + // first sort by length so that substrings come first + attributions.sort((a, b) => a.length - b.length); + attributions = attributions.filter((attrib, i) => { + for (let j = i + 1; j < attributions.length; j++) { + if (attributions[j].indexOf(attrib) >= 0) { return false; } + } + return true; + }); + + // check if attribution string is different to minimize DOM changes + const attribHTML = attributions.join(' | '); + if (attribHTML === this._attribHTML) return; + + this._attribHTML = attribHTML; + + if (attributions.length) { + this._innerContainer.innerHTML = attribHTML; + this._container.classList.remove('mapboxgl-attrib-empty'); + } else { + this._container.classList.add('mapboxgl-attrib-empty'); + } + // remove old DOM node from _editLink + this._editLink = null; + } + + _updateCompact() { + if (this._map.getCanvasContainer().offsetWidth <= 640) { + this._container.classList.add('mapboxgl-compact'); + } else { + this._container.classList.remove('mapboxgl-compact', 'mapboxgl-compact-show'); + } + } + +} + +export default AttributionControl; diff --git a/node_modules/mapbox-gl/src/ui/control/fullscreen_control.js b/node_modules/mapbox-gl/src/ui/control/fullscreen_control.js new file mode 100644 index 0000000000000000000000000000000000000000..e7006d5d871653e2f42e9c09e7acf143675d738d --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/control/fullscreen_control.js @@ -0,0 +1,147 @@ +// @flow + +import DOM from '../../util/dom'; + +import {bindAll, warnOnce} from '../../util/util'; +import window from '../../util/window'; + +import type Map from '../map'; + +type Options = { + container?: HTMLElement +}; + +/** + * A `FullscreenControl` control contains a button for toggling the map in and out of fullscreen mode. + * + * @implements {IControl} + * @param {Object} [options] + * @param {HTMLElement} [options.container] `container` is the [compatible DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullScreen#Compatible_elements) which should be made full screen. By default, the map container element will be made full screen. + * + * @example + * map.addControl(new mapboxgl.FullscreenControl({container: document.querySelector('body')})); + * @see [View a fullscreen map](https://www.mapbox.com/mapbox-gl-js/example/fullscreen/) + */ + +class FullscreenControl { + _map: Map; + _controlContainer: HTMLElement; + _fullscreen: boolean; + _fullscreenchange: string; + _fullscreenButton: HTMLElement; + _container: HTMLElement; + + constructor(options: Options) { + this._fullscreen = false; + if (options && options.container) { + if (options.container instanceof window.HTMLElement) { + this._container = options.container; + } else { + warnOnce('Full screen control \'container\' must be a DOM element.'); + } + } + bindAll([ + '_onClickFullscreen', + '_changeIcon' + ], this); + if ('onfullscreenchange' in window.document) { + this._fullscreenchange = 'fullscreenchange'; + } else if ('onmozfullscreenchange' in window.document) { + this._fullscreenchange = 'mozfullscreenchange'; + } else if ('onwebkitfullscreenchange' in window.document) { + this._fullscreenchange = 'webkitfullscreenchange'; + } else if ('onmsfullscreenchange' in window.document) { + this._fullscreenchange = 'MSFullscreenChange'; + } + } + + onAdd(map: Map) { + this._map = map; + if (!this._container) this._container = this._map.getContainer(); + this._controlContainer = DOM.create('div', `mapboxgl-ctrl mapboxgl-ctrl-group`); + if (this._checkFullscreenSupport()) { + this._setupUI(); + } else { + this._controlContainer.style.display = 'none'; + warnOnce('This device does not support fullscreen mode.'); + } + return this._controlContainer; + } + + onRemove() { + DOM.remove(this._controlContainer); + this._map = (null: any); + window.document.removeEventListener(this._fullscreenchange, this._changeIcon); + } + + _checkFullscreenSupport() { + return !!( + window.document.fullscreenEnabled || + (window.document: any).mozFullScreenEnabled || + (window.document: any).msFullscreenEnabled || + (window.document: any).webkitFullscreenEnabled + ); + } + + _setupUI() { + const button = this._fullscreenButton = DOM.create('button', (`mapboxgl-ctrl-fullscreen`), this._controlContainer); + DOM.create('span', `mapboxgl-ctrl-icon`, button).setAttribute('aria-hidden', true); + button.type = 'button'; + this._updateTitle(); + this._fullscreenButton.addEventListener('click', this._onClickFullscreen); + window.document.addEventListener(this._fullscreenchange, this._changeIcon); + } + + _updateTitle() { + const title = this._getTitle(); + this._fullscreenButton.setAttribute("aria-label", title); + this._fullscreenButton.title = title; + } + + _getTitle() { + return this._map._getUIString(this._isFullscreen() ? 'FullscreenControl.Exit' : 'FullscreenControl.Enter'); + } + + _isFullscreen() { + return this._fullscreen; + } + + _changeIcon() { + const fullscreenElement = + window.document.fullscreenElement || + (window.document: any).mozFullScreenElement || + (window.document: any).webkitFullscreenElement || + (window.document: any).msFullscreenElement; + + if ((fullscreenElement === this._container) !== this._fullscreen) { + this._fullscreen = !this._fullscreen; + this._fullscreenButton.classList.toggle(`mapboxgl-ctrl-shrink`); + this._fullscreenButton.classList.toggle(`mapboxgl-ctrl-fullscreen`); + this._updateTitle(); + } + } + + _onClickFullscreen() { + if (this._isFullscreen()) { + if (window.document.exitFullscreen) { + (window.document: any).exitFullscreen(); + } else if (window.document.mozCancelFullScreen) { + (window.document: any).mozCancelFullScreen(); + } else if (window.document.msExitFullscreen) { + (window.document: any).msExitFullscreen(); + } else if (window.document.webkitCancelFullScreen) { + (window.document: any).webkitCancelFullScreen(); + } + } else if (this._container.requestFullscreen) { + this._container.requestFullscreen(); + } else if ((this._container: any).mozRequestFullScreen) { + (this._container: any).mozRequestFullScreen(); + } else if ((this._container: any).msRequestFullscreen) { + (this._container: any).msRequestFullscreen(); + } else if ((this._container: any).webkitRequestFullscreen) { + (this._container: any).webkitRequestFullscreen(); + } + } +} + +export default FullscreenControl; diff --git a/node_modules/mapbox-gl/src/ui/control/geolocate_control.js b/node_modules/mapbox-gl/src/ui/control/geolocate_control.js new file mode 100644 index 0000000000000000000000000000000000000000..fd30719c1b822dd100f3c0e966596ac3e1a64693 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/control/geolocate_control.js @@ -0,0 +1,707 @@ +// @flow + +import {Event, Evented} from '../../util/evented'; +import DOM from '../../util/dom'; +import window from '../../util/window'; +import {extend, bindAll, warnOnce} from '../../util/util'; +import assert from 'assert'; +import LngLat from '../../geo/lng_lat'; +import Marker from '../marker'; + +import type Map from '../map'; +import type {AnimationOptions, CameraOptions} from '../camera'; + +type Options = { + positionOptions?: PositionOptions, + fitBoundsOptions?: AnimationOptions & CameraOptions, + trackUserLocation?: boolean, + showAccuracyCircle?: boolean, + showUserLocation?: boolean +}; + +const defaultOptions: Options = { + positionOptions: { + enableHighAccuracy: false, + maximumAge: 0, + timeout: 6000 /* 6 sec */ + }, + fitBoundsOptions: { + maxZoom: 15 + }, + trackUserLocation: false, + showAccuracyCircle: true, + showUserLocation: true +}; + +let supportsGeolocation; + +function checkGeolocationSupport(callback) { + if (supportsGeolocation !== undefined) { + callback(supportsGeolocation); + + } else if (window.navigator.permissions !== undefined) { + // navigator.permissions has incomplete browser support + // http://caniuse.com/#feat=permissions-api + // Test for the case where a browser disables Geolocation because of an + // insecure origin + window.navigator.permissions.query({name: 'geolocation'}).then((p) => { + supportsGeolocation = p.state !== 'denied'; + callback(supportsGeolocation); + }); + + } else { + supportsGeolocation = !!window.navigator.geolocation; + callback(supportsGeolocation); + } +} + +let numberOfWatches = 0; +let noTimeout = false; + +/** + * A `GeolocateControl` control provides a button that uses the browser's geolocation + * API to locate the user on the map. + * + * Not all browsers support geolocation, + * and some users may disable the feature. Geolocation support for modern + * browsers including Chrome requires sites to be served over HTTPS. If + * geolocation support is not available, the GeolocateControl will show + * as disabled. + * + * The zoom level applied will depend on the accuracy of the geolocation provided by the device. + * + * The GeolocateControl has two modes. If `trackUserLocation` is `false` (default) the control acts as a button, which when pressed will set the map's camera to target the user location. If the user moves, the map won't update. This is most suited for the desktop. If `trackUserLocation` is `true` the control acts as a toggle button that when active the user's location is actively monitored for changes. In this mode the GeolocateControl has three interaction states: + * * active - the map's camera automatically updates as the user's location changes, keeping the location dot in the center. Initial state and upon clicking the `GeolocateControl` button. + * * passive - the user's location dot automatically updates, but the map's camera does not. Occurs upon the user initiating a map movement. + * * disabled - occurs if Geolocation is not available, disabled or denied. + * + * These interaction states can't be controlled programmatically, rather they are set based on user interactions. + * + * @implements {IControl} + * @param {Object} [options] + * @param {Object} [options.positionOptions={enableHighAccuracy: false, timeout: 6000}] A Geolocation API [PositionOptions](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) object. + * @param {Object} [options.fitBoundsOptions={maxZoom: 15}] A {@link Map#fitBounds} options object to use when the map is panned and zoomed to the user's location. The default is to use a `maxZoom` of 15 to limit how far the map will zoom in for very accurate locations. + * @param {Object} [options.trackUserLocation=false] If `true` the Geolocate Control becomes a toggle button and when active the map will receive updates to the user's location as it changes. + * @param {Object} [options.showAccuracyCircle=true] By default, if showUserLocation is `true`, a transparent circle will be drawn around the user location indicating the accuracy (95% confidence level) of the user's location. Set to `false` to disable. Always disabled when showUserLocation is `false`. + * @param {Object} [options.showUserLocation=true] By default a dot will be shown on the map at the user's location. Set to `false` to disable. + * + * @example + * map.addControl(new mapboxgl.GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * })); + * @see [Locate the user](https://www.mapbox.com/mapbox-gl-js/example/locate-user/) + */ +class GeolocateControl extends Evented { + _map: Map; + options: Options; + _container: HTMLElement; + _dotElement: HTMLElement; + _circleElement: HTMLElement; + _geolocateButton: HTMLButtonElement; + _geolocationWatchID: number; + _timeoutId: ?TimeoutID; + _watchState: 'OFF' | 'ACTIVE_LOCK' | 'WAITING_ACTIVE' | 'ACTIVE_ERROR' | 'BACKGROUND' | 'BACKGROUND_ERROR'; + _lastKnownPosition: any; + _userLocationDotMarker: Marker; + _accuracyCircleMarker: Marker; + _accuracy: number; + _setup: boolean; // set to true once the control has been setup + + constructor(options: Options) { + super(); + this.options = extend({}, defaultOptions, options); + + bindAll([ + '_onSuccess', + '_onError', + '_onZoom', + '_finish', + '_setupUI', + '_updateCamera', + '_updateMarker' + ], this); + } + + onAdd(map: Map) { + this._map = map; + this._container = DOM.create('div', `mapboxgl-ctrl mapboxgl-ctrl-group`); + checkGeolocationSupport(this._setupUI); + return this._container; + } + + onRemove() { + // clear the geolocation watch if exists + if (this._geolocationWatchID !== undefined) { + window.navigator.geolocation.clearWatch(this._geolocationWatchID); + this._geolocationWatchID = (undefined: any); + } + + // clear the markers from the map + if (this.options.showUserLocation && this._userLocationDotMarker) { + this._userLocationDotMarker.remove(); + } + if (this.options.showAccuracyCircle && this._accuracyCircleMarker) { + this._accuracyCircleMarker.remove(); + } + + DOM.remove(this._container); + this._map.off('zoom', this._onZoom); + this._map = (undefined: any); + numberOfWatches = 0; + noTimeout = false; + } + + /** + * Check if the Geolocation API Position is outside the map's maxbounds. + * + * @param {Position} position the Geolocation API Position + * @returns {boolean} Returns `true` if position is outside the map's maxbounds, otherwise returns `false`. + * @private + */ + _isOutOfMapMaxBounds(position: Position) { + const bounds = this._map.getMaxBounds(); + const coordinates = position.coords; + + return bounds && ( + coordinates.longitude < bounds.getWest() || + coordinates.longitude > bounds.getEast() || + coordinates.latitude < bounds.getSouth() || + coordinates.latitude > bounds.getNorth() + ); + } + + _setErrorState() { + switch (this._watchState) { + case 'WAITING_ACTIVE': + this._watchState = 'ACTIVE_ERROR'; + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active'); + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error'); + break; + case 'ACTIVE_LOCK': + this._watchState = 'ACTIVE_ERROR'; + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active'); + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting'); + // turn marker grey + break; + case 'BACKGROUND': + this._watchState = 'BACKGROUND_ERROR'; + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background'); + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background-error'); + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting'); + // turn marker grey + break; + case 'ACTIVE_ERROR': + break; + default: + assert(false, `Unexpected watchState ${this._watchState}`); + } + } + + /** + * When the Geolocation API returns a new location, update the GeolocateControl. + * + * @param {Position} position the Geolocation API Position + * @private + */ + _onSuccess(position: Position) { + if (!this._map) { + // control has since been removed + return; + } + + if (this._isOutOfMapMaxBounds(position)) { + this._setErrorState(); + + this.fire(new Event('outofmaxbounds', position)); + this._updateMarker(); + this._finish(); + + return; + } + + if (this.options.trackUserLocation) { + // keep a record of the position so that if the state is BACKGROUND and the user + // clicks the button, we can move to ACTIVE_LOCK immediately without waiting for + // watchPosition to trigger _onSuccess + this._lastKnownPosition = position; + + switch (this._watchState) { + case 'WAITING_ACTIVE': + case 'ACTIVE_LOCK': + case 'ACTIVE_ERROR': + this._watchState = 'ACTIVE_LOCK'; + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active'); + break; + case 'BACKGROUND': + case 'BACKGROUND_ERROR': + this._watchState = 'BACKGROUND'; + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error'); + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background'); + break; + default: + assert(false, `Unexpected watchState ${this._watchState}`); + } + } + + // if showUserLocation and the watch state isn't off then update the marker location + if (this.options.showUserLocation && this._watchState !== 'OFF') { + this._updateMarker(position); + } + + // if in normal mode (not watch mode), or if in watch mode and the state is active watch + // then update the camera + if (!this.options.trackUserLocation || this._watchState === 'ACTIVE_LOCK') { + this._updateCamera(position); + } + + if (this.options.showUserLocation) { + this._dotElement.classList.remove('mapboxgl-user-location-dot-stale'); + } + + this.fire(new Event('geolocate', position)); + this._finish(); + } + + /** + * Update the camera location to center on the current position + * + * @param {Position} position the Geolocation API Position + * @private + */ + _updateCamera(position: Position) { + const center = new LngLat(position.coords.longitude, position.coords.latitude); + const radius = position.coords.accuracy; + const bearing = this._map.getBearing(); + const options = extend({bearing}, this.options.fitBoundsOptions); + + this._map.fitBounds(center.toBounds(radius), options, { + geolocateSource: true // tag this camera change so it won't cause the control to change to background state + }); + } + + /** + * Update the user location dot Marker to the current position + * + * @param {Position} [position] the Geolocation API Position + * @private + */ + _updateMarker(position: ?Position) { + if (position) { + const center = new LngLat(position.coords.longitude, position.coords.latitude); + this._accuracyCircleMarker.setLngLat(center).addTo(this._map); + this._userLocationDotMarker.setLngLat(center).addTo(this._map); + this._accuracy = position.coords.accuracy; + if (this.options.showUserLocation && this.options.showAccuracyCircle) { + this._updateCircleRadius(); + } + } else { + this._userLocationDotMarker.remove(); + this._accuracyCircleMarker.remove(); + } + } + + _updateCircleRadius() { + assert(this._circleElement); + const y = this._map._container.clientHeight / 2; + const a = this._map.unproject([0, y]); + const b = this._map.unproject([1, y]); + const metersPerPixel = a.distanceTo(b); + const circleDiameter = Math.ceil(2.0 * this._accuracy / metersPerPixel); + this._circleElement.style.width = `${circleDiameter}px`; + this._circleElement.style.height = `${circleDiameter}px`; + } + + _onZoom() { + if (this.options.showUserLocation && this.options.showAccuracyCircle) { + this._updateCircleRadius(); + } + } + + _onError(error: PositionError) { + if (!this._map) { + // control has since been removed + return; + } + + if (this.options.trackUserLocation) { + if (error.code === 1) { + // PERMISSION_DENIED + this._watchState = 'OFF'; + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active'); + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background'); + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error'); + this._geolocateButton.disabled = true; + const title = this._map._getUIString('GeolocateControl.LocationNotAvailable'); + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + + if (this._geolocationWatchID !== undefined) { + this._clearWatch(); + } + } else if (error.code === 3 && noTimeout) { + // this represents a forced error state + // this was triggered to force immediate geolocation when a watch is already present + // see https://github.com/mapbox/mapbox-gl-js/issues/8214 + // and https://w3c.github.io/geolocation-api/#example-5-forcing-the-user-agent-to-return-a-fresh-cached-position + return; + } else { + this._setErrorState(); + } + } + + if (this._watchState !== 'OFF' && this.options.showUserLocation) { + this._dotElement.classList.add('mapboxgl-user-location-dot-stale'); + } + + this.fire(new Event('error', error)); + + this._finish(); + } + + _finish() { + if (this._timeoutId) { clearTimeout(this._timeoutId); } + this._timeoutId = undefined; + } + + _setupUI(supported: boolean) { + this._container.addEventListener('contextmenu', (e: MouseEvent) => e.preventDefault()); + this._geolocateButton = DOM.create('button', `mapboxgl-ctrl-geolocate`, this._container); + DOM.create('span', `mapboxgl-ctrl-icon`, this._geolocateButton).setAttribute('aria-hidden', true); + this._geolocateButton.type = 'button'; + + if (supported === false) { + warnOnce('Geolocation support is not available so the GeolocateControl will be disabled.'); + const title = this._map._getUIString('GeolocateControl.LocationNotAvailable'); + this._geolocateButton.disabled = true; + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + } else { + const title = this._map._getUIString('GeolocateControl.FindMyLocation'); + this._geolocateButton.title = title; + this._geolocateButton.setAttribute('aria-label', title); + } + + if (this.options.trackUserLocation) { + this._geolocateButton.setAttribute('aria-pressed', 'false'); + this._watchState = 'OFF'; + } + + // when showUserLocation is enabled, keep the Geolocate button disabled until the device location marker is setup on the map + if (this.options.showUserLocation) { + this._dotElement = DOM.create('div', 'mapboxgl-user-location-dot'); + + this._userLocationDotMarker = new Marker(this._dotElement); + + this._circleElement = DOM.create('div', 'mapboxgl-user-location-accuracy-circle'); + this._accuracyCircleMarker = new Marker({element: this._circleElement, pitchAlignment: 'map'}); + + if (this.options.trackUserLocation) this._watchState = 'OFF'; + + this._map.on('zoom', this._onZoom); + } + + this._geolocateButton.addEventListener('click', + this.trigger.bind(this)); + + this._setup = true; + + // when the camera is changed (and it's not as a result of the Geolocation Control) change + // the watch mode to background watch, so that the marker is updated but not the camera. + if (this.options.trackUserLocation) { + this._map.on('movestart', (event) => { + const fromResize = event.originalEvent && event.originalEvent.type === 'resize'; + if (!event.geolocateSource && this._watchState === 'ACTIVE_LOCK' && !fromResize) { + this._watchState = 'BACKGROUND'; + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background'); + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active'); + + this.fire(new Event('trackuserlocationend')); + } + }); + } + } + + /** + * Programmatically request and move the map to the user's location. + * + * @returns {boolean} Returns `false` if called before control was added to a map, otherwise returns `true`. + * @example + * // Initialize the geolocate control. + * var geolocate = new mapboxgl.GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * map.on('load', function() { + * geolocate.trigger(); + * }); + */ + trigger() { + if (!this._setup) { + warnOnce('Geolocate control triggered before added to a map'); + return false; + } + if (this.options.trackUserLocation) { + // update watchState and do any outgoing state cleanup + switch (this._watchState) { + case 'OFF': + // turn on the Geolocate Control + this._watchState = 'WAITING_ACTIVE'; + + this.fire(new Event('trackuserlocationstart')); + break; + case 'WAITING_ACTIVE': + case 'ACTIVE_LOCK': + case 'ACTIVE_ERROR': + case 'BACKGROUND_ERROR': + // turn off the Geolocate Control + numberOfWatches--; + noTimeout = false; + this._watchState = 'OFF'; + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active'); + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error'); + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background'); + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error'); + + this.fire(new Event('trackuserlocationend')); + break; + case 'BACKGROUND': + this._watchState = 'ACTIVE_LOCK'; + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background'); + // set camera to last known location + if (this._lastKnownPosition) this._updateCamera(this._lastKnownPosition); + + this.fire(new Event('trackuserlocationstart')); + break; + default: + assert(false, `Unexpected watchState ${this._watchState}`); + } + + // incoming state setup + switch (this._watchState) { + case 'WAITING_ACTIVE': + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active'); + break; + case 'ACTIVE_LOCK': + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active'); + break; + case 'ACTIVE_ERROR': + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error'); + break; + case 'BACKGROUND': + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background'); + break; + case 'BACKGROUND_ERROR': + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting'); + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background-error'); + break; + case 'OFF': + break; + default: + assert(false, `Unexpected watchState ${this._watchState}`); + } + + // manage geolocation.watchPosition / geolocation.clearWatch + if (this._watchState === 'OFF' && this._geolocationWatchID !== undefined) { + // clear watchPosition as we've changed to an OFF state + this._clearWatch(); + } else if (this._geolocationWatchID === undefined) { + // enable watchPosition since watchState is not OFF and there is no watchPosition already running + + this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting'); + this._geolocateButton.setAttribute('aria-pressed', 'true'); + + numberOfWatches++; + let positionOptions; + if (numberOfWatches > 1) { + positionOptions = {maximumAge:600000, timeout:0}; + noTimeout = true; + } else { + positionOptions = this.options.positionOptions; + noTimeout = false; + } + + this._geolocationWatchID = window.navigator.geolocation.watchPosition( + this._onSuccess, this._onError, positionOptions); + } + } else { + window.navigator.geolocation.getCurrentPosition( + this._onSuccess, this._onError, this.options.positionOptions); + + // This timeout ensures that we still call finish() even if + // the user declines to share their location in Firefox + this._timeoutId = setTimeout(this._finish, 10000 /* 10sec */); + } + + return true; + } + + _clearWatch() { + window.navigator.geolocation.clearWatch(this._geolocationWatchID); + + this._geolocationWatchID = (undefined: any); + this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting'); + this._geolocateButton.setAttribute('aria-pressed', 'false'); + + if (this.options.showUserLocation) { + this._updateMarker(null); + } + } +} + +export default GeolocateControl; + +/* Geolocate Control Watch States + * This is the private state of the control. + * + * OFF + * off/inactive + * WAITING_ACTIVE + * Geolocate Control was clicked but still waiting for Geolocation API response with user location + * ACTIVE_LOCK + * Showing the user location as a dot AND tracking the camera to be fixed to their location. If their location changes the map moves to follow. + * ACTIVE_ERROR + * There was en error from the Geolocation API while trying to show and track the user location. + * BACKGROUND + * Showing the user location as a dot but the camera doesn't follow their location as it changes. + * BACKGROUND_ERROR + * There was an error from the Geolocation API while trying to show (but not track) the user location. + */ + +/** + * Fired on each Geolocation API position update which returned as success. + * + * @event geolocate + * @memberof GeolocateControl + * @instance + * @property {Position} data The returned [Position](https://developer.mozilla.org/en-US/docs/Web/API/Position) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition). + * @example + * // Initialize the geolocate control. + * var geolocate = new mapboxgl.GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a geolocate event occurs. + * geolocate.on('geolocate', function() { + * console.log('A geolocate event has occurred.') + * }); + * + */ + +/** + * Fired on each Geolocation API position update which returned as an error. + * + * @event error + * @memberof GeolocateControl + * @instance + * @property {PositionError} data The returned [PositionError](https://developer.mozilla.org/en-US/docs/Web/API/PositionError) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition). + * @example + * // Initialize the geolocate control. + * var geolocate = new mapboxgl.GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an error event occurs. + * geolocate.on('error', function() { + * console.log('An error event has occurred.') + * }); + * + */ + +/** + * Fired on each Geolocation API position update which returned as success but user position is out of map maxBounds. + * + * @event outofmaxbounds + * @memberof GeolocateControl + * @instance + * @property {Position} data The returned [Position](https://developer.mozilla.org/en-US/docs/Web/API/Position) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition). + * @example + * // Initialize the geolocate control. + * var geolocate = new mapboxgl.GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when an outofmaxbounds event occurs. + * geolocate.on('outofmaxbounds', function() { + * console.log('An outofmaxbounds event has occurred.') + * }); + * + */ + +/** + * Fired when the Geolocate Control changes to the active lock state, which happens either upon first obtaining a successful Geolocation API position for the user (a geolocate event will follow), or the user clicks the geolocate button when in the background state which uses the last known position to recenter the map and enter active lock state (no geolocate event will follow unless the users's location changes). + * + * @event trackuserlocationstart + * @memberof GeolocateControl + * @instance + * @example + * // Initialize the geolocate control. + * var geolocate = new mapboxgl.GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a trackuserlocationstart event occurs. + * geolocate.on('trackuserlocationstart', function() { + * console.log('A trackuserlocationstart event has occurred.') + * }); + * + */ + +/** + * Fired when the Geolocate Control changes to the background state, which happens when a user changes the camera during an active position lock. This only applies when trackUserLocation is true. In the background state, the dot on the map will update with location updates but the camera will not. + * + * @event trackuserlocationend + * @memberof GeolocateControl + * @instance + * @example + * // Initialize the geolocate control. + * var geolocate = new mapboxgl.GeolocateControl({ + * positionOptions: { + * enableHighAccuracy: true + * }, + * trackUserLocation: true + * }); + * // Add the control to the map. + * map.addControl(geolocate); + * // Set an event listener that fires + * // when a trackuserlocationend event occurs. + * geolocate.on('trackuserlocationend', function() { + * console.log('A trackuserlocationend event has occurred.') + * }); + * + */ diff --git a/node_modules/mapbox-gl/src/ui/control/logo_control.js b/node_modules/mapbox-gl/src/ui/control/logo_control.js new file mode 100644 index 0000000000000000000000000000000000000000..a56fdb912a12d83cfb4e8d5142af44cae0872f81 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/control/logo_control.js @@ -0,0 +1,92 @@ +// @flow + +import DOM from '../../util/dom'; + +import {bindAll} from '../../util/util'; + +import type Map from '../map'; + +/** + * A `LogoControl` is a control that adds the Mapbox watermark + * to the map as required by the [terms of service](https://www.mapbox.com/tos/) for Mapbox + * vector tiles and core styles. + * + * @implements {IControl} + * @private +**/ + +class LogoControl { + _map: Map; + _container: HTMLElement; + + constructor() { + bindAll(['_updateLogo'], this); + bindAll(['_updateCompact'], this); + } + + onAdd(map: Map) { + this._map = map; + this._container = DOM.create('div', 'mapboxgl-ctrl'); + const anchor = DOM.create('a', 'mapboxgl-ctrl-logo'); + anchor.target = "_blank"; + anchor.rel = "noopener nofollow"; + anchor.href = "https://www.mapbox.com/"; + anchor.setAttribute("aria-label", this._map._getUIString('LogoControl.Title')); + anchor.setAttribute("rel", "noopener nofollow"); + this._container.appendChild(anchor); + this._container.style.display = 'none'; + + this._map.on('sourcedata', this._updateLogo); + this._updateLogo(); + + this._map.on('resize', this._updateCompact); + this._updateCompact(); + + return this._container; + } + + onRemove() { + DOM.remove(this._container); + this._map.off('sourcedata', this._updateLogo); + this._map.off('resize', this._updateCompact); + } + + getDefaultPosition() { + return 'bottom-left'; + } + + _updateLogo(e: any) { + if (!e || e.sourceDataType === 'metadata') { + this._container.style.display = this._logoRequired() ? 'block' : 'none'; + } + } + + _logoRequired() { + if (!this._map.style) return; + + const sourceCaches = this._map.style.sourceCaches; + for (const id in sourceCaches) { + const source = sourceCaches[id].getSource(); + if (source.mapbox_logo) { + return true; + } + } + + return false; + } + + _updateCompact() { + const containerChildren = this._container.children; + if (containerChildren.length) { + const anchor = containerChildren[0]; + if (this._map.getCanvasContainer().offsetWidth < 250) { + anchor.classList.add('mapboxgl-compact'); + } else { + anchor.classList.remove('mapboxgl-compact'); + } + } + } + +} + +export default LogoControl; diff --git a/node_modules/mapbox-gl/src/ui/control/navigation_control.js b/node_modules/mapbox-gl/src/ui/control/navigation_control.js new file mode 100644 index 0000000000000000000000000000000000000000..4ec8da6647bc2368f21e4a0aebebbce9fe0a8e61 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/control/navigation_control.js @@ -0,0 +1,257 @@ +// @flow + +import DOM from '../../util/dom'; +import {extend, bindAll} from '../../util/util'; +import {MouseRotateHandler, MousePitchHandler} from '../handler/mouse'; +import window from '../../util/window'; + +import type Map from '../map'; + +type Options = { + showCompass?: boolean, + showZoom?: boolean, + visualizePitch?: boolean +}; + +const defaultOptions: Options = { + showCompass: true, + showZoom: true, + visualizePitch: false +}; + +/** + * A `NavigationControl` control contains zoom buttons and a compass. + * + * @implements {IControl} + * @param {Object} [options] + * @param {Boolean} [options.showCompass=true] If `true` the compass button is included. + * @param {Boolean} [options.showZoom=true] If `true` the zoom-in and zoom-out buttons are included. + * @param {Boolean} [options.visualizePitch=false] If `true` the pitch is visualized by rotating X-axis of compass. + * @example + * var nav = new mapboxgl.NavigationControl(); + * map.addControl(nav, 'top-left'); + * @see [Display map navigation controls](https://www.mapbox.com/mapbox-gl-js/example/navigation/) + * @see [Add a third party vector tile source](https://www.mapbox.com/mapbox-gl-js/example/third-party/) + */ +class NavigationControl { + _map: Map; + options: Options; + _container: HTMLElement; + _zoomInButton: HTMLButtonElement; + _zoomOutButton: HTMLButtonElement; + _compass: HTMLButtonElement; + _compassIcon: HTMLElement; + _handler: MouseRotateWrapper; + + constructor(options: Options) { + this.options = extend({}, defaultOptions, options); + + this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-group'); + this._container.addEventListener('contextmenu', (e) => e.preventDefault()); + + if (this.options.showZoom) { + bindAll([ + '_setButtonTitle', + '_updateZoomButtons' + ], this); + this._zoomInButton = this._createButton('mapboxgl-ctrl-zoom-in', (e) => this._map.zoomIn({}, {originalEvent: e})); + DOM.create('span', `mapboxgl-ctrl-icon`, this._zoomInButton).setAttribute('aria-hidden', true); + this._zoomOutButton = this._createButton('mapboxgl-ctrl-zoom-out', (e) => this._map.zoomOut({}, {originalEvent: e})); + DOM.create('span', `mapboxgl-ctrl-icon`, this._zoomOutButton).setAttribute('aria-hidden', true); + } + if (this.options.showCompass) { + bindAll([ + '_rotateCompassArrow' + ], this); + this._compass = this._createButton('mapboxgl-ctrl-compass', (e) => { + if (this.options.visualizePitch) { + this._map.resetNorthPitch({}, {originalEvent: e}); + } else { + this._map.resetNorth({}, {originalEvent: e}); + } + }); + this._compassIcon = DOM.create('span', 'mapboxgl-ctrl-icon', this._compass); + this._compassIcon.setAttribute('aria-hidden', true); + } + } + + _updateZoomButtons() { + const zoom = this._map.getZoom(); + const isMax = zoom === this._map.getMaxZoom(); + const isMin = zoom === this._map.getMinZoom(); + this._zoomInButton.disabled = isMax; + this._zoomOutButton.disabled = isMin; + this._zoomInButton.setAttribute('aria-disabled', isMax.toString()); + this._zoomOutButton.setAttribute('aria-disabled', isMin.toString()); + } + + _rotateCompassArrow() { + const rotate = this.options.visualizePitch ? + `scale(${1 / Math.pow(Math.cos(this._map.transform.pitch * (Math.PI / 180)), 0.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${this._map.transform.angle * (180 / Math.PI)}deg)` : + `rotate(${this._map.transform.angle * (180 / Math.PI)}deg)`; + + this._compassIcon.style.transform = rotate; + } + + onAdd(map: Map) { + this._map = map; + if (this.options.showZoom) { + this._setButtonTitle(this._zoomInButton, 'ZoomIn'); + this._setButtonTitle(this._zoomOutButton, 'ZoomOut'); + this._map.on('zoom', this._updateZoomButtons); + this._updateZoomButtons(); + } + if (this.options.showCompass) { + this._setButtonTitle(this._compass, 'ResetBearing'); + if (this.options.visualizePitch) { + this._map.on('pitch', this._rotateCompassArrow); + } + this._map.on('rotate', this._rotateCompassArrow); + this._rotateCompassArrow(); + this._handler = new MouseRotateWrapper(this._map, this._compass, this.options.visualizePitch); + } + return this._container; + } + + onRemove() { + DOM.remove(this._container); + if (this.options.showZoom) { + this._map.off('zoom', this._updateZoomButtons); + } + if (this.options.showCompass) { + if (this.options.visualizePitch) { + this._map.off('pitch', this._rotateCompassArrow); + } + this._map.off('rotate', this._rotateCompassArrow); + this._handler.off(); + delete this._handler; + } + + delete this._map; + } + + _createButton(className: string, fn: () => mixed) { + const a = DOM.create('button', className, this._container); + a.type = 'button'; + a.addEventListener('click', fn); + return a; + } + + _setButtonTitle(button: HTMLButtonElement, title: string) { + const str = this._map._getUIString(`NavigationControl.${title}`); + button.title = str; + button.setAttribute('aria-label', str); + } +} + +class MouseRotateWrapper { + + map: Map; + _clickTolerance: number; + element: HTMLElement; + mouseRotate: MouseRotateHandler; + mousePitch: MousePitchHandler; + _startPos: Point; + _lastPos: Point; + + constructor(map: Map, element: HTMLElement, pitch?: boolean = false) { + this._clickTolerance = 10; + this.element = element; + this.mouseRotate = new MouseRotateHandler({clickTolerance: map.dragRotate._mouseRotate._clickTolerance}); + this.map = map; + if (pitch) this.mousePitch = new MousePitchHandler({clickTolerance: map.dragRotate._mousePitch._clickTolerance}); + + bindAll(['mousedown', 'mousemove', 'mouseup', 'touchstart', 'touchmove', 'touchend', 'reset'], this); + DOM.addEventListener(element, 'mousedown', this.mousedown); + DOM.addEventListener(element, 'touchstart', this.touchstart, {passive: false}); + DOM.addEventListener(element, 'touchmove', this.touchmove); + DOM.addEventListener(element, 'touchend', this.touchend); + DOM.addEventListener(element, 'touchcancel', this.reset); + } + + down(e: MouseEvent, point: Point) { + this.mouseRotate.mousedown(e, point); + if (this.mousePitch) this.mousePitch.mousedown(e, point); + DOM.disableDrag(); + } + + move(e: MouseEvent, point: Point) { + const map = this.map; + const r = this.mouseRotate.mousemoveWindow(e, point); + if (r && r.bearingDelta) map.setBearing(map.getBearing() + r.bearingDelta); + if (this.mousePitch) { + const p = this.mousePitch.mousemoveWindow(e, point); + if (p && p.pitchDelta) map.setPitch(map.getPitch() + p.pitchDelta); + } + } + + off() { + const element = this.element; + DOM.removeEventListener(element, 'mousedown', this.mousedown); + DOM.removeEventListener(element, 'touchstart', this.touchstart, {passive: false}); + DOM.removeEventListener(element, 'touchmove', this.touchmove); + DOM.removeEventListener(element, 'touchend', this.touchend); + DOM.removeEventListener(element, 'touchcancel', this.reset); + this.offTemp(); + } + + offTemp() { + DOM.enableDrag(); + DOM.removeEventListener(window, 'mousemove', this.mousemove); + DOM.removeEventListener(window, 'mouseup', this.mouseup); + } + + mousedown(e: MouseEvent) { + this.down(extend({}, e, {ctrlKey: true, preventDefault: () => e.preventDefault()}), DOM.mousePos(this.element, e)); + DOM.addEventListener(window, 'mousemove', this.mousemove); + DOM.addEventListener(window, 'mouseup', this.mouseup); + } + + mousemove(e: MouseEvent) { + this.move(e, DOM.mousePos(this.element, e)); + } + + mouseup(e: MouseEvent) { + this.mouseRotate.mouseupWindow(e); + if (this.mousePitch) this.mousePitch.mouseupWindow(e); + this.offTemp(); + } + + touchstart(e: TouchEvent) { + if (e.targetTouches.length !== 1) { + this.reset(); + } else { + this._startPos = this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0]; + this.down((({type: 'mousedown', button: 0, ctrlKey: true, preventDefault: () => e.preventDefault()}: any): MouseEvent), this._startPos); + } + } + + touchmove(e: TouchEvent) { + if (e.targetTouches.length !== 1) { + this.reset(); + } else { + this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0]; + this.move((({preventDefault: () => e.preventDefault()}: any): MouseEvent), this._lastPos); + } + } + + touchend(e: TouchEvent) { + if (e.targetTouches.length === 0 && + this._startPos && + this._lastPos && + this._startPos.dist(this._lastPos) < this._clickTolerance) { + this.element.click(); + } + this.reset(); + } + + reset() { + this.mouseRotate.reset(); + if (this.mousePitch) this.mousePitch.reset(); + delete this._startPos; + delete this._lastPos; + this.offTemp(); + } +} + +export default NavigationControl; diff --git a/node_modules/mapbox-gl/src/ui/control/scale_control.js b/node_modules/mapbox-gl/src/ui/control/scale_control.js new file mode 100644 index 0000000000000000000000000000000000000000..a8c5ce258587bc7561c559ee1a3c6f32944fa2eb --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/control/scale_control.js @@ -0,0 +1,142 @@ +// @flow + +import DOM from '../../util/dom'; +import {extend, bindAll} from '../../util/util'; + +import type Map from '../map'; + +type Unit = 'imperial' | 'metric' | 'nautical'; + +type Options = { + maxWidth?: number, + unit?: Unit; +}; + +const defaultOptions: Options = { + maxWidth: 100, + unit: 'metric' +}; + +/** + * A `ScaleControl` control displays the ratio of a distance on the map to the corresponding distance on the ground. + * + * @implements {IControl} + * @param {Object} [options] + * @param {number} [options.maxWidth='100'] The maximum length of the scale control in pixels. + * @param {string} [options.unit='metric'] Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`). + * @example + * var scale = new mapboxgl.ScaleControl({ + * maxWidth: 80, + * unit: 'imperial' + * }); + * map.addControl(scale); + * + * scale.setUnit('metric'); + */ +class ScaleControl { + _map: Map; + _container: HTMLElement; + options: Options; + + constructor(options: Options) { + this.options = extend({}, defaultOptions, options); + + bindAll([ + '_onMove', + 'setUnit' + ], this); + } + + getDefaultPosition() { + return 'bottom-left'; + } + + _onMove() { + updateScale(this._map, this._container, this.options); + } + + onAdd(map: Map) { + this._map = map; + this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-scale', map.getContainer()); + + this._map.on('move', this._onMove); + this._onMove(); + + return this._container; + } + + onRemove() { + DOM.remove(this._container); + this._map.off('move', this._onMove); + this._map = (undefined: any); + } + + /** + * Set the scale's unit of the distance + * + * @param unit Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`). + */ + setUnit(unit: Unit) { + this.options.unit = unit; + updateScale(this._map, this._container, this.options); + } +} + +export default ScaleControl; + +function updateScale(map, container, options) { + // A horizontal scale is imagined to be present at center of the map + // container with maximum length (Default) as 100px. + // Using spherical law of cosines approximation, the real distance is + // found between the two coordinates. + const maxWidth = options && options.maxWidth || 100; + + const y = map._container.clientHeight / 2; + const left = map.unproject([0, y]); + const right = map.unproject([maxWidth, y]); + const maxMeters = left.distanceTo(right); + // The real distance corresponding to 100px scale length is rounded off to + // near pretty number and the scale length for the same is found out. + // Default unit of the scale is based on User's locale. + if (options && options.unit === 'imperial') { + const maxFeet = 3.2808 * maxMeters; + if (maxFeet > 5280) { + const maxMiles = maxFeet / 5280; + setScale(container, maxWidth, maxMiles, map._getUIString('ScaleControl.Miles')); + } else { + setScale(container, maxWidth, maxFeet, map._getUIString('ScaleControl.Feet')); + } + } else if (options && options.unit === 'nautical') { + const maxNauticals = maxMeters / 1852; + setScale(container, maxWidth, maxNauticals, map._getUIString('ScaleControl.NauticalMiles')); + } else if (maxMeters >= 1000) { + setScale(container, maxWidth, maxMeters / 1000, map._getUIString('ScaleControl.Kilometers')); + } else { + setScale(container, maxWidth, maxMeters, map._getUIString('ScaleControl.Meters')); + } +} + +function setScale(container, maxWidth, maxDistance, unit) { + const distance = getRoundNum(maxDistance); + const ratio = distance / maxDistance; + container.style.width = `${maxWidth * ratio}px`; + container.innerHTML = `${distance} ${unit}`; +} + +function getDecimalRoundNum(d) { + const multiplier = Math.pow(10, Math.ceil(-Math.log(d) / Math.LN10)); + return Math.round(d * multiplier) / multiplier; +} + +function getRoundNum(num) { + const pow10 = Math.pow(10, (`${Math.floor(num)}`).length - 1); + let d = num / pow10; + + d = d >= 10 ? 10 : + d >= 5 ? 5 : + d >= 3 ? 3 : + d >= 2 ? 2 : + d >= 1 ? 1 : getDecimalRoundNum(d); + + return pow10 * d; +} diff --git a/node_modules/mapbox-gl/src/ui/default_locale.js b/node_modules/mapbox-gl/src/ui/default_locale.js new file mode 100644 index 0000000000000000000000000000000000000000..92c548d4504d84f4fe24ca755739e9726f584173 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/default_locale.js @@ -0,0 +1,22 @@ +// @flow + +const defaultLocale = { + 'AttributionControl.ToggleAttribution': 'Toggle attribution', + 'AttributionControl.MapFeedback': 'Map feedback', + 'FullscreenControl.Enter': 'Enter fullscreen', + 'FullscreenControl.Exit': 'Exit fullscreen', + 'GeolocateControl.FindMyLocation': 'Find my location', + 'GeolocateControl.LocationNotAvailable': 'Location not available', + 'LogoControl.Title': 'Mapbox logo', + 'NavigationControl.ResetBearing': 'Reset bearing to north', + 'NavigationControl.ZoomIn': 'Zoom in', + 'NavigationControl.ZoomOut': 'Zoom out', + 'ScaleControl.Feet': 'ft', + 'ScaleControl.Meters': 'm', + 'ScaleControl.Kilometers': 'km', + 'ScaleControl.Miles': 'mi', + 'ScaleControl.NauticalMiles': 'nm' + +}; + +export default defaultLocale; diff --git a/node_modules/mapbox-gl/src/ui/events.js b/node_modules/mapbox-gl/src/ui/events.js new file mode 100644 index 0000000000000000000000000000000000000000..275225d61e53c4c4a4a0cecd958b93edce65072b --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/events.js @@ -0,0 +1,1301 @@ +// @flow + +import {Event} from '../util/evented'; + +import DOM from '../util/dom'; +import Point from '@mapbox/point-geometry'; +import {extend} from '../util/util'; + +import type Map from './map'; +import type LngLat from '../geo/lng_lat'; + +/** + * `MapMouseEvent` is the event type for mouse-related map events. + * @extends {Object} + * @example + * // The `click` event is an example of a `MapMouseEvent`. + * // Set up an event listener on the map. + * map.on('click', function(e) { + * // The event object (e) contains information like the + * // coordinates of the point on the map that was clicked. + * console.log('A click event has occurred at ' + e.lngLat); + * }); + */ +export class MapMouseEvent extends Event { + /** + * The event type (one of {@link Map.event:mousedown}, + * {@link Map.event:mouseup}, + * {@link Map.event:click}, + * {@link Map.event:dblclick}, + * {@link Map.event:mousemove}, + * {@link Map.event:mouseover}, + * {@link Map.event:mouseenter}, + * {@link Map.event:mouseleave}, + * {@link Map.event:mouseout}, + * {@link Map.event:contextmenu}). + */ + type: 'mousedown' + | 'mouseup' + | 'click' + | 'dblclick' + | 'mousemove' + | 'mouseover' + | 'mouseenter' + | 'mouseleave' + | 'mouseout' + | 'contextmenu'; + + /** + * The `Map` object that fired the event. + */ + target: Map; + + /** + * The DOM event which caused the map event. + */ + originalEvent: MouseEvent; + + /** + * The pixel coordinates of the mouse cursor, relative to the map and measured from the top left corner. + */ + point: Point; + + /** + * The geographic location on the map of the mouse cursor. + */ + lngLat: LngLat; + + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the following default map behaviors: + * + * * On `mousedown` events, the behavior of {@link DragPanHandler} + * * On `mousedown` events, the behavior of {@link DragRotateHandler} + * * On `mousedown` events, the behavior of {@link BoxZoomHandler} + * * On `dblclick` events, the behavior of {@link DoubleClickZoomHandler} + * + */ + preventDefault() { + this._defaultPrevented = true; + } + + /** + * `true` if `preventDefault` has been called. + * @private + */ + get defaultPrevented(): boolean { + return this._defaultPrevented; + } + + _defaultPrevented: boolean; + + /** + * @private + */ + constructor(type: string, map: Map, originalEvent: MouseEvent, data: Object = {}) { + const point = DOM.mousePos(map.getCanvasContainer(), originalEvent); + const lngLat = map.unproject(point); + super(type, extend({point, lngLat, originalEvent}, data)); + this._defaultPrevented = false; + this.target = map; + } +} + +/** + * `MapTouchEvent` is the event type for touch-related map events. + * @extends {Object} + */ +export class MapTouchEvent extends Event { + /** + * The event type. + */ + type: 'touchstart' + | 'touchend' + | 'touchcancel'; + + /** + * The `Map` object that fired the event. + */ + target: Map; + + /** + * The DOM event which caused the map event. + */ + originalEvent: TouchEvent; + + /** + * The geographic location on the map of the center of the touch event points. + */ + lngLat: LngLat; + + /** + * The pixel coordinates of the center of the touch event points, relative to the map and measured from the top left + * corner. + */ + point: Point; + + /** + * The array of pixel coordinates corresponding to a + * [touch event's `touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) property. + */ + points: Array; + + /** + * The geographical locations on the map corresponding to a + * [touch event's `touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) property. + */ + lngLats: Array; + + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the following default map behaviors: + * + * * On `touchstart` events, the behavior of {@link DragPanHandler} + * * On `touchstart` events, the behavior of {@link TouchZoomRotateHandler} + * + */ + preventDefault() { + this._defaultPrevented = true; + } + + /** + * `true` if `preventDefault` has been called. + * @private + */ + get defaultPrevented(): boolean { + return this._defaultPrevented; + } + + _defaultPrevented: boolean; + + /** + * @private + */ + constructor(type: string, map: Map, originalEvent: TouchEvent) { + const touches = type === "touchend" ? originalEvent.changedTouches : originalEvent.touches; + const points = DOM.touchPos(map.getCanvasContainer(), touches); + const lngLats = points.map((t) => map.unproject(t)); + const point = points.reduce((prev, curr, i, arr) => { + return prev.add(curr.div(arr.length)); + }, new Point(0, 0)); + const lngLat = map.unproject(point); + super(type, {points, point, lngLats, lngLat, originalEvent}); + this._defaultPrevented = false; + } +} + +/** + * `MapWheelEvent` is the event type for the `wheel` map event. + * @extends {Object} + */ +export class MapWheelEvent extends Event { + /** + * The event type. + */ + type: 'wheel'; + + /** + * The `Map` object that fired the event. + */ + target: Map; + + /** + * The DOM event which caused the map event. + */ + originalEvent: WheelEvent; + + /** + * Prevents subsequent default processing of the event by the map. + * + * Calling this method will prevent the the behavior of {@link ScrollZoomHandler}. + */ + preventDefault() { + this._defaultPrevented = true; + } + + /** + * `true` if `preventDefault` has been called. + * @private + */ + get defaultPrevented(): boolean { + return this._defaultPrevented; + } + + _defaultPrevented: boolean; + + /** + * @private + */ + constructor(type: string, map: Map, originalEvent: WheelEvent) { + super(type, {originalEvent}); + this._defaultPrevented = false; + } +} + +/** + * A `MapBoxZoomEvent` is the event type for the boxzoom-related map events emitted by the {@link BoxZoomHandler}. + * + * @typedef {Object} MapBoxZoomEvent + * @property {MouseEvent} originalEvent The DOM event that triggered the boxzoom event. Can be a `MouseEvent` or `KeyboardEvent` + * @property {string} type The type of boxzoom event. One of `boxzoomstart`, `boxzoomend` or `boxzoomcancel` + * @property {Map} target The `Map` instance that triggerred the event + */ +export type MapBoxZoomEvent = { + type: 'boxzoomstart' + | 'boxzoomend' + | 'boxzoomcancel', + target: Map, + originalEvent: MouseEvent +}; + +/** + * A `MapDataEvent` object is emitted with the {@link Map.event:data} + * and {@link Map.event:dataloading} events. Possible values for + * `dataType`s are: + * + * - `'source'`: The non-tile data associated with any source + * - `'style'`: The [style](https://www.mapbox.com/mapbox-gl-style-spec/) used by the map + * + * @typedef {Object} MapDataEvent + * @property {string} type The event type. + * @property {string} dataType The type of data that has changed. One of `'source'`, `'style'`. + * @property {boolean} [isSourceLoaded] True if the event has a `dataType` of `source` and the source has no outstanding network requests. + * @property {Object} [source] The [style spec representation of the source](https://www.mapbox.com/mapbox-gl-style-spec/#sources) if the event has a `dataType` of `source`. + * @property {string} [sourceDataType] Included if the event has a `dataType` of `source` and the event signals + * that internal data has been received or changed. Possible values are `metadata`, `content` and `visibility`. + * @property {Object} [tile] The tile being loaded or changed, if the event has a `dataType` of `source` and + * the event is related to loading of a tile. + * @property {Coordinate} [coord] The coordinate of the tile if the event has a `dataType` of `source` and + * the event is related to loading of a tile. + * @example + * // The sourcedata event is an example of MapDataEvent. + * // Set up an event listener on the map. + * map.on('sourcedata', function(e) { + * if (e.isSourceLoaded) { + * // Do something when the source has finished loading + * } + * }); + */ +export type MapDataEvent = { + type: string, + dataType: string +}; + +export type MapContextEvent = { + type: 'webglcontextlost' | 'webglcontextrestored', + originalEvent: WebGLContextEvent +} + +export type MapEvent = + /** + * Fired when a pointing device (usually a mouse) is pressed within the map. + * + * **Note:** This event is compatible with the optional `layerId` parameter. + * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the + * the cursor is pressed while inside a visible portion of the specifed layer. + * + * @event mousedown + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener + * map.on('mousedown', function() { + * console.log('A mousedown event has occurred.'); + * }); + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener for a specific layer + * map.on('mousedown', 'poi-label', function() { + * console.log('A mousedown event has occurred on a visible portion of the poi-label layer.'); + * }); + * @see [Highlight features within a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/) + * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/) + */ + | 'mousedown' + + /** + * Fired when a pointing device (usually a mouse) is released within the map. + * + * **Note:** This event is compatible with the optional `layerId` parameter. + * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the + * the cursor is released while inside a visible portion of the specifed layer. + * + * @event mouseup + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener + * map.on('mouseup', function() { + * console.log('A mouseup event has occurred.'); + * }); + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener for a specific layer + * map.on('mouseup', 'poi-label', function() { + * console.log('A mouseup event has occurred on a visible portion of the poi-label layer.'); + * }); + * @see [Highlight features within a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/) + * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/) + */ + | 'mouseup' + + /** + * Fired when a pointing device (usually a mouse) is moved within the map. + * As you move the cursor across a web page containing a map, + * the event will fire each time it enters the map or any child elements. + * + * **Note:** This event is compatible with the optional `layerId` parameter. + * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the + * the cursor is moved inside a visible portion of the specifed layer. + * + * @event mouseover + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener + * map.on('mouseover', function() { + * console.log('A mouseover event has occurred.'); + * }); + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener for a specific layer + * map.on('mouseover', 'poi-label', function() { + * console.log('A mouseover event has occurred on a visible portion of the poi-label layer.'); + * }); + * @see [Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/) + * @see [Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/) + * @see [Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/) + */ + | 'mouseover' + + /** + * Fired when a pointing device (usually a mouse) is moved while the cursor is inside the map. + * As you move the cursor across the map, the event will fire every time the cursor changes position within the map. + * + * **Note:** This event is compatible with the optional `layerId` parameter. + * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the + * the cursor is inside a visible portion of the specified layer. + * + * @event mousemove + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener + * map.on('mousemove', function() { + * console.log('A mousemove event has occurred.'); + * }); + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener for a specific layer + * map.on('mousemove', 'poi-label', function() { + * console.log('A mousemove event has occurred on a visible portion of the poi-label layer.'); + * }); + * @see [Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/) + * @see [Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/) + * @see [Display a popup on over](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/) + */ + | 'mousemove' + + /** + * Fired when a pointing device (usually a mouse) is pressed and released at the same point on the map. + * + * **Note:** This event is compatible with the optional `layerId` parameter. + * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the + * point that is pressed and released contains a visible portion of the specifed layer. + * + * @event click + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener + * map.on('click', function(e) { + * console.log('A click event has occurred at ' + e.lngLat); + * }); + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener for a specific layer + * map.on('click', 'poi-label', function(e) { + * console.log('A click event has occurred on a visible portion of the poi-label layer at ' + e.lngLat); + * }); + * @see [Measure distances](https://www.mapbox.com/mapbox-gl-js/example/measure/) + * @see [Center the map on a clicked symbol](https://www.mapbox.com/mapbox-gl-js/example/center-on-symbol/) + */ + | 'click' + + /** + * Fired when a pointing device (usually a mouse) is pressed and released twice at the same point on + * the map in rapid succession. + * + * **Note:** This event is compatible with the optional `layerId` parameter. + * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only + * when the point that is clicked twice contains a visible portion of the specifed layer. + * + * @event dblclick + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener + * map.on('dblclick', function(e) { + * console.log('A dblclick event has occurred at ' + e.lngLat); + * }); + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener for a specific layer + * map.on('dblclick', 'poi-label', function(e) { + * console.log('A dblclick event has occurred on a visible portion of the poi-label layer at ' + e.lngLat); + * }); + */ + | 'dblclick' + + /** + * Fired when a pointing device (usually a mouse) enters a visible portion of a specified layer from + * outside that layer or outside the map canvas. + * + * **Important:** This event can only be listened for when {@link Map#on} includes three arguments, + * where the second argument specifies the desired layer. + * + * @event mouseenter + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener + * map.on('mouseenter', 'water', function() { + * console.log('A mouseenter event occurred on a visible portion of the water layer.'); + * }); + * @see [Center the map on a clicked symbol](https://docs.mapbox.com/mapbox-gl-js/example/center-on-symbol/) + * @see [Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/) + */ + | 'mouseenter' + + /** + * Fired when a pointing device (usually a mouse) leaves a visible portion of a specified layer, or leaves + * the map canvas. + * + * **Important:** This event can only be listened for when {@link Map#on} includes three arguements, + * where the second argument specifies the desired layer. + * + * @event mouseleave + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when the pointing device leaves + * // a visible portion of the specified layer. + * map.on('mouseleave', 'water', function() { + * console.log('A mouseleave event occurred.'); + * }); + * @see [Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/) + * @see [Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/) + */ + | 'mouseleave' + + /** + * Fired when a point device (usually a mouse) leaves the map's canvas. + * + * @event mouseout + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when the pointing device leave's + * // the map's canvas. + * map.on('mouseout', function() { + * console.log('A mouseout event occurred.'); + * }); + */ + | 'mouseout' + + /** + * Fired when the right button of the mouse is clicked or the context menu key is pressed within the map. + * + * @event contextmenu + * @memberof Map + * @instance + * @property {MapMouseEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when the right mouse button is + * // pressed within the map. + * map.on('contextmenu', function() { + * console.log('A contextmenu event occurred.'); + * }); + */ + | 'contextmenu' + + /** + * Fired when a [`wheel`](https://developer.mozilla.org/en-US/docs/Web/Events/wheel) event occurs within the map. + * + * @event wheel + * @memberof Map + * @instance + * @property {MapWheelEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when a wheel event occurs within the map. + * map.on('wheel', function() { + * console.log('A wheel event occurred.'); + * }); + */ + | 'wheel' + + /** + * Fired when a [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event occurs within the map. + * + * @event touchstart + * @memberof Map + * @instance + * @property {MapTouchEvent} data + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when a touchstart event occurs within the map. + * map.on('touchstart', function() { + * console.log('A touchstart event occurred.'); + * }); + * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/) + */ + | 'touchstart' + + /** + * Fired when a [`touchend`](https://developer.mozilla.org/en-US/docs/Web/Events/touchend) event occurs within the map. + * + * @event touchend + * @memberof Map + * @instance + * @property {MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when a touchstart event occurs within the map. + * map.on('touchstart', function() { + * console.log('A touchstart event occurred.'); + * }); + * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/) + */ + | 'touchend' + + /** + * Fired when a [`touchmove`](https://developer.mozilla.org/en-US/docs/Web/Events/touchmove) event occurs within the map. + * + * @event touchmove + * @memberof Map + * @instance + * @property {MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when a touchmove event occurs within the map. + * map.on('touchmove', function() { + * console.log('A touchmove event occurred.'); + * }); + * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/) + */ + | 'touchmove' + + /** + * Fired when a [`touchcancel`](https://developer.mozilla.org/en-US/docs/Web/Events/touchcancel) event occurs within the map. + * + * @event touchcancel + * @memberof Map + * @instance + * @property {MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when a touchcancel event occurs within the map. + * map.on('touchcancel', function() { + * console.log('A touchcancel event occurred.'); + * }); + */ + | 'touchcancel' + + /** + * Fired just before the map begins a transition from one + * view to another, as the result of either user interaction or methods such as {@link Map#jumpTo}. + * + * @event movestart + * @memberof Map + * @instance + * @property {{originalEvent: DragEvent}} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just before the map begins a transition + * // from one view to another. + * map.on('movestart', function() { + * console.log('A movestart` event occurred.'); + * }); + */ + | 'movestart' + + /** + * Fired repeatedly during an animated transition from one view to + * another, as the result of either user interaction or methods such as {@link Map#flyTo}. + * + * @event move + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // repeatedly during an animated transition. + * map.on('move', function() { + * console.log('A move event occurred.'); + * }); + * @see [Display HTML clusters with custom properties](https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/) + * @see [Filter features within map view](https://docs.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/) + */ + | 'move' + + /** + * Fired just after the map completes a transition from one + * view to another, as the result of either user interaction or methods such as {@link Map#jumpTo}. + * + * @event moveend + * @memberof Map + * @instance + * @property {{originalEvent: DragEvent}} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just after the map completes a transition. + * map.on('moveend', function() { + * console.log('A moveend event occurred.'); + * }); + * @see [Play map locations as a slideshow](https://www.mapbox.com/mapbox-gl-js/example/playback-locations/) + * @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/) + * @see [Display HTML clusters with custom properties](https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/) + */ + | 'moveend' + + /** + * Fired when a "drag to pan" interaction starts. See {@link DragPanHandler}. + * + * @event dragstart + * @memberof Map + * @instance + * @property {{originalEvent: DragEvent}} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when a "drag to pan" interaction starts. + * map.on('dragstart', function() { + * console.log('A dragstart event occurred.'); + * }); + */ + | 'dragstart' + + /** + * Fired repeatedly during a "drag to pan" interaction. See {@link DragPanHandler}. + * + * @event drag + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // repeatedly during a "drag to pan" interaction. + * map.on('drag', function() { + * console.log('A drag event occurred.'); + * }); + */ + | 'drag' + + /** + * Fired when a "drag to pan" interaction ends. See {@link DragPanHandler}. + * + * @event dragend + * @memberof Map + * @instance + * @property {{originalEvent: DragEvent}} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when a "drag to pan" interaction ends. + * map.on('dragend', function() { + * console.log('A dragend event occurred.'); + * }); + * @see [Create a draggable marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-marker/) + */ + | 'dragend' + + /** + * Fired just before the map begins a transition from one zoom level to another, + * as the result of either user interaction or methods such as {@link Map#flyTo}. + * + * @event zoomstart + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just before a zoom transition starts. + * map.on('zoomstart', function() { + * console.log('A zoomstart event occurred.'); + * }); + */ + | 'zoomstart' + + /** + * Fired repeatedly during an animated transition from one zoom level to another, + * as the result of either user interaction or methods such as {@link Map#flyTo}. + * + * @event zoom + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // repeatedly during a zoom transition. + * map.on('zoom', function() { + * console.log('A zoom event occurred.'); + * }); + * @see [Update a choropleth layer by zoom level](https://www.mapbox.com/mapbox-gl-js/example/updating-choropleth/) + */ + | 'zoom' + + /** + * Fired just after the map completes a transition from one zoom level to another, + * as the result of either user interaction or methods such as {@link Map#flyTo}. + * + * @event zoomend + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just after a zoom transition finishes. + * map.on('zoomend', function() { + * console.log('A zoomend event occurred.'); + * }); + */ + | 'zoomend' + + /** + * Fired when a "drag to rotate" interaction starts. See {@link DragRotateHandler}. + * + * @event rotatestart + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just before a "drag to rotate" interaction starts. + * map.on('rotatestart', function() { + * console.log('A rotatestart event occurred.'); + * }); + */ + | 'rotatestart' + + /** + * Fired repeatedly during a "drag to rotate" interaction. See {@link DragRotateHandler}. + * + * @event rotate + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // repeatedly during "drag to rotate" interaction. + * map.on('rotate', function() { + * console.log('A rotate event occurred.'); + * }); + */ + | 'rotate' + + /** + * Fired when a "drag to rotate" interaction ends. See {@link DragRotateHandler}. + * + * @event rotateend + * @memberof Map + * @instance + * @property {MapMouseEvent | MapTouchEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just after a "drag to rotate" interaction ends. + * map.on('rotateend', function() { + * console.log('A rotateend event occurred.'); + * }); + */ + | 'rotateend' + + /** + * Fired whenever the map's pitch (tilt) begins a change as + * the result of either user interaction or methods such as {@link Map#flyTo} . + * + * @event pitchstart + * @memberof Map + * @instance + * @property {MapEventData} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just before a pitch (tilt) transition starts. + * map.on('pitchstart', function() { + * console.log('A pitchstart event occurred.'); + * }); + */ + | 'pitchstart' + + /** + * Fired repeatedly during the map's pitch (tilt) animation between + * one state and another as the result of either user interaction + * or methods such as {@link Map#flyTo}. + * + * @event pitch + * @memberof Map + * @instance + * @property {MapEventData} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // repeatedly during a pitch (tilt) transition. + * map.on('pitch', function() { + * console.log('A pitch event occurred.'); + * }); + */ + | 'pitch' + + /** + * Fired immediately after the map's pitch (tilt) finishes changing as + * the result of either user interaction or methods such as {@link Map#flyTo}. + * + * @event pitchend + * @memberof Map + * @instance + * @property {MapEventData} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just after a pitch (tilt) transition ends. + * map.on('pitchend', function() { + * console.log('A pitchend event occurred.'); + * }); + */ + | 'pitchend' + + /** + * Fired when a "box zoom" interaction starts. See {@link BoxZoomHandler}. + * + * @event boxzoomstart + * @memberof Map + * @instance + * @property {MapBoxZoomEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just before a "box zoom" interaction starts. + * map.on('boxzoomstart', function() { + * console.log('A boxzoomstart event occurred.'); + * }); + */ + | 'boxzoomstart' + + /** + * Fired when a "box zoom" interaction ends. See {@link BoxZoomHandler}. + * + * @event boxzoomend + * @memberof Map + * @instance + * @type {Object} + * @property {MapBoxZoomEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just after a "box zoom" interaction ends. + * map.on('boxzoomend', function() { + * console.log('A boxzoomend event occurred.'); + * }); + */ + | 'boxzoomend' + + /** + * Fired when the user cancels a "box zoom" interaction, or when the bounding box does not meet the minimum size threshold. + * See {@link BoxZoomHandler}. + * + * @event boxzoomcancel + * @memberof Map + * @instance + * @property {MapBoxZoomEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // the user cancels a "box zoom" interaction. + * map.on('boxzoomcancel', function() { + * console.log('A boxzoomcancel event occurred.'); + * }); + */ + | 'boxzoomcancel' + + /** + * Fired immediately after the map has been resized. + * + * @event resize + * @memberof Map + * @instance + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // immediately after the map has been resized. + * map.on('resize', function() { + * console.log('A resize event occurred.'); + * }); + */ + | 'resize' + + /** + * Fired when the WebGL context is lost. + * + * @event webglcontextlost + * @memberof Map + * @instance + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when the WebGL context is lost. + * map.on('webglcontextlost', function() { + * console.log('A webglcontextlost event occurred.'); + * }); + */ + | 'webglcontextlost' + + /** + * Fired when the WebGL context is restored. + * + * @event webglcontextrestored + * @memberof Map + * @instance + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when the WebGL context is restored. + * map.on('webglcontextrestored', function() { + * console.log('A webglcontextrestored event occurred.'); + * }); + */ + | 'webglcontextrestored' + + /** + * Fired immediately after all necessary resources have been downloaded + * and the first visually complete rendering of the map has occurred. + * + * @event load + * @memberof Map + * @instance + * @type {Object} + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when the map has finished loading. + * map.on('load', function() { + * console.log('A load event occurred.'); + * }); + * @see [Draw GeoJSON points](https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/) + * @see [Add live realtime data](https://www.mapbox.com/mapbox-gl-js/example/live-geojson/) + * @see [Animate a point](https://www.mapbox.com/mapbox-gl-js/example/animate-point-along-line/) + */ + | 'load' + + /** + * Fired whenever the map is drawn to the screen, as the result of + * + * - a change to the map's position, zoom, pitch, or bearing + * - a change to the map's style + * - a change to a GeoJSON source + * - the loading of a vector tile, GeoJSON file, glyph, or sprite + * + * @event render + * @memberof Map + * @instance + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // whenever the map is drawn to the screen. + * map.on('render', function() { + * console.log('A render event occurred.'); + * }); + */ + | 'render' + + /** + * Fired after the last frame rendered before the map enters an + * "idle" state: + * + * - No camera transitions are in progress + * - All currently requested tiles have loaded + * - All fade/transition animations have completed + * + * @event idle + * @memberof Map + * @instance + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just before the map enters an "idle" state. + * map.on('idle', function() { + * console.log('A idle event occurred.'); + * }); + */ + | 'idle' + + /** + * Fired immediately after the map has been removed with {@link Map.event:remove}. + * + * @event remove + * @memberof Map + * @instance + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // just after the map is removed. + * map.on('remove', function() { + * console.log('A remove event occurred.'); + * }); + */ + | 'remove' + + /** + * Fired when an error occurs. This is GL JS's primary error reporting + * mechanism. We use an event instead of `throw` to better accommodate + * asyncronous operations. If no listeners are bound to the `error` event, the + * error will be printed to the console. + * + * @event error + * @memberof Map + * @instance + * @property {{error: {message: string}}} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when an error occurs. + * map.on('error', function() { + * console.log('A error event occurred.'); + * }); + */ + | 'error' + + /** + * Fired when any map data loads or changes. See {@link MapDataEvent} + * for more information. + * + * @event data + * @memberof Map + * @instance + * @property {MapDataEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when map data loads or changes. + * map.on('data', function() { + * console.log('A data event occurred.'); + * }); + * @see [Display HTML clusters with custom properties](https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/) + */ + | 'data' + + /** + * Fired when the map's style loads or changes. See + * {@link MapDataEvent} for more information. + * + * @event styledata + * @memberof Map + * @instance + * @property {MapDataEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when the map's style loads or changes. + * map.on('styledata', function() { + * console.log('A styledata event occurred.'); + * }); + */ + | 'styledata' + + /** + * Fired when one of the map's sources loads or changes, including if a tile belonging + * to a source loads or changes. See {@link MapDataEvent} for more information. + * + * @event sourcedata + * @memberof Map + * @instance + * @property {MapDataEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when one of the map's sources loads or changes. + * map.on('sourcedata', function() { + * console.log('A sourcedata event occurred.'); + * }); + */ + | 'sourcedata' + + /** + * Fired when any map data (style, source, tile, etc) begins loading or + * changing asyncronously. All `dataloading` events are followed by a `data` + * or `error` event. See {@link MapDataEvent} for more information. + * + * @event dataloading + * @memberof Map + * @instance + * @property {MapDataEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // when any map data begins loading + * // or changing asynchronously. + * map.on('dataloading', function() { + * console.log('A dataloading event occurred.'); + * }); + */ + | 'dataloading' + + /** + * Fired when the map's style begins loading or changing asyncronously. + * All `styledataloading` events are followed by a `styledata` + * or `error` event. See {@link MapDataEvent} for more information. + * + * @event styledataloading + * @memberof Map + * @instance + * @property {MapDataEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // map's style begins loading or + * // changing asyncronously. + * map.on('styledataloading', function() { + * console.log('A styledataloading event occurred.'); + * }); + */ + | 'styledataloading' + + /** + * Fired when one of the map's sources begins loading or changing asyncronously. + * All `sourcedataloading` events are followed by a `sourcedata` or `error` event. + * See {@link MapDataEvent} for more information. + * + * @event sourcedataloading + * @memberof Map + * @instance + * @property {MapDataEvent} data + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // map's sources begin loading or + * // changing asyncronously. + * map.on('sourcedataloading', function() { + * console.log('A sourcedataloading event occurred.'); + * }); + */ + | 'sourcedataloading' + + /** + * Fired when an icon or pattern needed by the style is missing. The missing image can + * be added with {@link Map#addImage} within this event listener callback to prevent the image from + * being skipped. This event can be used to dynamically generate icons and patterns. + * + * @event styleimagemissing + * @memberof Map + * @instance + * @property {string} id The id of the missing image. + * @example + * // Initialize the map + * var map = new mapboxgl.Map({ // map options }); + * // Set an event listener that fires + * // an icon or pattern is missing. + * map.on('styleimagemissing', function() { + * console.log('A styleimagemissing event occurred.'); + * }); + * @see [Generate and add a missing icon to the map](https://mapbox.com/mapbox-gl-js/example/add-image-missing-generated/) + */ + | 'styleimagemissing' + + /** + * @event style.load + * @memberof Map + * @instance + * @private + */ + | 'style.load'; diff --git a/node_modules/mapbox-gl/src/ui/handler/box_zoom.js b/node_modules/mapbox-gl/src/ui/handler/box_zoom.js new file mode 100644 index 0000000000000000000000000000000000000000..c004e3637d004065f31900114010f03ce1190f27 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/box_zoom.js @@ -0,0 +1,170 @@ +// @flow + +import DOM from '../../util/dom'; + +import {Event} from '../../util/evented'; + +import type Map from '../map'; + +/** + * The `BoxZoomHandler` allows the user to zoom the map to fit within a bounding box. + * The bounding box is defined by clicking and holding `shift` while dragging the cursor. + */ +class BoxZoomHandler { + _map: Map; + _el: HTMLElement; + _container: HTMLElement; + _enabled: boolean; + _active: boolean; + _startPos: Point; + _lastPos: Point; + _box: HTMLElement; + _clickTolerance: number; + + /** + * @private + */ + constructor(map: Map, options: { + clickTolerance: number + }) { + this._map = map; + this._el = map.getCanvasContainer(); + this._container = map.getContainer(); + this._clickTolerance = options.clickTolerance || 1; + } + + /** + * Returns a Boolean indicating whether the "box zoom" interaction is enabled. + * + * @returns {boolean} `true` if the "box zoom" interaction is enabled. + */ + isEnabled() { + return !!this._enabled; + } + + /** + * Returns a Boolean indicating whether the "box zoom" interaction is active, i.e. currently being used. + * + * @returns {boolean} `true` if the "box zoom" interaction is active. + */ + isActive() { + return !!this._active; + } + + /** + * Enables the "box zoom" interaction. + * + * @example + * map.boxZoom.enable(); + */ + enable() { + if (this.isEnabled()) return; + this._enabled = true; + } + + /** + * Disables the "box zoom" interaction. + * + * @example + * map.boxZoom.disable(); + */ + disable() { + if (!this.isEnabled()) return; + this._enabled = false; + } + + mousedown(e: MouseEvent, point: Point) { + if (!this.isEnabled()) return; + if (!(e.shiftKey && e.button === 0)) return; + + DOM.disableDrag(); + this._startPos = this._lastPos = point; + this._active = true; + } + + mousemoveWindow(e: MouseEvent, point: Point) { + if (!this._active) return; + + const pos = point; + + if (this._lastPos.equals(pos) || (!this._box && pos.dist(this._startPos) < this._clickTolerance)) { + return; + } + + const p0 = this._startPos; + this._lastPos = pos; + + if (!this._box) { + this._box = DOM.create('div', 'mapboxgl-boxzoom', this._container); + this._container.classList.add('mapboxgl-crosshair'); + this._fireEvent('boxzoomstart', e); + } + + const minX = Math.min(p0.x, pos.x), + maxX = Math.max(p0.x, pos.x), + minY = Math.min(p0.y, pos.y), + maxY = Math.max(p0.y, pos.y); + + DOM.setTransform(this._box, `translate(${minX}px,${minY}px)`); + + this._box.style.width = `${maxX - minX}px`; + this._box.style.height = `${maxY - minY}px`; + } + + mouseupWindow(e: MouseEvent, point: Point) { + if (!this._active) return; + + if (e.button !== 0) return; + + const p0 = this._startPos, + p1 = point; + + this.reset(); + + DOM.suppressClick(); + + if (p0.x === p1.x && p0.y === p1.y) { + this._fireEvent('boxzoomcancel', e); + } else { + this._map.fire(new Event('boxzoomend', {originalEvent: e})); + return { + cameraAnimation: map => map.fitScreenCoordinates(p0, p1, this._map.getBearing(), {linear: true}) + }; + } + } + + keydown(e: KeyboardEvent) { + if (!this._active) return; + + if (e.keyCode === 27) { + this.reset(); + this._fireEvent('boxzoomcancel', e); + } + } + + blur() { + this.reset(); + } + + reset() { + this._active = false; + + this._container.classList.remove('mapboxgl-crosshair'); + + if (this._box) { + DOM.remove(this._box); + this._box = (null: any); + } + + DOM.enableDrag(); + + delete this._startPos; + delete this._lastPos; + } + + _fireEvent(type: string, e: *) { + return this._map.fire(new Event(type, {originalEvent: e})); + } +} + +export default BoxZoomHandler; diff --git a/node_modules/mapbox-gl/src/ui/handler/click_zoom.js b/node_modules/mapbox-gl/src/ui/handler/click_zoom.js new file mode 100644 index 0000000000000000000000000000000000000000..2d8f5662b7f876ce01aeb50d47e016a3da6aafbc --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/click_zoom.js @@ -0,0 +1,52 @@ +// @flow + +import type Point from '@mapbox/point-geometry'; +import type Map from '../map'; + +export default class ClickZoomHandler { + + _enabled: boolean; + _active: boolean; + + constructor() { + this.reset(); + } + + reset() { + this._active = false; + } + + blur() { + this.reset(); + } + + dblclick(e: MouseEvent, point: Point) { + e.preventDefault(); + return { + cameraAnimation: (map: Map) => { + map.easeTo({ + duration: 300, + zoom: map.getZoom() + (e.shiftKey ? -1 : 1), + around: map.unproject(point) + }, {originalEvent: e}); + } + }; + } + + enable() { + this._enabled = true; + } + + disable() { + this._enabled = false; + this.reset(); + } + + isEnabled() { + return this._enabled; + } + + isActive() { + return this._active; + } +} diff --git a/node_modules/mapbox-gl/src/ui/handler/handler_util.js b/node_modules/mapbox-gl/src/ui/handler/handler_util.js new file mode 100644 index 0000000000000000000000000000000000000000..493f93d626404ed543f0507cc750bbb441151adb --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/handler_util.js @@ -0,0 +1,12 @@ +// @flow + +import assert from 'assert'; + +export function indexTouches(touches: Array, points: Array) { + assert(touches.length === points.length); + const obj = {}; + for (let i = 0; i < touches.length; i++) { + obj[touches[i].identifier] = points[i]; + } + return obj; +} diff --git a/node_modules/mapbox-gl/src/ui/handler/keyboard.js b/node_modules/mapbox-gl/src/ui/handler/keyboard.js new file mode 100644 index 0000000000000000000000000000000000000000..15de2d541532b4a7502fee689b6d75b27bba3a0e --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/keyboard.js @@ -0,0 +1,208 @@ +// @flow + +import type Map from '../map'; + +const defaultOptions = { + panStep: 100, + bearingStep: 15, + pitchStep: 10 +}; + +/** + * The `KeyboardHandler` allows the user to zoom, rotate, and pan the map using + * the following keyboard shortcuts: + * + * - `=` / `+`: Increase the zoom level by 1. + * - `Shift-=` / `Shift-+`: Increase the zoom level by 2. + * - `-`: Decrease the zoom level by 1. + * - `Shift--`: Decrease the zoom level by 2. + * - Arrow keys: Pan by 100 pixels. + * - `Shift+⇢`: Increase the rotation by 15 degrees. + * - `Shift+⇠`: Decrease the rotation by 15 degrees. + * - `Shift+⇡`: Increase the pitch by 10 degrees. + * - `Shift+⇣`: Decrease the pitch by 10 degrees. + */ +class KeyboardHandler { + _enabled: boolean; + _active: boolean; + _panStep: number; + _bearingStep: number; + _pitchStep: number; + _rotationDisabled: boolean; + + /** + * @private + */ + constructor() { + const stepOptions = defaultOptions; + this._panStep = stepOptions.panStep; + this._bearingStep = stepOptions.bearingStep; + this._pitchStep = stepOptions.pitchStep; + this._rotationDisabled = false; + } + + blur() { + this.reset(); + } + + reset() { + this._active = false; + } + + keydown(e: KeyboardEvent) { + if (e.altKey || e.ctrlKey || e.metaKey) return; + + let zoomDir = 0; + let bearingDir = 0; + let pitchDir = 0; + let xDir = 0; + let yDir = 0; + + switch (e.keyCode) { + case 61: + case 107: + case 171: + case 187: + zoomDir = 1; + break; + + case 189: + case 109: + case 173: + zoomDir = -1; + break; + + case 37: + if (e.shiftKey) { + bearingDir = -1; + } else { + e.preventDefault(); + xDir = -1; + } + break; + + case 39: + if (e.shiftKey) { + bearingDir = 1; + } else { + e.preventDefault(); + xDir = 1; + } + break; + + case 38: + if (e.shiftKey) { + pitchDir = 1; + } else { + e.preventDefault(); + yDir = -1; + } + break; + + case 40: + if (e.shiftKey) { + pitchDir = -1; + } else { + e.preventDefault(); + yDir = 1; + } + break; + + default: + return; + } + + if (this._rotationDisabled) { + bearingDir = 0; + pitchDir = 0; + } + + return { + cameraAnimation: (map: Map) => { + const zoom = map.getZoom(); + map.easeTo({ + duration: 300, + easeId: 'keyboardHandler', + easing: easeOut, + + zoom: zoomDir ? Math.round(zoom) + zoomDir * (e.shiftKey ? 2 : 1) : zoom, + bearing: map.getBearing() + bearingDir * this._bearingStep, + pitch: map.getPitch() + pitchDir * this._pitchStep, + offset: [-xDir * this._panStep, -yDir * this._panStep], + center: map.getCenter() + }, {originalEvent: e}); + } + }; + } + + /** + * Enables the "keyboard rotate and zoom" interaction. + * + * @example + * map.keyboard.enable(); + */ + enable() { + this._enabled = true; + } + + /** + * Disables the "keyboard rotate and zoom" interaction. + * + * @example + * map.keyboard.disable(); + */ + disable() { + this._enabled = false; + this.reset(); + } + + /** + * Returns a Boolean indicating whether the "keyboard rotate and zoom" + * interaction is enabled. + * + * @returns {boolean} `true` if the "keyboard rotate and zoom" + * interaction is enabled. + */ + isEnabled() { + return this._enabled; + } + + /** + * Returns true if the handler is enabled and has detected the start of a + * zoom/rotate gesture. + * + * @returns {boolean} `true` if the handler is enabled and has detected the + * start of a zoom/rotate gesture. + */ + isActive() { + return this._active; + } + + /** + * Disables the "keyboard pan/rotate" interaction, leaving the + * "keyboard zoom" interaction enabled. + * + * @example + * map.keyboard.disableRotation(); + */ + disableRotation() { + this._rotationDisabled = true; + } + + /** + * Enables the "keyboard pan/rotate" interaction. + * + * @example + * map.keyboard.enable(); + * map.keyboard.enableRotation(); + */ + enableRotation() { + this._rotationDisabled = false; + } +} + +function easeOut(t: number) { + return t * (2 - t); +} + +export default KeyboardHandler; diff --git a/node_modules/mapbox-gl/src/ui/handler/map_event.js b/node_modules/mapbox-gl/src/ui/handler/map_event.js new file mode 100644 index 0000000000000000000000000000000000000000..31b46e5ba23b0255fb237f73c1e53c27f3166069 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/map_event.js @@ -0,0 +1,156 @@ +// @flow + +import {MapMouseEvent, MapTouchEvent, MapWheelEvent} from '../events'; +import type Map from '../map'; + +export class MapEventHandler { + + _mousedownPos: Point; + _clickTolerance: number; + _map: Map; + + constructor(map: Map, options: { clickTolerance: number }) { + this._map = map; + this._clickTolerance = options.clickTolerance; + } + + reset() { + delete this._mousedownPos; + } + + wheel(e: WheelEvent) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - ScrollZoom + return this._firePreventable(new MapWheelEvent(e.type, this._map, e)); + } + + mousedown(e: MouseEvent, point: Point) { + this._mousedownPos = point; + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - MousePan + // - MouseRotate + // - MousePitch + // - DblclickHandler + return this._firePreventable(new MapMouseEvent(e.type, this._map, e)); + } + + mouseup(e: MouseEvent) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + + click(e: MouseEvent, point: Point) { + if (this._mousedownPos && this._mousedownPos.dist(point) >= this._clickTolerance) return; + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + + dblclick(e: MouseEvent) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - DblClickZoom + return this._firePreventable(new MapMouseEvent(e.type, this._map, e)); + } + + mouseover(e: MouseEvent) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + + mouseout(e: MouseEvent) { + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + + touchstart(e: TouchEvent) { + // If mapEvent.preventDefault() is called by the user, prevent handlers such as: + // - TouchPan + // - TouchZoom + // - TouchRotate + // - TouchPitch + // - TapZoom + // - SwipeZoom + return this._firePreventable(new MapTouchEvent(e.type, this._map, e)); + } + + touchmove(e: TouchEvent) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + + touchend(e: TouchEvent) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + + touchcancel(e: TouchEvent) { + this._map.fire(new MapTouchEvent(e.type, this._map, e)); + } + + _firePreventable(mapEvent: MapMouseEvent | MapTouchEvent | MapWheelEvent) { + this._map.fire(mapEvent); + if (mapEvent.defaultPrevented) { + // returning an object marks the handler as active and resets other handlers + return {}; + } + } + + isEnabled() { + return true; + } + + isActive() { + return false; + } + enable() {} + disable() {} +} + +export class BlockableMapEventHandler { + _map: Map; + _delayContextMenu: boolean; + _contextMenuEvent: MouseEvent; + + constructor(map: Map) { + this._map = map; + } + + reset() { + this._delayContextMenu = false; + delete this._contextMenuEvent; + } + + mousemove(e: MouseEvent) { + // mousemove map events should not be fired when interaction handlers (pan, rotate, etc) are active + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + + mousedown() { + this._delayContextMenu = true; + } + + mouseup() { + this._delayContextMenu = false; + if (this._contextMenuEvent) { + this._map.fire(new MapMouseEvent('contextmenu', this._map, this._contextMenuEvent)); + delete this._contextMenuEvent; + } + } + contextmenu(e: MouseEvent) { + if (this._delayContextMenu) { + // Mac: contextmenu fired on mousedown; we save it until mouseup for consistency's sake + this._contextMenuEvent = e; + } else { + // Windows: contextmenu fired on mouseup, so fire event now + this._map.fire(new MapMouseEvent(e.type, this._map, e)); + } + + // prevent browser context menu when necessary + if (this._map.listens('contextmenu')) { + e.preventDefault(); + } + } + + isEnabled() { + return true; + } + + isActive() { + return false; + } + enable() {} + disable() {} +} diff --git a/node_modules/mapbox-gl/src/ui/handler/mouse.js b/node_modules/mapbox-gl/src/ui/handler/mouse.js new file mode 100644 index 0000000000000000000000000000000000000000..55b235fe39f74a089166d6d065345839ed6e21ee --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/mouse.js @@ -0,0 +1,171 @@ +// @flow + +import DOM from '../../util/dom'; +import type Point from '@mapbox/point-geometry'; + +const LEFT_BUTTON = 0; +const RIGHT_BUTTON = 2; + +// the values for each button in MouseEvent.buttons +const BUTTONS_FLAGS = { + [LEFT_BUTTON]: 1, + [RIGHT_BUTTON]: 2 +}; + +function buttonStillPressed(e: MouseEvent, button: number) { + const flag = BUTTONS_FLAGS[button]; + return e.buttons === undefined || (e.buttons & flag) !== flag; +} + +class MouseHandler { + + _enabled: boolean; + _active: boolean; + _lastPoint: Point; + _eventButton: number; + _moved: boolean; + _clickTolerance: number; + + constructor(options: { clickTolerance: number }) { + this.reset(); + this._clickTolerance = options.clickTolerance || 1; + } + + blur() { + this.reset(); + } + + reset() { + this._active = false; + this._moved = false; + delete this._lastPoint; + delete this._eventButton; + } + + _correctButton(e: MouseEvent, button: number) { //eslint-disable-line + return false; // implemented by child + } + + _move(lastPoint: Point, point: Point) { //eslint-disable-line + return {}; // implemented by child + } + + mousedown(e: MouseEvent, point: Point) { + if (this._lastPoint) return; + + const eventButton = DOM.mouseButton(e); + if (!this._correctButton(e, eventButton)) return; + + this._lastPoint = point; + this._eventButton = eventButton; + } + + mousemoveWindow(e: MouseEvent, point: Point) { + const lastPoint = this._lastPoint; + if (!lastPoint) return; + e.preventDefault(); + + if (buttonStillPressed(e, this._eventButton)) { + // Some browsers don't fire a `mouseup` when the mouseup occurs outside + // the window or iframe: + // https://github.com/mapbox/mapbox-gl-js/issues/4622 + // + // If the button is no longer pressed during this `mousemove` it may have + // been released outside of the window or iframe. + this.reset(); + return; + } + + if (!this._moved && point.dist(lastPoint) < this._clickTolerance) return; + this._moved = true; + this._lastPoint = point; + + // implemented by child class + return this._move(lastPoint, point); + } + + mouseupWindow(e: MouseEvent) { + if (!this._lastPoint) return; + const eventButton = DOM.mouseButton(e); + if (eventButton !== this._eventButton) return; + if (this._moved) DOM.suppressClick(); + this.reset(); + } + + enable() { + this._enabled = true; + } + + disable() { + this._enabled = false; + this.reset(); + } + + isEnabled() { + return this._enabled; + } + + isActive() { + return this._active; + } +} + +export class MousePanHandler extends MouseHandler { + + mousedown(e: MouseEvent, point: Point) { + super.mousedown(e, point); + if (this._lastPoint) this._active = true; + } + _correctButton(e: MouseEvent, button: number) { + return button === LEFT_BUTTON && !e.ctrlKey; + } + + _move(lastPoint: Point, point: Point) { + return { + around: point, + panDelta: point.sub(lastPoint) + }; + } +} + +export class MouseRotateHandler extends MouseHandler { + _correctButton(e: MouseEvent, button: number) { + return (button === LEFT_BUTTON && e.ctrlKey) || (button === RIGHT_BUTTON); + } + + _move(lastPoint: Point, point: Point) { + const degreesPerPixelMoved = 0.8; + const bearingDelta = (point.x - lastPoint.x) * degreesPerPixelMoved; + if (bearingDelta) { + this._active = true; + return {bearingDelta}; + } + } + + contextmenu(e: MouseEvent) { + // prevent browser context menu when necessary; we don't allow it with rotation + // because we can't discern rotation gesture start from contextmenu on Mac + e.preventDefault(); + } +} + +export class MousePitchHandler extends MouseHandler { + _correctButton(e: MouseEvent, button: number) { + return (button === LEFT_BUTTON && e.ctrlKey) || (button === RIGHT_BUTTON); + } + + _move(lastPoint: Point, point: Point) { + const degreesPerPixelMoved = -0.5; + const pitchDelta = (point.y - lastPoint.y) * degreesPerPixelMoved; + if (pitchDelta) { + this._active = true; + return {pitchDelta}; + } + } + + contextmenu(e: MouseEvent) { + // prevent browser context menu when necessary; we don't allow it with rotation + // because we can't discern rotation gesture start from contextmenu on Mac + e.preventDefault(); + } +} diff --git a/node_modules/mapbox-gl/src/ui/handler/scroll_zoom.js b/node_modules/mapbox-gl/src/ui/handler/scroll_zoom.js new file mode 100644 index 0000000000000000000000000000000000000000..40eb32a89d4d8bd26bbd12c052111351b778aeae --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/scroll_zoom.js @@ -0,0 +1,350 @@ +// @flow + +import assert from 'assert'; +import DOM from '../../util/dom'; + +import {ease as _ease, bindAll, bezier} from '../../util/util'; +import browser from '../../util/browser'; +import window from '../../util/window'; +import {number as interpolate} from '../../style-spec/util/interpolate'; +import LngLat from '../../geo/lng_lat'; + +import type Map from '../map'; +import type HandlerManager from '../handler_manager'; +import type Point from '@mapbox/point-geometry'; + +// deltaY value for mouse scroll wheel identification +const wheelZoomDelta = 4.000244140625; + +// These magic numbers control the rate of zoom. Trackpad events fire at a greater +// frequency than mouse scroll wheel, so reduce the zoom rate per wheel tick +const defaultZoomRate = 1 / 100; +const wheelZoomRate = 1 / 450; + +// upper bound on how much we scale the map in any single render frame; this +// is used to limit zoom rate in the case of very fast scrolling +const maxScalePerFrame = 2; + +/** + * The `ScrollZoomHandler` allows the user to zoom the map by scrolling. + */ +class ScrollZoomHandler { + _map: Map; + _el: HTMLElement; + _enabled: boolean; + _active: boolean; + _zooming: boolean; + _aroundCenter: boolean; + _around: Point; + _aroundPoint: Point; + _type: 'wheel' | 'trackpad' | null; + _lastValue: number; + _timeout: ?TimeoutID; // used for delayed-handling of a single wheel movement + _finishTimeout: ?TimeoutID; // used to delay final '{move,zoom}end' events + + _lastWheelEvent: any; + _lastWheelEventTime: number; + + _startZoom: ?number; + _targetZoom: ?number; + _delta: number; + _easing: ?((number) => number); + _prevEase: ?{start: number, duration: number, easing: (_: number) => number}; + + _frameId: ?boolean; + _handler: HandlerManager; + + _defaultZoomRate: number; + _wheelZoomRate: number; + + /** + * @private + */ + constructor(map: Map, handler: HandlerManager) { + this._map = map; + this._el = map.getCanvasContainer(); + this._handler = handler; + + this._delta = 0; + + this._defaultZoomRate = defaultZoomRate; + this._wheelZoomRate = wheelZoomRate; + + bindAll(['_onTimeout'], this); + } + + /** + * Set the zoom rate of a trackpad + * @param {number} [zoomRate=1/100] The rate used to scale trackpad movement to a zoom value. + * @example + * // Speed up trackpad zoom + * map.scrollZoom.setZoomRate(1/25); + */ + setZoomRate(zoomRate: number) { + this._defaultZoomRate = zoomRate; + } + + /** + * Set the zoom rate of a mouse wheel + * @param {number} [wheelZoomRate=1/450] The rate used to scale mouse wheel movement to a zoom value. + * @example + * // Slow down zoom of mouse wheel + * map.scrollZoom.setWheelZoomRate(1/600); + */ + setWheelZoomRate(wheelZoomRate: number) { + this._wheelZoomRate = wheelZoomRate; + } + + /** + * Returns a Boolean indicating whether the "scroll to zoom" interaction is enabled. + * + * @returns {boolean} `true` if the "scroll to zoom" interaction is enabled. + */ + isEnabled() { + return !!this._enabled; + } + + /* + * Active state is turned on and off with every scroll wheel event and is set back to false before the map + * render is called, so _active is not a good candidate for determining if a scroll zoom animation is in + * progress. + */ + isActive() { + return !!this._active || this._finishTimeout !== undefined; + } + + isZooming() { + return !!this._zooming; + } + + /** + * Enables the "scroll to zoom" interaction. + * + * @param {Object} [options] Options object. + * @param {string} [options.around] If "center" is passed, map will zoom around center of map + * + * @example + * map.scrollZoom.enable(); + * @example + * map.scrollZoom.enable({ around: 'center' }) + */ + enable(options: any) { + if (this.isEnabled()) return; + this._enabled = true; + this._aroundCenter = options && options.around === 'center'; + } + + /** + * Disables the "scroll to zoom" interaction. + * + * @example + * map.scrollZoom.disable(); + */ + disable() { + if (!this.isEnabled()) return; + this._enabled = false; + } + + wheel(e: WheelEvent) { + if (!this.isEnabled()) return; + + // Remove `any` cast when https://github.com/facebook/flow/issues/4879 is fixed. + let value = e.deltaMode === (window.WheelEvent: any).DOM_DELTA_LINE ? e.deltaY * 40 : e.deltaY; + const now = browser.now(), + timeDelta = now - (this._lastWheelEventTime || 0); + + this._lastWheelEventTime = now; + + if (value !== 0 && (value % wheelZoomDelta) === 0) { + // This one is definitely a mouse wheel event. + this._type = 'wheel'; + + } else if (value !== 0 && Math.abs(value) < 4) { + // This one is definitely a trackpad event because it is so small. + this._type = 'trackpad'; + + } else if (timeDelta > 400) { + // This is likely a new scroll action. + this._type = null; + this._lastValue = value; + + // Start a timeout in case this was a singular event, and dely it by up to 40ms. + this._timeout = setTimeout(this._onTimeout, 40, e); + + } else if (!this._type) { + // This is a repeating event, but we don't know the type of event just yet. + // If the delta per time is small, we assume it's a fast trackpad; otherwise we switch into wheel mode. + this._type = (Math.abs(timeDelta * value) < 200) ? 'trackpad' : 'wheel'; + + // Make sure our delayed event isn't fired again, because we accumulate + // the previous event (which was less than 40ms ago) into this event. + if (this._timeout) { + clearTimeout(this._timeout); + this._timeout = null; + value += this._lastValue; + } + } + + // Slow down zoom if shift key is held for more precise zooming + if (e.shiftKey && value) value = value / 4; + + // Only fire the callback if we actually know what type of scrolling device the user uses. + if (this._type) { + this._lastWheelEvent = e; + this._delta -= value; + if (!this._active) { + this._start(e); + } + } + + e.preventDefault(); + } + + _onTimeout(initialEvent: any) { + this._type = 'wheel'; + this._delta -= this._lastValue; + if (!this._active) { + this._start(initialEvent); + } + } + + _start(e: any) { + if (!this._delta) return; + + if (this._frameId) { + this._frameId = null; + } + + this._active = true; + if (!this.isZooming()) { + this._zooming = true; + } + + if (this._finishTimeout) { + clearTimeout(this._finishTimeout); + delete this._finishTimeout; + } + + const pos = DOM.mousePos(this._el, e); + + this._around = LngLat.convert(this._aroundCenter ? this._map.getCenter() : this._map.unproject(pos)); + this._aroundPoint = this._map.transform.locationPoint(this._around); + if (!this._frameId) { + this._frameId = true; + this._handler._triggerRenderFrame(); + } + } + + renderFrame() { + if (!this._frameId) return; + this._frameId = null; + + if (!this.isActive()) return; + const tr = this._map.transform; + + // if we've had scroll events since the last render frame, consume the + // accumulated delta, and update the target zoom level accordingly + if (this._delta !== 0) { + // For trackpad events and single mouse wheel ticks, use the default zoom rate + const zoomRate = (this._type === 'wheel' && Math.abs(this._delta) > wheelZoomDelta) ? this._wheelZoomRate : this._defaultZoomRate; + // Scale by sigmoid of scroll wheel delta. + let scale = maxScalePerFrame / (1 + Math.exp(-Math.abs(this._delta * zoomRate))); + + if (this._delta < 0 && scale !== 0) { + scale = 1 / scale; + } + + const fromScale = typeof this._targetZoom === 'number' ? tr.zoomScale(this._targetZoom) : tr.scale; + this._targetZoom = Math.min(tr.maxZoom, Math.max(tr.minZoom, tr.scaleZoom(fromScale * scale))); + + // if this is a mouse wheel, refresh the starting zoom and easing + // function we're using to smooth out the zooming between wheel + // events + if (this._type === 'wheel') { + this._startZoom = tr.zoom; + this._easing = this._smoothOutEasing(200); + } + + this._delta = 0; + } + + const targetZoom = typeof this._targetZoom === 'number' ? + this._targetZoom : tr.zoom; + const startZoom = this._startZoom; + const easing = this._easing; + + let finished = false; + let zoom; + if (this._type === 'wheel' && startZoom && easing) { + assert(easing && typeof startZoom === 'number'); + + const t = Math.min((browser.now() - this._lastWheelEventTime) / 200, 1); + const k = easing(t); + zoom = interpolate(startZoom, targetZoom, k); + if (t < 1) { + if (!this._frameId) { + this._frameId = true; + } + } else { + finished = true; + } + } else { + zoom = targetZoom; + finished = true; + } + + this._active = true; + + if (finished) { + this._active = false; + this._finishTimeout = setTimeout(() => { + this._zooming = false; + this._handler._triggerRenderFrame(); + delete this._targetZoom; + delete this._finishTimeout; + }, 200); + } + + return { + noInertia: true, + needsRenderFrame: !finished, + zoomDelta: zoom - tr.zoom, + around: this._aroundPoint, + originalEvent: this._lastWheelEvent + }; + } + + _smoothOutEasing(duration: number) { + let easing = _ease; + + if (this._prevEase) { + const ease = this._prevEase, + t = (browser.now() - ease.start) / ease.duration, + speed = ease.easing(t + 0.01) - ease.easing(t), + + // Quick hack to make new bezier that is continuous with last + x = 0.27 / Math.sqrt(speed * speed + 0.0001) * 0.01, + y = Math.sqrt(0.27 * 0.27 - x * x); + + easing = bezier(x, y, 0.25, 1); + } + + this._prevEase = { + start: browser.now(), + duration, + easing + }; + + return easing; + } + + blur() { + this.reset(); + } + + reset() { + this._active = false; + } +} + +export default ScrollZoomHandler; diff --git a/node_modules/mapbox-gl/src/ui/handler/shim/dblclick_zoom.js b/node_modules/mapbox-gl/src/ui/handler/shim/dblclick_zoom.js new file mode 100644 index 0000000000000000000000000000000000000000..b63cfbada678bee026b1b8509b7b33174950dbb5 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/shim/dblclick_zoom.js @@ -0,0 +1,62 @@ +// @flow + +import type ClickZoomHandler from '../click_zoom'; +import type TapZoomHandler from './../tap_zoom'; + +/** + * The `DoubleClickZoomHandler` allows the user to zoom the map at a point by + * double clicking or double tapping. + */ +export default class DoubleClickZoomHandler { + + _clickZoom: ClickZoomHandler; + _tapZoom: TapZoomHandler; + + /** + * @private + */ + constructor(clickZoom: ClickZoomHandler, TapZoom: TapZoomHandler) { + this._clickZoom = clickZoom; + this._tapZoom = TapZoom; + } + + /** + * Enables the "double click to zoom" interaction. + * + * @example + * map.doubleClickZoom.enable(); + */ + enable() { + this._clickZoom.enable(); + this._tapZoom.enable(); + } + + /** + * Disables the "double click to zoom" interaction. + * + * @example + * map.doubleClickZoom.disable(); + */ + disable() { + this._clickZoom.disable(); + this._tapZoom.disable(); + } + + /** + * Returns a Boolean indicating whether the "double click to zoom" interaction is enabled. + * + * @returns {boolean} `true` if the "double click to zoom" interaction is enabled. + */ + isEnabled() { + return this._clickZoom.isEnabled() && this._tapZoom.isEnabled(); + } + + /** + * Returns a Boolean indicating whether the "double click to zoom" interaction is active, i.e. currently being used. + * + * @returns {boolean} `true` if the "double click to zoom" interaction is active. + */ + isActive() { + return this._clickZoom.isActive() || this._tapZoom.isActive(); + } +} diff --git a/node_modules/mapbox-gl/src/ui/handler/shim/drag_pan.js b/node_modules/mapbox-gl/src/ui/handler/shim/drag_pan.js new file mode 100644 index 0000000000000000000000000000000000000000..2b55e42539f44d88415e41cd582c1c3afd1f4e4d --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/shim/drag_pan.js @@ -0,0 +1,88 @@ +// @flow + +import type {MousePanHandler} from '../mouse'; +import type TouchPanHandler from './../touch_pan'; + +export type DragPanOptions = { + linearity?: number; + easing?: (t: number) => number; + deceleration?: number; + maxSpeed?: number; +}; + +/** + * The `DragPanHandler` allows the user to pan the map by clicking and dragging + * the cursor. + */ +export default class DragPanHandler { + + _el: HTMLElement; + _mousePan: MousePanHandler; + _touchPan: TouchPanHandler; + _inertiaOptions: DragPanOptions + + /** + * @private + */ + constructor(el: HTMLElement, mousePan: MousePanHandler, touchPan: TouchPanHandler) { + this._el = el; + this._mousePan = mousePan; + this._touchPan = touchPan; + } + + /** + * Enables the "drag to pan" interaction. + * + * @param {Object} [options] Options object + * @param {number} [options.linearity=0] factor used to scale the drag velocity + * @param {Function} [options.easing=bezier(0, 0, 0.3, 1)] easing function applled to `map.panTo` when applying the drag. + * @param {number} [options.maxSpeed=1400] the maximum value of the drag velocity. + * @param {number} [options.deceleration=2500] the rate at which the speed reduces after the pan ends. + * + * @example + * map.dragPan.enable(); + * @example + * map.dragPan.enable({ + * linearity: 0.3, + * easing: bezier(0, 0, 0.3, 1), + * maxSpeed: 1400, + * deceleration: 2500, + * }); + */ + enable(options?: DragPanOptions) { + this._inertiaOptions = options || {}; + this._mousePan.enable(); + this._touchPan.enable(); + this._el.classList.add('mapboxgl-touch-drag-pan'); + } + + /** + * Disables the "drag to pan" interaction. + * + * @example + * map.dragPan.disable(); + */ + disable() { + this._mousePan.disable(); + this._touchPan.disable(); + this._el.classList.remove('mapboxgl-touch-drag-pan'); + } + + /** + * Returns a Boolean indicating whether the "drag to pan" interaction is enabled. + * + * @returns {boolean} `true` if the "drag to pan" interaction is enabled. + */ + isEnabled() { + return this._mousePan.isEnabled() && this._touchPan.isEnabled(); + } + + /** + * Returns a Boolean indicating whether the "drag to pan" interaction is active, i.e. currently being used. + * + * @returns {boolean} `true` if the "drag to pan" interaction is active. + */ + isActive() { + return this._mousePan.isActive() || this._touchPan.isActive(); + } +} diff --git a/node_modules/mapbox-gl/src/ui/handler/shim/drag_rotate.js b/node_modules/mapbox-gl/src/ui/handler/shim/drag_rotate.js new file mode 100644 index 0000000000000000000000000000000000000000..22141fa5116fdd5848188bbccd304c72edf5b0e0 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/shim/drag_rotate.js @@ -0,0 +1,67 @@ +// @flow + +import type {MouseRotateHandler, MousePitchHandler} from '../mouse'; + +/** + * The `DragRotateHandler` allows the user to rotate the map by clicking and + * dragging the cursor while holding the right mouse button or `ctrl` key. + */ +export default class DragRotateHandler { + + _mouseRotate: MouseRotateHandler; + _mousePitch: MousePitchHandler; + _pitchWithRotate: boolean; + + /** + * @param {Object} [options] + * @param {number} [options.bearingSnap] The threshold, measured in degrees, that determines when the map's + * bearing will snap to north. + * @param {bool} [options.pitchWithRotate=true] Control the map pitch in addition to the bearing + * @private + */ + constructor(options: {pitchWithRotate: boolean}, mouseRotate: MouseRotateHandler, mousePitch: MousePitchHandler) { + this._pitchWithRotate = options.pitchWithRotate; + this._mouseRotate = mouseRotate; + this._mousePitch = mousePitch; + } + + /** + * Enables the "drag to rotate" interaction. + * + * @example + * map.dragRotate.enable(); + */ + enable() { + this._mouseRotate.enable(); + if (this._pitchWithRotate) this._mousePitch.enable(); + } + + /** + * Disables the "drag to rotate" interaction. + * + * @example + * map.dragRotate.disable(); + */ + disable() { + this._mouseRotate.disable(); + this._mousePitch.disable(); + } + + /** + * Returns a Boolean indicating whether the "drag to rotate" interaction is enabled. + * + * @returns {boolean} `true` if the "drag to rotate" interaction is enabled. + */ + isEnabled() { + return this._mouseRotate.isEnabled() && (!this._pitchWithRotate || this._mousePitch.isEnabled()); + } + + /** + * Returns a Boolean indicating whether the "drag to rotate" interaction is active, i.e. currently being used. + * + * @returns {boolean} `true` if the "drag to rotate" interaction is active. + */ + isActive() { + return this._mouseRotate.isActive() || this._mousePitch.isActive(); + } +} diff --git a/node_modules/mapbox-gl/src/ui/handler/shim/touch_zoom_rotate.js b/node_modules/mapbox-gl/src/ui/handler/shim/touch_zoom_rotate.js new file mode 100644 index 0000000000000000000000000000000000000000..b1cbe4ea7bd6eeb69f0c8e60a5ab8eb1df4f3091 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/shim/touch_zoom_rotate.js @@ -0,0 +1,108 @@ +// @flow + +import type {TouchZoomHandler, TouchRotateHandler} from '../touch_zoom_rotate'; +import type TapDragZoomHandler from '../tap_drag_zoom'; + +/** + * The `TouchZoomRotateHandler` allows the user to zoom and rotate the map by + * pinching on a touchscreen. + * + * They can zoom with one finger by double tapping and dragging. On the second tap, + * hold the finger down and drag up or down to zoom in or out. + */ +export default class TouchZoomRotateHandler { + + _el: HTMLElement; + _touchZoom: TouchZoomHandler; + _touchRotate: TouchRotateHandler; + _tapDragZoom: TapDragZoomHandler; + _rotationDisabled: boolean; + _enabled: boolean; + + /** + * @private + */ + constructor(el: HTMLElement, touchZoom: TouchZoomHandler, touchRotate: TouchRotateHandler, tapDragZoom: TapDragZoomHandler) { + this._el = el; + this._touchZoom = touchZoom; + this._touchRotate = touchRotate; + this._tapDragZoom = tapDragZoom; + this._rotationDisabled = false; + this._enabled = true; + } + + /** + * Enables the "pinch to rotate and zoom" interaction. + * + * @param {Object} [options] Options object. + * @param {string} [options.around] If "center" is passed, map will zoom around the center + * + * @example + * map.touchZoomRotate.enable(); + * @example + * map.touchZoomRotate.enable({ around: 'center' }); + */ + enable(options: ?{around?: 'center'}) { + this._touchZoom.enable(options); + if (!this._rotationDisabled) this._touchRotate.enable(options); + this._tapDragZoom.enable(); + this._el.classList.add('mapboxgl-touch-zoom-rotate'); + } + + /** + * Disables the "pinch to rotate and zoom" interaction. + * + * @example + * map.touchZoomRotate.disable(); + */ + disable() { + this._touchZoom.disable(); + this._touchRotate.disable(); + this._tapDragZoom.disable(); + this._el.classList.remove('mapboxgl-touch-zoom-rotate'); + } + + /** + * Returns a Boolean indicating whether the "pinch to rotate and zoom" interaction is enabled. + * + * @returns {boolean} `true` if the "pinch to rotate and zoom" interaction is enabled. + */ + isEnabled() { + return this._touchZoom.isEnabled() && + (this._rotationDisabled || this._touchRotate.isEnabled()) && + this._tapDragZoom.isEnabled(); + } + + /** + * Returns true if the handler is enabled and has detected the start of a zoom/rotate gesture. + * + * @returns {boolean} //eslint-disable-line + */ + isActive() { + return this._touchZoom.isActive() || this._touchRotate.isActive() || this._tapDragZoom.isActive(); + } + + /** + * Disables the "pinch to rotate" interaction, leaving the "pinch to zoom" + * interaction enabled. + * + * @example + * map.touchZoomRotate.disableRotation(); + */ + disableRotation() { + this._rotationDisabled = true; + this._touchRotate.disable(); + } + + /** + * Enables the "pinch to rotate" interaction. + * + * @example + * map.touchZoomRotate.enable(); + * map.touchZoomRotate.enableRotation(); + */ + enableRotation() { + this._rotationDisabled = false; + if (this._touchZoom.isEnabled()) this._touchRotate.enable(); + } +} diff --git a/node_modules/mapbox-gl/src/ui/handler/tap_drag_zoom.js b/node_modules/mapbox-gl/src/ui/handler/tap_drag_zoom.js new file mode 100644 index 0000000000000000000000000000000000000000..d8bf435a2c5414fd3d23653b1f439e004765e65a --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/tap_drag_zoom.js @@ -0,0 +1,103 @@ +// @flow + +import {TapRecognizer, MAX_TAP_INTERVAL} from './tap_recognizer'; +import type Point from '@mapbox/point-geometry'; + +export default class TapDragZoomHandler { + + _enabled: boolean; + _active: boolean; + _swipePoint: Point; + _swipeTouch: number; + _tapTime: number; + _tap: TapRecognizer; + + constructor() { + + this._tap = new TapRecognizer({ + numTouches: 1, + numTaps: 1 + }); + + this.reset(); + } + + reset() { + this._active = false; + delete this._swipePoint; + delete this._swipeTouch; + delete this._tapTime; + this._tap.reset(); + } + + touchstart(e: TouchEvent, points: Array, mapTouches: Array) { + if (this._swipePoint) return; + + if (this._tapTime && e.timeStamp - this._tapTime > MAX_TAP_INTERVAL) { + this.reset(); + } + + if (!this._tapTime) { + this._tap.touchstart(e, points, mapTouches); + } else if (mapTouches.length > 0) { + this._swipePoint = points[0]; + this._swipeTouch = mapTouches[0].identifier; + } + + } + + touchmove(e: TouchEvent, points: Array, mapTouches: Array) { + if (!this._tapTime) { + this._tap.touchmove(e, points, mapTouches); + } else if (this._swipePoint) { + if (mapTouches[0].identifier !== this._swipeTouch) { + return; + } + + const newSwipePoint = points[0]; + const dist = newSwipePoint.y - this._swipePoint.y; + this._swipePoint = newSwipePoint; + + e.preventDefault(); + this._active = true; + + return { + zoomDelta: dist / 128 + }; + } + } + + touchend(e: TouchEvent, points: Array, mapTouches: Array) { + if (!this._tapTime) { + const point = this._tap.touchend(e, points, mapTouches); + if (point) { + this._tapTime = e.timeStamp; + } + } else if (this._swipePoint) { + if (mapTouches.length === 0) { + this.reset(); + } + } + } + + touchcancel() { + this.reset(); + } + + enable() { + this._enabled = true; + } + + disable() { + this._enabled = false; + this.reset(); + } + + isEnabled() { + return this._enabled; + } + + isActive() { + return this._active; + } +} diff --git a/node_modules/mapbox-gl/src/ui/handler/tap_recognizer.js b/node_modules/mapbox-gl/src/ui/handler/tap_recognizer.js new file mode 100644 index 0000000000000000000000000000000000000000..01e9dee629e36fe61af590d5e45733518aa3fa13 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/tap_recognizer.js @@ -0,0 +1,133 @@ +// @flow + +import Point from '@mapbox/point-geometry'; +import {indexTouches} from './handler_util'; + +function getCentroid(points: Array) { + const sum = new Point(0, 0); + for (const point of points) { + sum._add(point); + } + return sum.div(points.length); +} + +export const MAX_TAP_INTERVAL = 500; +const MAX_TOUCH_TIME = 500; +const MAX_DIST = 30; + +export class SingleTapRecognizer { + + numTouches: number; + centroid: Point; + startTime: number; + aborted: boolean; + touches: { [number | string]: Point }; + + constructor(options: { numTouches: number }) { + this.reset(); + this.numTouches = options.numTouches; + } + + reset() { + delete this.centroid; + delete this.startTime; + delete this.touches; + this.aborted = false; + } + + touchstart(e: TouchEvent, points: Array, mapTouches: Array) { + + if (this.centroid || mapTouches.length > this.numTouches) { + this.aborted = true; + } + if (this.aborted) { + return; + } + + if (this.startTime === undefined) { + this.startTime = e.timeStamp; + } + + if (mapTouches.length === this.numTouches) { + this.centroid = getCentroid(points); + this.touches = indexTouches(mapTouches, points); + } + } + + touchmove(e: TouchEvent, points: Array, mapTouches: Array) { + if (this.aborted || !this.centroid) return; + + const newTouches = indexTouches(mapTouches, points); + for (const id in this.touches) { + const prevPos = this.touches[id]; + const pos = newTouches[id]; + if (!pos || pos.dist(prevPos) > MAX_DIST) { + this.aborted = true; + } + } + } + + touchend(e: TouchEvent, points: Array, mapTouches: Array) { + if (!this.centroid || e.timeStamp - this.startTime > MAX_TOUCH_TIME) { + this.aborted = true; + } + + if (mapTouches.length === 0) { + const centroid = !this.aborted && this.centroid; + this.reset(); + if (centroid) return centroid; + } + } + +} + +export class TapRecognizer { + + singleTap: SingleTapRecognizer; + numTaps: number; + lastTime: number; + lastTap: Point; + count: number; + + constructor(options: { numTaps: number, numTouches: number }) { + this.singleTap = new SingleTapRecognizer(options); + this.numTaps = options.numTaps; + this.reset(); + } + + reset() { + this.lastTime = Infinity; + delete this.lastTap; + this.count = 0; + this.singleTap.reset(); + } + + touchstart(e: TouchEvent, points: Array, mapTouches: Array) { + this.singleTap.touchstart(e, points, mapTouches); + } + + touchmove(e: TouchEvent, points: Array, mapTouches: Array) { + this.singleTap.touchmove(e, points, mapTouches); + } + + touchend(e: TouchEvent, points: Array, mapTouches: Array) { + const tap = this.singleTap.touchend(e, points, mapTouches); + if (tap) { + const soonEnough = e.timeStamp - this.lastTime < MAX_TAP_INTERVAL; + const closeEnough = !this.lastTap || this.lastTap.dist(tap) < MAX_DIST; + + if (!soonEnough || !closeEnough) { + this.reset(); + } + + this.count++; + this.lastTime = e.timeStamp; + this.lastTap = tap; + + if (this.count === this.numTaps) { + this.reset(); + return tap; + } + } + } +} diff --git a/node_modules/mapbox-gl/src/ui/handler/tap_zoom.js b/node_modules/mapbox-gl/src/ui/handler/tap_zoom.js new file mode 100644 index 0000000000000000000000000000000000000000..1aee59d1e8835320d0e01b1f6e191b167798b6e2 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/tap_zoom.js @@ -0,0 +1,93 @@ +// @flow + +import {TapRecognizer} from './tap_recognizer'; +import type Point from '@mapbox/point-geometry'; +import type Map from '../map'; + +export default class TapZoomHandler { + + _enabled: boolean; + _active: boolean; + _zoomIn: TapRecognizer; + _zoomOut: TapRecognizer; + + constructor() { + this._zoomIn = new TapRecognizer({ + numTouches: 1, + numTaps: 2 + }); + + this._zoomOut = new TapRecognizer({ + numTouches: 2, + numTaps: 1 + }); + + this.reset(); + } + + reset() { + this._active = false; + this._zoomIn.reset(); + this._zoomOut.reset(); + } + + touchstart(e: TouchEvent, points: Array, mapTouches: Array) { + this._zoomIn.touchstart(e, points, mapTouches); + this._zoomOut.touchstart(e, points, mapTouches); + } + + touchmove(e: TouchEvent, points: Array, mapTouches: Array) { + this._zoomIn.touchmove(e, points, mapTouches); + this._zoomOut.touchmove(e, points, mapTouches); + } + + touchend(e: TouchEvent, points: Array, mapTouches: Array) { + const zoomInPoint = this._zoomIn.touchend(e, points, mapTouches); + const zoomOutPoint = this._zoomOut.touchend(e, points, mapTouches); + + if (zoomInPoint) { + this._active = true; + e.preventDefault(); + setTimeout(() => this.reset(), 0); + return { + cameraAnimation: (map: Map) => map.easeTo({ + duration: 300, + zoom: map.getZoom() + 1, + around: map.unproject(zoomInPoint) + }, {originalEvent: e}) + }; + } else if (zoomOutPoint) { + this._active = true; + e.preventDefault(); + setTimeout(() => this.reset(), 0); + return { + cameraAnimation: (map: Map) => map.easeTo({ + duration: 300, + zoom: map.getZoom() - 1, + around: map.unproject(zoomOutPoint) + }, {originalEvent: e}) + }; + } + } + + touchcancel() { + this.reset(); + } + + enable() { + this._enabled = true; + } + + disable() { + this._enabled = false; + this.reset(); + } + + isEnabled() { + return this._enabled; + } + + isActive() { + return this._active; + } +} diff --git a/node_modules/mapbox-gl/src/ui/handler/touch_pan.js b/node_modules/mapbox-gl/src/ui/handler/touch_pan.js new file mode 100644 index 0000000000000000000000000000000000000000..6a879efb828143767a7bb3efc4166a76517045ca --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/touch_pan.js @@ -0,0 +1,101 @@ +// @flow + +import Point from '@mapbox/point-geometry'; +import {indexTouches} from './handler_util'; + +export default class TouchPanHandler { + + _enabled: boolean; + _active: boolean; + _touches: { [string | number]: Point }; + _minTouches: number; + _clickTolerance: number; + _sum: Point; + + constructor(options: { clickTolerance: number }) { + this._minTouches = 1; + this._clickTolerance = options.clickTolerance || 1; + this.reset(); + } + + reset() { + this._active = false; + this._touches = {}; + this._sum = new Point(0, 0); + } + + touchstart(e: TouchEvent, points: Array, mapTouches: Array) { + return this._calculateTransform(e, points, mapTouches); + } + + touchmove(e: TouchEvent, points: Array, mapTouches: Array) { + if (!this._active || mapTouches.length < this._minTouches) return; + e.preventDefault(); + return this._calculateTransform(e, points, mapTouches); + } + + touchend(e: TouchEvent, points: Array, mapTouches: Array) { + this._calculateTransform(e, points, mapTouches); + + if (this._active && mapTouches.length < this._minTouches) { + this.reset(); + } + } + + touchcancel() { + this.reset(); + } + + _calculateTransform(e: TouchEvent, points: Array, mapTouches: Array) { + if (mapTouches.length > 0) this._active = true; + + const touches = indexTouches(mapTouches, points); + + const touchPointSum = new Point(0, 0); + const touchDeltaSum = new Point(0, 0); + let touchDeltaCount = 0; + + for (const identifier in touches) { + const point = touches[identifier]; + const prevPoint = this._touches[identifier]; + if (prevPoint) { + touchPointSum._add(point); + touchDeltaSum._add(point.sub(prevPoint)); + touchDeltaCount++; + touches[identifier] = point; + } + } + + this._touches = touches; + + if (touchDeltaCount < this._minTouches || !touchDeltaSum.mag()) return; + + const panDelta = touchDeltaSum.div(touchDeltaCount); + this._sum._add(panDelta); + if (this._sum.mag() < this._clickTolerance) return; + + const around = touchPointSum.div(touchDeltaCount); + + return { + around, + panDelta + }; + } + + enable() { + this._enabled = true; + } + + disable() { + this._enabled = false; + this.reset(); + } + + isEnabled() { + return this._enabled; + } + + isActive() { + return this._active; + } +} diff --git a/node_modules/mapbox-gl/src/ui/handler/touch_zoom_rotate.js b/node_modules/mapbox-gl/src/ui/handler/touch_zoom_rotate.js new file mode 100644 index 0000000000000000000000000000000000000000..8e7b910c2058a65e9ad7167f90e69b0e5c92ee68 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler/touch_zoom_rotate.js @@ -0,0 +1,305 @@ +// @flow + +import Point from '@mapbox/point-geometry'; +import DOM from '../../util/dom'; + +class TwoTouchHandler { + + _enabled: boolean; + _active: boolean; + _firstTwoTouches: [number, number]; + _vector: Point; + _startVector: Point; + _aroundCenter: boolean; + + constructor() { + this.reset(); + } + + reset() { + this._active = false; + delete this._firstTwoTouches; + } + + _start(points: [Point, Point]) {} //eslint-disable-line + _move(points: [Point, Point], pinchAround: Point, e: TouchEvent) { return {}; } //eslint-disable-line + + touchstart(e: TouchEvent, points: Array, mapTouches: Array) { + //console.log(e.target, e.targetTouches.length ? e.targetTouches[0].target : null); + //log('touchstart', points, e.target.innerHTML, e.targetTouches.length ? e.targetTouches[0].target.innerHTML: undefined); + if (this._firstTwoTouches || mapTouches.length < 2) return; + + this._firstTwoTouches = [ + mapTouches[0].identifier, + mapTouches[1].identifier + ]; + + // implemented by child classes + this._start([points[0], points[1]]); + } + + touchmove(e: TouchEvent, points: Array, mapTouches: Array) { + if (!this._firstTwoTouches) return; + + e.preventDefault(); + + const [idA, idB] = this._firstTwoTouches; + const a = getTouchById(mapTouches, points, idA); + const b = getTouchById(mapTouches, points, idB); + if (!a || !b) return; + const pinchAround = this._aroundCenter ? null : a.add(b).div(2); + + // implemented by child classes + return this._move([a, b], pinchAround, e); + + } + + touchend(e: TouchEvent, points: Array, mapTouches: Array) { + if (!this._firstTwoTouches) return; + + const [idA, idB] = this._firstTwoTouches; + const a = getTouchById(mapTouches, points, idA); + const b = getTouchById(mapTouches, points, idB); + if (a && b) return; + + if (this._active) DOM.suppressClick(); + + this.reset(); + } + + touchcancel() { + this.reset(); + } + + enable(options: ?{around?: 'center'}) { + this._enabled = true; + this._aroundCenter = !!options && options.around === 'center'; + } + + disable() { + this._enabled = false; + this.reset(); + } + + isEnabled() { + return this._enabled; + } + + isActive() { + return this._active; + } +} + +function getTouchById(mapTouches: Array, points: Array, identifier: number) { + for (let i = 0; i < mapTouches.length; i++) { + if (mapTouches[i].identifier === identifier) return points[i]; + } +} + +/* ZOOM */ + +const ZOOM_THRESHOLD = 0.1; + +function getZoomDelta(distance, lastDistance) { + return Math.log(distance / lastDistance) / Math.LN2; +} + +export class TouchZoomHandler extends TwoTouchHandler { + + _distance: number; + _startDistance: number; + + reset() { + super.reset(); + delete this._distance; + delete this._startDistance; + } + + _start(points: [Point, Point]) { + this._startDistance = this._distance = points[0].dist(points[1]); + } + + _move(points: [Point, Point], pinchAround: Point) { + const lastDistance = this._distance; + this._distance = points[0].dist(points[1]); + if (!this._active && Math.abs(getZoomDelta(this._distance, this._startDistance)) < ZOOM_THRESHOLD) return; + this._active = true; + return { + zoomDelta: getZoomDelta(this._distance, lastDistance), + pinchAround + }; + } +} + +/* ROTATE */ + +const ROTATION_THRESHOLD = 25; // pixels along circumference of touch circle + +function getBearingDelta(a, b) { + return a.angleWith(b) * 180 / Math.PI; +} + +export class TouchRotateHandler extends TwoTouchHandler { + _minDiameter: number; + + reset() { + super.reset(); + delete this._minDiameter; + delete this._startVector; + delete this._vector; + } + + _start(points: [Point, Point]) { + this._startVector = this._vector = points[0].sub(points[1]); + this._minDiameter = points[0].dist(points[1]); + } + + _move(points: [Point, Point], pinchAround: Point) { + const lastVector = this._vector; + this._vector = points[0].sub(points[1]); + + if (!this._active && this._isBelowThreshold(this._vector)) return; + this._active = true; + + return { + bearingDelta: getBearingDelta(this._vector, lastVector), + pinchAround + }; + } + + _isBelowThreshold(vector: Point) { + /* + * The threshold before a rotation actually happens is configured in + * pixels alongth circumference of the circle formed by the two fingers. + * This makes the threshold in degrees larger when the fingers are close + * together and smaller when the fingers are far apart. + * + * Use the smallest diameter from the whole gesture to reduce sensitivity + * when pinching in and out. + */ + + this._minDiameter = Math.min(this._minDiameter, vector.mag()); + const circumference = Math.PI * this._minDiameter; + const threshold = ROTATION_THRESHOLD / circumference * 360; + + const bearingDeltaSinceStart = getBearingDelta(vector, this._startVector); + return Math.abs(bearingDeltaSinceStart) < threshold; + } +} + +/* PITCH */ + +function isVertical(vector) { + return Math.abs(vector.y) > Math.abs(vector.x); +} + +const ALLOWED_SINGLE_TOUCH_TIME = 100; + +/** + * The `TouchPitchHandler` allows the user to pitch the map by dragging up and down with two fingers. + */ +export class TouchPitchHandler extends TwoTouchHandler { + + _valid: boolean | void; + _firstMove: number; + _lastPoints: [Point, Point]; + + reset() { + super.reset(); + this._valid = undefined; + delete this._firstMove; + delete this._lastPoints; + } + + _start(points: [Point, Point]) { + this._lastPoints = points; + if (isVertical(points[0].sub(points[1]))) { + // fingers are more horizontal than vertical + this._valid = false; + + } + } + + _move(points: [Point, Point], center: Point, e: TouchEvent) { + const vectorA = points[0].sub(this._lastPoints[0]); + const vectorB = points[1].sub(this._lastPoints[1]); + + this._valid = this.gestureBeginsVertically(vectorA, vectorB, e.timeStamp); + if (!this._valid) return; + + this._lastPoints = points; + this._active = true; + const yDeltaAverage = (vectorA.y + vectorB.y) / 2; + const degreesPerPixelMoved = -0.5; + return { + pitchDelta: yDeltaAverage * degreesPerPixelMoved + }; + } + + gestureBeginsVertically(vectorA: Point, vectorB: Point, timeStamp: number) { + if (this._valid !== undefined) return this._valid; + + const threshold = 2; + const movedA = vectorA.mag() >= threshold; + const movedB = vectorB.mag() >= threshold; + + // neither finger has moved a meaningful amount, wait + if (!movedA && !movedB) return; + + // One finger has moved and the other has not. + // If enough time has passed, decide it is not a pitch. + if (!movedA || !movedB) { + if (this._firstMove === undefined) { + this._firstMove = timeStamp; + } + + if (timeStamp - this._firstMove < ALLOWED_SINGLE_TOUCH_TIME) { + // still waiting for a movement from the second finger + return undefined; + } else { + return false; + } + } + + const isSameDirection = vectorA.y > 0 === vectorB.y > 0; + return isVertical(vectorA) && isVertical(vectorB) && isSameDirection; + } + + /** + * Returns a Boolean indicating whether the "drag to pitch" interaction is enabled. + * + * @memberof TouchPitchHandler + * @name isEnabled + * @instance + * @returns {boolean} `true` if the "drag to pitch" interaction is enabled. + */ + + /** + * Returns a Boolean indicating whether the "drag to pitch" interaction is active, i.e. currently being used. + * + * @memberof TouchPitchHandler + * @name isActive + * @instance + * @returns {boolean} `true` if the "drag to pitch" interaction is active. + */ + + /** + * Enables the "drag to pitch" interaction. + * + * @memberof TouchPitchHandler + * @name enable + * @instance + * @example + * map.touchPitch.enable(); + */ + + /** + * Disables the "drag to pitch" interaction. + * + * @memberof TouchPitchHandler + * @name disable + * @instance + * @example + * map.touchPitch.disable(); + */ +} diff --git a/node_modules/mapbox-gl/src/ui/handler_inertia.js b/node_modules/mapbox-gl/src/ui/handler_inertia.js new file mode 100644 index 0000000000000000000000000000000000000000..7c3fc13dfca4217ac111098a81c501ab6ba3f64a --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler_inertia.js @@ -0,0 +1,158 @@ +// @flow + +import browser from '../util/browser'; +import type Map from './map'; +import {bezier, clamp, extend} from '../util/util'; +import Point from '@mapbox/point-geometry'; +import type {DragPanOptions} from './handler/shim/drag_pan'; + +const defaultInertiaOptions = { + linearity: 0.3, + easing: bezier(0, 0, 0.3, 1), +}; + +const defaultPanInertiaOptions = extend({ + deceleration: 2500, + maxSpeed: 1400 +}, defaultInertiaOptions); + +const defaultZoomInertiaOptions = extend({ + deceleration: 20, + maxSpeed: 1400 +}, defaultInertiaOptions); + +const defaultBearingInertiaOptions = extend({ + deceleration: 1000, + maxSpeed: 360 +}, defaultInertiaOptions); + +const defaultPitchInertiaOptions = extend({ + deceleration: 1000, + maxSpeed: 90 +}, defaultInertiaOptions); + +export type InertiaOptions = { + linearity: number; + easing: (t: number) => number; + deceleration: number; + maxSpeed: number; +}; + +export type InputEvent = MouseEvent | TouchEvent | KeyboardEvent | WheelEvent; + +export default class HandlerInertia { + _map: Map; + _inertiaBuffer: Array<{ time: number, settings: Object }>; + + constructor(map: Map) { + this._map = map; + this.clear(); + } + + clear() { + this._inertiaBuffer = []; + } + + record(settings: any) { + this._drainInertiaBuffer(); + this._inertiaBuffer.push({time: browser.now(), settings}); + } + + _drainInertiaBuffer() { + const inertia = this._inertiaBuffer, + now = browser.now(), + cutoff = 160; //msec + + while (inertia.length > 0 && now - inertia[0].time > cutoff) + inertia.shift(); + } + + _onMoveEnd(panInertiaOptions?: DragPanOptions) { + this._drainInertiaBuffer(); + if (this._inertiaBuffer.length < 2) { + return; + } + + const deltas = { + zoom: 0, + bearing: 0, + pitch: 0, + pan: new Point(0, 0), + pinchAround: undefined, + around: undefined + }; + + for (const {settings} of this._inertiaBuffer) { + deltas.zoom += settings.zoomDelta || 0; + deltas.bearing += settings.bearingDelta || 0; + deltas.pitch += settings.pitchDelta || 0; + if (settings.panDelta) deltas.pan._add(settings.panDelta); + if (settings.around) deltas.around = settings.around; + if (settings.pinchAround) deltas.pinchAround = settings.pinchAround; + } + + const lastEntry = this._inertiaBuffer[this._inertiaBuffer.length - 1]; + const duration = (lastEntry.time - this._inertiaBuffer[0].time); + + const easeOptions = {}; + + if (deltas.pan.mag()) { + const result = calculateEasing(deltas.pan.mag(), duration, extend({}, defaultPanInertiaOptions, panInertiaOptions || {})); + easeOptions.offset = deltas.pan.mult(result.amount / deltas.pan.mag()); + easeOptions.center = this._map.transform.center; + extendDuration(easeOptions, result); + } + + if (deltas.zoom) { + const result = calculateEasing(deltas.zoom, duration, defaultZoomInertiaOptions); + easeOptions.zoom = this._map.transform.zoom + result.amount; + extendDuration(easeOptions, result); + } + + if (deltas.bearing) { + const result = calculateEasing(deltas.bearing, duration, defaultBearingInertiaOptions); + easeOptions.bearing = this._map.transform.bearing + clamp(result.amount, -179, 179); + extendDuration(easeOptions, result); + } + + if (deltas.pitch) { + const result = calculateEasing(deltas.pitch, duration, defaultPitchInertiaOptions); + easeOptions.pitch = this._map.transform.pitch + result.amount; + extendDuration(easeOptions, result); + } + + if (easeOptions.zoom || easeOptions.bearing) { + const last = deltas.pinchAround === undefined ? deltas.around : deltas.pinchAround; + easeOptions.around = last ? this._map.unproject(last) : this._map.getCenter(); + } + + this.clear(); + return extend(easeOptions, { + noMoveStart: true + }); + + } +} + +// Unfortunately zoom, bearing, etc can't have different durations and easings so +// we need to choose one. We use the longest duration and it's corresponding easing. +function extendDuration(easeOptions, result) { + if (!easeOptions.duration || easeOptions.duration < result.duration) { + easeOptions.duration = result.duration; + easeOptions.easing = result.easing; + } +} + +function calculateEasing(amount, inertiaDuration: number, inertiaOptions) { + const {maxSpeed, linearity, deceleration} = inertiaOptions; + const speed = clamp( + amount * linearity / (inertiaDuration / 1000), + -maxSpeed, + maxSpeed); + const duration = Math.abs(speed) / (deceleration * linearity); + return { + easing: inertiaOptions.easing, + duration: duration * 1000, + amount: speed * (duration / 2) + }; +} diff --git a/node_modules/mapbox-gl/src/ui/handler_manager.js b/node_modules/mapbox-gl/src/ui/handler_manager.js new file mode 100644 index 0000000000000000000000000000000000000000..4b4d2d9f04692e1f866b426c25a10e4a6d92c5ca --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/handler_manager.js @@ -0,0 +1,531 @@ +// @flow + +import {Event} from '../util/evented'; +import DOM from '../util/dom'; +import type Map from './map'; +import HandlerInertia from './handler_inertia'; +import {MapEventHandler, BlockableMapEventHandler} from './handler/map_event'; +import BoxZoomHandler from './handler/box_zoom'; +import TapZoomHandler from './handler/tap_zoom'; +import {MousePanHandler, MouseRotateHandler, MousePitchHandler} from './handler/mouse'; +import TouchPanHandler from './handler/touch_pan'; +import {TouchZoomHandler, TouchRotateHandler, TouchPitchHandler} from './handler/touch_zoom_rotate'; +import KeyboardHandler from './handler/keyboard'; +import ScrollZoomHandler from './handler/scroll_zoom'; +import DoubleClickZoomHandler from './handler/shim/dblclick_zoom'; +import ClickZoomHandler from './handler/click_zoom'; +import TapDragZoomHandler from './handler/tap_drag_zoom'; +import DragPanHandler from './handler/shim/drag_pan'; +import DragRotateHandler from './handler/shim/drag_rotate'; +import TouchZoomRotateHandler from './handler/shim/touch_zoom_rotate'; +import {bindAll, extend} from '../util/util'; +import window from '../util/window'; +import Point from '@mapbox/point-geometry'; +import assert from 'assert'; + +export type InputEvent = MouseEvent | TouchEvent | KeyboardEvent | WheelEvent; + +const isMoving = p => p.zoom || p.drag || p.pitch || p.rotate; + +class RenderFrameEvent extends Event { + type: 'renderFrame'; + timeStamp: number; +} + +// Handlers interpret dom events and return camera changes that should be +// applied to the map (`HandlerResult`s). The camera changes are all deltas. +// The handler itself should have no knowledge of the map's current state. +// This makes it easier to merge multiple results and keeps handlers simpler. +// For example, if there is a mousedown and mousemove, the mousePan handler +// would return a `panDelta` on the mousemove. +export interface Handler { + enable(): void; + disable(): void; + isEnabled(): boolean; + isActive(): boolean; + + // `reset` can be called by the manager at any time and must reset everything to it's original state + reset(): void; + + // Handlers can optionally implement these methods. + // They are called with dom events whenever those dom evens are received. + +touchstart?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void; + +touchmove?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void; + +touchend?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void; + +touchcancel?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void; + +mousedown?: (e: MouseEvent, point: Point) => HandlerResult | void; + +mousemove?: (e: MouseEvent, point: Point) => HandlerResult | void; + +mouseup?: (e: MouseEvent, point: Point) => HandlerResult | void; + +dblclick?: (e: MouseEvent, point: Point) => HandlerResult | void; + +wheel?: (e: WheelEvent, point: Point) => HandlerResult | void; + +keydown?: (e: KeyboardEvent) => HandlerResult | void; + +keyup?: (e: KeyboardEvent) => HandlerResult | void; + + // `renderFrame` is the only non-dom event. It is called during render + // frames and can be used to smooth camera changes (see scroll handler). + +renderFrame?: () => HandlerResult | void; +} + +// All handler methods that are called with events can optionally return a `HandlerResult`. +export type HandlerResult = {| + panDelta?: Point, + zoomDelta?: number, + bearingDelta?: number, + pitchDelta?: number, + // the point to not move when changing the camera + around?: Point | null, + // same as above, except for pinch actions, which are given higher priority + pinchAround?: Point | null, + // A method that can fire a one-off easing by directly changing the map's camera. + cameraAnimation?: (map: Map) => any; + + // The last three properties are needed by only one handler: scrollzoom. + // The DOM event to be used as the `originalEvent` on any camera change events. + originalEvent?: any, + // Makes the manager trigger a frame, allowing the handler to return multiple results over time (see scrollzoom). + needsRenderFrame?: boolean, + // The camera changes won't get recorded for inertial zooming. + noInertia?: boolean +|}; + +function hasChange(result: HandlerResult) { + return (result.panDelta && result.panDelta.mag()) || result.zoomDelta || result.bearingDelta || result.pitchDelta; +} + +class HandlerManager { + _map: Map; + _el: HTMLElement; + _handlers: Array<{ handlerName: string, handler: Handler, allowed: any }>; + _eventsInProgress: Object; + _frameId: number; + _inertia: HandlerInertia; + _bearingSnap: number; + _handlersById: { [string]: Handler }; + _updatingCamera: boolean; + _changes: Array<[HandlerResult, Object, any]>; + _previousActiveHandlers: { [string]: Handler }; + _listeners: Array<[HTMLElement, string, void | {passive?: boolean, capture?: boolean}]>; + + constructor(map: Map, options: { interactive: boolean, pitchWithRotate: boolean, clickTolerance: number, bearingSnap: number}) { + this._map = map; + this._el = this._map.getCanvasContainer(); + this._handlers = []; + this._handlersById = {}; + this._changes = []; + + this._inertia = new HandlerInertia(map); + this._bearingSnap = options.bearingSnap; + this._previousActiveHandlers = {}; + + // Track whether map is currently moving, to compute start/move/end events + this._eventsInProgress = {}; + + this._addDefaultHandlers(options); + + bindAll(['handleEvent', 'handleWindowEvent'], this); + + const el = this._el; + + this._listeners = [ + // This needs to be `passive: true` so that a double tap fires two + // pairs of touchstart/end events in iOS Safari 13. If this is set to + // `passive: false` then the second pair of events is only fired if + // preventDefault() is called on the first touchstart. Calling preventDefault() + // undesirably prevents click events. + [el, 'touchstart', {passive: true}], + // This needs to be `passive: false` so that scrolls and pinches can be + // prevented in browsers that don't support `touch-actions: none`, for example iOS Safari 12. + [el, 'touchmove', {passive: false}], + [el, 'touchend', undefined], + [el, 'touchcancel', undefined], + + [el, 'mousedown', undefined], + [el, 'mousemove', undefined], + [el, 'mouseup', undefined], + + // Bind window-level event listeners for move and up/end events. In the absence of + // the pointer capture API, which is not supported by all necessary platforms, + // window-level event listeners give us the best shot at capturing events that + // fall outside the map canvas element. Use `{capture: true}` for the move event + // to prevent map move events from being fired during a drag. + [window.document, 'mousemove', {capture: true}], + [window.document, 'mouseup', undefined], + + [el, 'mouseover', undefined], + [el, 'mouseout', undefined], + [el, 'dblclick', undefined], + [el, 'click', undefined], + + [el, 'keydown', {capture: false}], + [el, 'keyup', undefined], + + [el, 'wheel', {passive: false}], + [el, 'contextmenu', undefined], + + [window, 'blur', undefined] + ]; + + for (const [target, type, listenerOptions] of this._listeners) { + DOM.addEventListener(target, type, target === window.document ? this.handleWindowEvent : this.handleEvent, listenerOptions); + } + } + + destroy() { + for (const [target, type, listenerOptions] of this._listeners) { + DOM.removeEventListener(target, type, target === window.document ? this.handleWindowEvent : this.handleEvent, listenerOptions); + } + } + + _addDefaultHandlers(options: { interactive: boolean, pitchWithRotate: boolean, clickTolerance: number }) { + const map = this._map; + const el = map.getCanvasContainer(); + this._add('mapEvent', new MapEventHandler(map, options)); + + const boxZoom = map.boxZoom = new BoxZoomHandler(map, options); + this._add('boxZoom', boxZoom); + + const tapZoom = new TapZoomHandler(); + const clickZoom = new ClickZoomHandler(); + map.doubleClickZoom = new DoubleClickZoomHandler(clickZoom, tapZoom); + this._add('tapZoom', tapZoom); + this._add('clickZoom', clickZoom); + + const tapDragZoom = new TapDragZoomHandler(); + this._add('tapDragZoom', tapDragZoom); + + const touchPitch = map.touchPitch = new TouchPitchHandler(); + this._add('touchPitch', touchPitch); + + const mouseRotate = new MouseRotateHandler(options); + const mousePitch = new MousePitchHandler(options); + map.dragRotate = new DragRotateHandler(options, mouseRotate, mousePitch); + this._add('mouseRotate', mouseRotate, ['mousePitch']); + this._add('mousePitch', mousePitch, ['mouseRotate']); + + const mousePan = new MousePanHandler(options); + const touchPan = new TouchPanHandler(options); + map.dragPan = new DragPanHandler(el, mousePan, touchPan); + this._add('mousePan', mousePan); + this._add('touchPan', touchPan, ['touchZoom', 'touchRotate']); + + const touchRotate = new TouchRotateHandler(); + const touchZoom = new TouchZoomHandler(); + map.touchZoomRotate = new TouchZoomRotateHandler(el, touchZoom, touchRotate, tapDragZoom); + this._add('touchRotate', touchRotate, ['touchPan', 'touchZoom']); + this._add('touchZoom', touchZoom, ['touchPan', 'touchRotate']); + + const scrollZoom = map.scrollZoom = new ScrollZoomHandler(map, this); + this._add('scrollZoom', scrollZoom, ['mousePan']); + + const keyboard = map.keyboard = new KeyboardHandler(); + this._add('keyboard', keyboard); + + this._add('blockableMapEvent', new BlockableMapEventHandler(map)); + + for (const name of ['boxZoom', 'doubleClickZoom', 'tapDragZoom', 'touchPitch', 'dragRotate', 'dragPan', 'touchZoomRotate', 'scrollZoom', 'keyboard']) { + if (options.interactive && (options: any)[name]) { + (map: any)[name].enable((options: any)[name]); + } + } + } + + _add(handlerName: string, handler: Handler, allowed?: Array) { + this._handlers.push({handlerName, handler, allowed}); + this._handlersById[handlerName] = handler; + } + + stop(allowEndAnimation: boolean) { + // do nothing if this method was triggered by a gesture update + if (this._updatingCamera) return; + + for (const {handler} of this._handlers) { + handler.reset(); + } + this._inertia.clear(); + this._fireEvents({}, {}, allowEndAnimation); + this._changes = []; + } + + isActive() { + for (const {handler} of this._handlers) { + if (handler.isActive()) return true; + } + return false; + } + + isZooming() { + return !!this._eventsInProgress.zoom || this._map.scrollZoom.isZooming(); + } + isRotating() { + return !!this._eventsInProgress.rotate; + } + + isMoving() { + return Boolean(isMoving(this._eventsInProgress)) || this.isZooming(); + } + + _blockedByActive(activeHandlers: { [string]: Handler }, allowed: Array, myName: string) { + for (const name in activeHandlers) { + if (name === myName) continue; + if (!allowed || allowed.indexOf(name) < 0) { + return true; + } + } + return false; + } + + handleWindowEvent(e: InputEvent) { + this.handleEvent(e, `${e.type}Window`); + } + + _getMapTouches(touches: TouchList) { + const mapTouches = []; + for (const t of touches) { + const target = ((t.target: any): Node); + if (this._el.contains(target)) { + mapTouches.push(t); + } + } + return ((mapTouches: any): TouchList); + } + + handleEvent(e: InputEvent | RenderFrameEvent, eventName?: string) { + + this._updatingCamera = true; + assert(e.timeStamp !== undefined); + + const inputEvent = e.type === 'renderFrame' ? undefined : ((e: any): InputEvent); + + /* + * We don't call e.preventDefault() for any events by default. + * Handlers are responsible for calling it where necessary. + */ + + const mergedHandlerResult: HandlerResult = {needsRenderFrame: false}; + const eventsInProgress = {}; + const activeHandlers = {}; + + const mapTouches = e.touches ? this._getMapTouches(((e: any): TouchEvent).touches) : undefined; + const points = mapTouches ? DOM.touchPos(this._el, mapTouches) : DOM.mousePos(this._el, ((e: any): MouseEvent)); + + for (const {handlerName, handler, allowed} of this._handlers) { + if (!handler.isEnabled()) continue; + + let data: HandlerResult | void; + if (this._blockedByActive(activeHandlers, allowed, handlerName)) { + handler.reset(); + + } else { + if ((handler: any)[eventName || e.type]) { + data = (handler: any)[eventName || e.type](e, points, mapTouches); + this.mergeHandlerResult(mergedHandlerResult, eventsInProgress, data, handlerName, inputEvent); + if (data && data.needsRenderFrame) { + this._triggerRenderFrame(); + } + } + } + + if (data || handler.isActive()) { + activeHandlers[handlerName] = handler; + } + } + + const deactivatedHandlers = {}; + for (const name in this._previousActiveHandlers) { + if (!activeHandlers[name]) { + deactivatedHandlers[name] = inputEvent; + } + } + this._previousActiveHandlers = activeHandlers; + + if (Object.keys(deactivatedHandlers).length || hasChange(mergedHandlerResult)) { + this._changes.push([mergedHandlerResult, eventsInProgress, deactivatedHandlers]); + this._triggerRenderFrame(); + } + + if (Object.keys(activeHandlers).length || hasChange(mergedHandlerResult)) { + this._map._stop(true); + } + + this._updatingCamera = false; + + const {cameraAnimation} = mergedHandlerResult; + if (cameraAnimation) { + this._inertia.clear(); + this._fireEvents({}, {}, true); + this._changes = []; + cameraAnimation(this._map); + } + } + + mergeHandlerResult(mergedHandlerResult: HandlerResult, eventsInProgress: Object, handlerResult: HandlerResult, name: string, e?: InputEvent) { + if (!handlerResult) return; + + extend(mergedHandlerResult, handlerResult); + + const eventData = {handlerName: name, originalEvent: handlerResult.originalEvent || e}; + + // track which handler changed which camera property + if (handlerResult.zoomDelta !== undefined) { + eventsInProgress.zoom = eventData; + } + if (handlerResult.panDelta !== undefined) { + eventsInProgress.drag = eventData; + } + if (handlerResult.pitchDelta !== undefined) { + eventsInProgress.pitch = eventData; + } + if (handlerResult.bearingDelta !== undefined) { + eventsInProgress.rotate = eventData; + } + + } + + _applyChanges() { + const combined = {}; + const combinedEventsInProgress = {}; + const combinedDeactivatedHandlers = {}; + + for (const [change, eventsInProgress, deactivatedHandlers] of this._changes) { + + if (change.panDelta) combined.panDelta = (combined.panDelta || new Point(0, 0))._add(change.panDelta); + if (change.zoomDelta) combined.zoomDelta = (combined.zoomDelta || 0) + change.zoomDelta; + if (change.bearingDelta) combined.bearingDelta = (combined.bearingDelta || 0) + change.bearingDelta; + if (change.pitchDelta) combined.pitchDelta = (combined.pitchDelta || 0) + change.pitchDelta; + if (change.around !== undefined) combined.around = change.around; + if (change.pinchAround !== undefined) combined.pinchAround = change.pinchAround; + if (change.noInertia) combined.noInertia = change.noInertia; + + extend(combinedEventsInProgress, eventsInProgress); + extend(combinedDeactivatedHandlers, deactivatedHandlers); + } + + this._updateMapTransform(combined, combinedEventsInProgress, combinedDeactivatedHandlers); + this._changes = []; + } + + _updateMapTransform(combinedResult: any, combinedEventsInProgress: Object, deactivatedHandlers: Object) { + + const map = this._map; + const tr = map.transform; + + if (!hasChange(combinedResult)) { + return this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true); + } + + let {panDelta, zoomDelta, bearingDelta, pitchDelta, around, pinchAround} = combinedResult; + + if (pinchAround !== undefined) { + around = pinchAround; + } + + // stop any ongoing camera animations (easeTo, flyTo) + map._stop(true); + + around = around || map.transform.centerPoint; + const loc = tr.pointLocation(panDelta ? around.sub(panDelta) : around); + if (bearingDelta) tr.bearing += bearingDelta; + if (pitchDelta) tr.pitch += pitchDelta; + if (zoomDelta) tr.zoom += zoomDelta; + tr.setLocationAtPoint(loc, around); + + this._map._update(); + if (!combinedResult.noInertia) this._inertia.record(combinedResult); + this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true); + + } + + _fireEvents(newEventsInProgress: { [string]: Object }, deactivatedHandlers: Object, allowEndAnimation: boolean) { + + const wasMoving = isMoving(this._eventsInProgress); + const nowMoving = isMoving(newEventsInProgress); + + const startEvents = {}; + + for (const eventName in newEventsInProgress) { + const {originalEvent} = newEventsInProgress[eventName]; + if (!this._eventsInProgress[eventName]) { + startEvents[`${eventName}start`] = originalEvent; + } + this._eventsInProgress[eventName] = newEventsInProgress[eventName]; + } + + // fire start events only after this._eventsInProgress has been updated + if (!wasMoving && nowMoving) { + this._fireEvent('movestart', nowMoving.originalEvent); + } + + for (const name in startEvents) { + this._fireEvent(name, startEvents[name]); + } + + if (nowMoving) { + this._fireEvent('move', nowMoving.originalEvent); + } + + for (const eventName in newEventsInProgress) { + const {originalEvent} = newEventsInProgress[eventName]; + this._fireEvent(eventName, originalEvent); + } + + const endEvents = {}; + + let originalEndEvent; + for (const eventName in this._eventsInProgress) { + const {handlerName, originalEvent} = this._eventsInProgress[eventName]; + if (!this._handlersById[handlerName].isActive()) { + delete this._eventsInProgress[eventName]; + originalEndEvent = deactivatedHandlers[handlerName] || originalEvent; + endEvents[`${eventName}end`] = originalEndEvent; + } + } + + for (const name in endEvents) { + this._fireEvent(name, endEvents[name]); + } + + const stillMoving = isMoving(this._eventsInProgress); + if (allowEndAnimation && (wasMoving || nowMoving) && !stillMoving) { + this._updatingCamera = true; + const inertialEase = this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions); + + const shouldSnapToNorth = bearing => bearing !== 0 && -this._bearingSnap < bearing && bearing < this._bearingSnap; + + if (inertialEase) { + if (shouldSnapToNorth(inertialEase.bearing || this._map.getBearing())) { + inertialEase.bearing = 0; + } + this._map.easeTo(inertialEase, {originalEvent: originalEndEvent}); + } else { + this._map.fire(new Event('moveend', {originalEvent: originalEndEvent})); + if (shouldSnapToNorth(this._map.getBearing())) { + this._map.resetNorth(); + } + } + this._updatingCamera = false; + } + + } + + _fireEvent(type: string, e: *) { + this._map.fire(new Event(type, e ? {originalEvent: e} : {})); + } + + _requestFrame() { + this._map.triggerRepaint(); + return this._map._renderTaskQueue.add(timeStamp => { + delete this._frameId; + this.handleEvent(new RenderFrameEvent('renderFrame', {timeStamp})); + this._applyChanges(); + }); + } + + _triggerRenderFrame() { + if (this._frameId === undefined) { + this._frameId = this._requestFrame(); + } + } + +} + +export default HandlerManager; diff --git a/node_modules/mapbox-gl/src/ui/hash.js b/node_modules/mapbox-gl/src/ui/hash.js new file mode 100644 index 0000000000000000000000000000000000000000..82d98153b518626c241309031d8e415d955c5e41 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/hash.js @@ -0,0 +1,148 @@ +// @flow + +import {bindAll} from '../util/util'; +import window from '../util/window'; +import throttle from '../util/throttle'; + +import type Map from './map'; + +/* + * Adds the map's position to its page's location hash. + * Passed as an option to the map object. + * + * @returns {Hash} `this` + */ +class Hash { + _map: Map; + _updateHash: () => ?TimeoutID; + _hashName: ?string; + + constructor(hashName: ?string) { + this._hashName = hashName && encodeURIComponent(hashName); + bindAll([ + '_getCurrentHash', + '_onHashChange', + '_updateHash' + ], this); + + // Mobile Safari doesn't allow updating the hash more than 100 times per 30 seconds. + this._updateHash = throttle(this._updateHashUnthrottled.bind(this), 30 * 1000 / 100); + } + + /* + * Map element to listen for coordinate changes + * + * @param {Object} map + * @returns {Hash} `this` + */ + addTo(map: Map) { + this._map = map; + window.addEventListener('hashchange', this._onHashChange, false); + this._map.on('moveend', this._updateHash); + return this; + } + + /* + * Removes hash + * + * @returns {Popup} `this` + */ + remove() { + window.removeEventListener('hashchange', this._onHashChange, false); + this._map.off('moveend', this._updateHash); + clearTimeout(this._updateHash()); + + delete this._map; + return this; + } + + getHashString(mapFeedback?: boolean) { + const center = this._map.getCenter(), + zoom = Math.round(this._map.getZoom() * 100) / 100, + // derived from equation: 512px * 2^z / 360 / 10^d < 0.5px + precision = Math.ceil((zoom * Math.LN2 + Math.log(512 / 360 / 0.5)) / Math.LN10), + m = Math.pow(10, precision), + lng = Math.round(center.lng * m) / m, + lat = Math.round(center.lat * m) / m, + bearing = this._map.getBearing(), + pitch = this._map.getPitch(); + let hash = ''; + if (mapFeedback) { + // new map feedback site has some constraints that don't allow + // us to use the same hash format as we do for the Map hash option. + hash += `/${lng}/${lat}/${zoom}`; + } else { + hash += `${zoom}/${lat}/${lng}`; + } + + if (bearing || pitch) hash += (`/${Math.round(bearing * 10) / 10}`); + if (pitch) hash += (`/${Math.round(pitch)}`); + + if (this._hashName) { + const hashName = this._hashName; + let found = false; + const parts = window.location.hash.slice(1).split('&').map(part => { + const key = part.split('=')[0]; + if (key === hashName) { + found = true; + return `${key}=${hash}`; + } + return part; + }).filter(a => a); + if (!found) { + parts.push(`${hashName}=${hash}`); + } + return `#${parts.join('&')}`; + } + + return `#${hash}`; + } + + _getCurrentHash() { + // Get the current hash from location, stripped from its number sign + const hash = window.location.hash.replace('#', ''); + if (this._hashName) { + // Split the parameter-styled hash into parts and find the value we need + let keyval; + hash.split('&').map( + part => part.split('=') + ).forEach(part => { + if (part[0] === this._hashName) { + keyval = part; + } + }); + return (keyval ? keyval[1] || '' : '').split('/'); + } + return hash.split('/'); + } + + _onHashChange() { + const loc = this._getCurrentHash(); + if (loc.length >= 3 && !loc.some(v => isNaN(v))) { + const bearing = this._map.dragRotate.isEnabled() && this._map.touchZoomRotate.isEnabled() ? +(loc[3] || 0) : this._map.getBearing(); + this._map.jumpTo({ + center: [+loc[2], +loc[1]], + zoom: +loc[0], + bearing, + pitch: +(loc[4] || 0) + }); + return true; + } + return false; + } + + _updateHashUnthrottled() { + // Replace if already present, else append the updated hash string + const location = window.location.href.replace(/(#.+)?$/, this.getHashString()); + try { + window.history.replaceState(window.history.state, null, location); + } catch (SecurityError) { + // IE11 does not allow this if the page is within an iframe created + // with iframe.contentWindow.document.write(...). + // https://github.com/mapbox/mapbox-gl-js/issues/7410 + } + } + +} + +export default Hash; diff --git a/node_modules/mapbox-gl/src/ui/map.js b/node_modules/mapbox-gl/src/ui/map.js new file mode 100644 index 0000000000000000000000000000000000000000..e832103777890ed7e02b3b494a36bf5861436c19 --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/map.js @@ -0,0 +1,2874 @@ +// @flow + +import {version} from '../../package.json'; +import {extend, bindAll, warnOnce, uniqueId} from '../util/util'; +import browser from '../util/browser'; +import window from '../util/window'; +const {HTMLImageElement, HTMLElement, ImageBitmap} = window; +import DOM from '../util/dom'; +import {getImage, getJSON, ResourceType} from '../util/ajax'; +import {RequestManager} from '../util/mapbox'; +import Style from '../style/style'; +import EvaluationParameters from '../style/evaluation_parameters'; +import Painter from '../render/painter'; +import Transform from '../geo/transform'; +import Hash from './hash'; +import HandlerManager from './handler_manager'; +import Camera from './camera'; +import LngLat from '../geo/lng_lat'; +import LngLatBounds from '../geo/lng_lat_bounds'; +import Point from '@mapbox/point-geometry'; +import AttributionControl from './control/attribution_control'; +import LogoControl from './control/logo_control'; +import isSupported from '@mapbox/mapbox-gl-supported'; +import {RGBAImage} from '../util/image'; +import {Event, ErrorEvent} from '../util/evented'; +import {MapMouseEvent} from './events'; +import TaskQueue from '../util/task_queue'; +import webpSupported from '../util/webp_supported'; +import {PerformanceMarkers, PerformanceUtils} from '../util/performance'; + +import {setCacheLimits} from '../util/tile_request_cache'; + +import type {PointLike} from '@mapbox/point-geometry'; +import type {RequestTransformFunction} from '../util/mapbox'; +import type {LngLatLike} from '../geo/lng_lat'; +import type {LngLatBoundsLike} from '../geo/lng_lat_bounds'; +import type {StyleOptions, StyleSetterOptions} from '../style/style'; +import type {MapEvent, MapDataEvent} from './events'; +import type {CustomLayerInterface} from '../style/style_layer/custom_style_layer'; +import type {StyleImageInterface, StyleImageMetadata} from '../style/style_image'; + +import type ScrollZoomHandler from './handler/scroll_zoom'; +import type BoxZoomHandler from './handler/box_zoom'; +import type {TouchPitchHandler} from './handler/touch_zoom_rotate'; +import type DragRotateHandler from './handler/shim/drag_rotate'; +import type DragPanHandler, {DragPanOptions} from './handler/shim/drag_pan'; +import type KeyboardHandler from './handler/keyboard'; +import type DoubleClickZoomHandler from './handler/shim/dblclick_zoom'; +import type TouchZoomRotateHandler from './handler/shim/touch_zoom_rotate'; +import defaultLocale from './default_locale'; +import type {TaskID} from '../util/task_queue'; +import type {Cancelable} from '../types/cancelable'; +import type { + LayerSpecification, + FilterSpecification, + StyleSpecification, + LightSpecification, + SourceSpecification +} from '../style-spec/types'; + +type ControlPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; +/* eslint-disable no-use-before-define */ +type IControl = { + onAdd(map: Map): HTMLElement; + onRemove(map: Map): void; + + +getDefaultPosition?: () => ControlPosition; +} +/* eslint-enable no-use-before-define */ + +type MapOptions = { + hash?: boolean | string, + interactive?: boolean, + container: HTMLElement | string, + bearingSnap?: number, + attributionControl?: boolean, + customAttribution?: string | Array, + logoPosition?: ControlPosition, + failIfMajorPerformanceCaveat?: boolean, + preserveDrawingBuffer?: boolean, + antialias?: boolean, + refreshExpiredTiles?: boolean, + maxBounds?: LngLatBoundsLike, + scrollZoom?: boolean, + minZoom?: ?number, + maxZoom?: ?number, + minPitch?: ?number, + maxPitch?: ?number, + boxZoom?: boolean, + dragRotate?: boolean, + dragPan?: DragPanOptions, + keyboard?: boolean, + doubleClickZoom?: boolean, + touchZoomRotate?: boolean, + touchPitch?: boolean, + trackResize?: boolean, + center?: LngLatLike, + zoom?: number, + bearing?: number, + pitch?: number, + renderWorldCopies?: boolean, + maxTileCacheSize?: number, + transformRequest?: RequestTransformFunction, + accessToken: string, + locale?: Object +}; + +const defaultMinZoom = -2; +const defaultMaxZoom = 22; + +// the default values, but also the valid range +const defaultMinPitch = 0; +const defaultMaxPitch = 60; + +const defaultOptions = { + center: [0, 0], + zoom: 0, + bearing: 0, + pitch: 0, + + minZoom: defaultMinZoom, + maxZoom: defaultMaxZoom, + + minPitch: defaultMinPitch, + maxPitch: defaultMaxPitch, + + interactive: true, + scrollZoom: true, + boxZoom: true, + dragRotate: true, + dragPan: true, + keyboard: true, + doubleClickZoom: true, + touchZoomRotate: true, + touchPitch: true, + + bearingSnap: 7, + clickTolerance: 3, + pitchWithRotate: true, + + hash: false, + attributionControl: true, + + failIfMajorPerformanceCaveat: false, + preserveDrawingBuffer: false, + trackResize: true, + renderWorldCopies: true, + refreshExpiredTiles: true, + maxTileCacheSize: null, + localIdeographFontFamily: 'sans-serif', + transformRequest: null, + accessToken: null, + fadeDuration: 300, + crossSourceCollisions: true +}; + +/** + * The `Map` object represents the map on your page. It exposes methods + * and properties that enable you to programmatically change the map, + * and fires events as users interact with it. + * + * You create a `Map` by specifying a `container` and other options. + * Then Mapbox GL JS initializes the map on the page and returns your `Map` + * object. + * + * @extends Evented + * @param {Object} options + * @param {HTMLElement|string} options.container The HTML element in which Mapbox GL JS will render the map, or the element's string `id`. The specified element must have no children. + * @param {number} [options.minZoom=0] The minimum zoom level of the map (0-24). + * @param {number} [options.maxZoom=22] The maximum zoom level of the map (0-24). + * @param {number} [options.minPitch=0] The minimum pitch of the map (0-60). + * @param {number} [options.maxPitch=60] The maximum pitch of the map (0-60). + * @param {Object|string} [options.style] The map's Mapbox style. This must be an a JSON object conforming to + * the schema described in the [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/), or a URL to + * such JSON. + * + * To load a style from the Mapbox API, you can use a URL of the form `mapbox://styles/:owner/:style`, + * where `:owner` is your Mapbox account name and `:style` is the style ID. Or you can use one of the following + * [the predefined Mapbox styles](https://www.mapbox.com/maps/): + * + * * `mapbox://styles/mapbox/streets-v11` + * * `mapbox://styles/mapbox/outdoors-v11` + * * `mapbox://styles/mapbox/light-v10` + * * `mapbox://styles/mapbox/dark-v10` + * * `mapbox://styles/mapbox/satellite-v9` + * * `mapbox://styles/mapbox/satellite-streets-v11` + * * `mapbox://styles/mapbox/navigation-preview-day-v4` + * * `mapbox://styles/mapbox/navigation-preview-night-v4` + * * `mapbox://styles/mapbox/navigation-guidance-day-v4` + * * `mapbox://styles/mapbox/navigation-guidance-night-v4` + * + * Tilesets hosted with Mapbox can be style-optimized if you append `?optimize=true` to the end of your style URL, like `mapbox://styles/mapbox/streets-v11?optimize=true`. + * Learn more about style-optimized vector tiles in our [API documentation](https://www.mapbox.com/api-documentation/maps/#retrieve-tiles). + * + * @param {(boolean|string)} [options.hash=false] If `true`, the map's position (zoom, center latitude, center longitude, bearing, and pitch) will be synced with the hash fragment of the page's URL. + * For example, `http://path/to/my/page.html#2.59/39.26/53.07/-24.1/60`. + * An additional string may optionally be provided to indicate a parameter-styled hash, + * e.g. http://path/to/my/page.html#map=2.59/39.26/53.07/-24.1/60&foo=bar, where foo + * is a custom parameter and bar is an arbitrary hash distinct from the map hash. + * @param {boolean} [options.interactive=true] If `false`, no mouse, touch, or keyboard listeners will be attached to the map, so it will not respond to interaction. + * @param {number} [options.bearingSnap=7] The threshold, measured in degrees, that determines when the map's + * bearing will snap to north. For example, with a `bearingSnap` of 7, if the user rotates + * the map within 7 degrees of north, the map will automatically snap to exact north. + * @param {boolean} [options.pitchWithRotate=true] If `false`, the map's pitch (tilt) control with "drag to rotate" interaction will be disabled. + * @param {number} [options.clickTolerance=3] The max number of pixels a user can shift the mouse pointer during a click for it to be considered a valid click (as opposed to a mouse drag). + * @param {boolean} [options.attributionControl=true] If `true`, an {@link AttributionControl} will be added to the map. + * @param {string | Array} [options.customAttribution] String or strings to show in an {@link AttributionControl}. Only applicable if `options.attributionControl` is `true`. + * @param {string} [options.logoPosition='bottom-left'] A string representing the position of the Mapbox wordmark on the map. Valid options are `top-left`,`top-right`, `bottom-left`, `bottom-right`. + * @param {boolean} [options.failIfMajorPerformanceCaveat=false] If `true`, map creation will fail if the performance of Mapbox + * GL JS would be dramatically worse than expected (i.e. a software renderer would be used). + * @param {boolean} [options.preserveDrawingBuffer=false] If `true`, the map's canvas can be exported to a PNG using `map.getCanvas().toDataURL()`. This is `false` by default as a performance optimization. + * @param {boolean} [options.antialias] If `true`, the gl context will be created with MSAA antialiasing, which can be useful for antialiasing custom layers. this is `false` by default as a performance optimization. + * @param {boolean} [options.refreshExpiredTiles=true] If `false`, the map won't attempt to re-request tiles once they expire per their HTTP `cacheControl`/`expires` headers. + * @param {LngLatBoundsLike} [options.maxBounds] If set, the map will be constrained to the given bounds. + * @param {boolean|Object} [options.scrollZoom=true] If `true`, the "scroll to zoom" interaction is enabled. An `Object` value is passed as options to {@link ScrollZoomHandler#enable}. + * @param {boolean} [options.boxZoom=true] If `true`, the "box zoom" interaction is enabled (see {@link BoxZoomHandler}). + * @param {boolean} [options.dragRotate=true] If `true`, the "drag to rotate" interaction is enabled (see {@link DragRotateHandler}). + * @param {boolean|Object} [options.dragPan=true] If `true`, the "drag to pan" interaction is enabled. An `Object` value is passed as options to {@link DragPanHandler#enable}. + * @param {boolean} [options.keyboard=true] If `true`, keyboard shortcuts are enabled (see {@link KeyboardHandler}). + * @param {boolean} [options.doubleClickZoom=true] If `true`, the "double click to zoom" interaction is enabled (see {@link DoubleClickZoomHandler}). + * @param {boolean|Object} [options.touchZoomRotate=true] If `true`, the "pinch to rotate and zoom" interaction is enabled. An `Object` value is passed as options to {@link TouchZoomRotateHandler#enable}. + * @param {boolean|Object} [options.touchPitch=true] If `true`, the "drag to pitch" interaction is enabled. An `Object` value is passed as options to {@link TouchPitchHandler#enable}. + * @param {boolean} [options.trackResize=true] If `true`, the map will automatically resize when the browser window resizes. + * @param {LngLatLike} [options.center=[0, 0]] The inital geographical centerpoint of the map. If `center` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `[0, 0]` Note: Mapbox GL uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON. + * @param {number} [options.zoom=0] The initial zoom level of the map. If `zoom` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`. + * @param {number} [options.bearing=0] The initial bearing (rotation) of the map, measured in degrees counter-clockwise from north. If `bearing` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`. + * @param {number} [options.pitch=0] The initial pitch (tilt) of the map, measured in degrees away from the plane of the screen (0-60). If `pitch` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`. + * @param {LngLatBoundsLike} [options.bounds] The initial bounds of the map. If `bounds` is specified, it overrides `center` and `zoom` constructor options. + * @param {Object} [options.fitBoundsOptions] A {@link Map#fitBounds} options object to use _only_ when fitting the initial `bounds` provided above. + * @param {boolean} [options.renderWorldCopies=true] If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`: + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * @param {number} [options.maxTileCacheSize=null] The maximum number of tiles stored in the tile cache for a given source. If omitted, the cache will be dynamically sized based on the current viewport. + * @param {string} [options.localIdeographFontFamily='sans-serif'] Defines a CSS + * font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' and 'Hangul Syllables' ranges. + * In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold). + * Set to `false`, to enable font settings from the map's style for these glyph ranges. Note that [Mapbox Studio](https://studio.mapbox.com/) sets this value to `false` by default. + * The purpose of this option is to avoid bandwidth-intensive glyph server requests. (See [Use locally generated ideographs](https://www.mapbox.com/mapbox-gl-js/example/local-ideographs).) + * @param {RequestTransformFunction} [options.transformRequest=null] A callback run before the Map makes a request for an external URL. The callback can be used to modify the url, set headers, or set the credentials property for cross-origin requests. + * Expected to return an object with a `url` property and optionally `headers` and `credentials` properties. + * @param {boolean} [options.collectResourceTiming=false] If `true`, Resource Timing API information will be collected for requests made by GeoJSON and Vector Tile web workers (this information is normally inaccessible from the main Javascript thread). Information will be returned in a `resourceTiming` property of relevant `data` events. + * @param {number} [options.fadeDuration=300] Controls the duration of the fade-in/fade-out animation for label collisions, in milliseconds. This setting affects all symbol layers. This setting does not affect the duration of runtime styling transitions or raster tile cross-fading. + * @param {boolean} [options.crossSourceCollisions=true] If `true`, symbols from multiple sources can collide with each other during collision detection. If `false`, collision detection is run separately for the symbols in each source. + * @param {string} [options.accessToken=null] If specified, map will use this token instead of the one defined in mapboxgl.accessToken. + * @param {Object} [options.locale=null] A patch to apply to the default localization table for UI strings, e.g. control tooltips. The `locale` object maps namespaced UI string IDs to translated strings in the target language; see `src/ui/default_locale.js` for an example with all supported string IDs. The object may specify all UI strings (thereby adding support for a new translation) or only a subset of strings (thereby patching the default translation table). + * @example + * var map = new mapboxgl.Map({ + * container: 'map', + * center: [-122.420679, 37.772537], + * zoom: 13, + * style: style_object, + * hash: true, + * transformRequest: (url, resourceType)=> { + * if(resourceType === 'Source' && url.startsWith('http://myHost')) { + * return { + * url: url.replace('http', 'https'), + * headers: { 'my-custom-header': true}, + * credentials: 'include' // Include cookies for cross-origin requests + * } + * } + * } + * }); + * @see [Display a map](https://www.mapbox.com/mapbox-gl-js/examples/) + */ +class Map extends Camera { + style: Style; + painter: Painter; + handlers: HandlerManager; + + _container: HTMLElement; + _missingCSSCanary: HTMLElement; + _canvasContainer: HTMLElement; + _controlContainer: HTMLElement; + _controlPositions: {[_: string]: HTMLElement}; + _interactive: ?boolean; + _showTileBoundaries: ?boolean; + _showCollisionBoxes: ?boolean; + _showPadding: ?boolean; + _showOverdrawInspector: boolean; + _repaint: ?boolean; + _vertices: ?boolean; + _canvas: HTMLCanvasElement; + _maxTileCacheSize: number; + _frame: ?Cancelable; + _styleDirty: ?boolean; + _sourcesDirty: ?boolean; + _placementDirty: ?boolean; + _loaded: boolean; + // accounts for placement finishing as well + _fullyLoaded: boolean; + _trackResize: boolean; + _preserveDrawingBuffer: boolean; + _failIfMajorPerformanceCaveat: boolean; + _antialias: boolean; + _refreshExpiredTiles: boolean; + _hash: Hash; + _delegatedListeners: any; + _fadeDuration: number; + _crossSourceCollisions: boolean; + _crossFadingFactor: number; + _collectResourceTiming: boolean; + _renderTaskQueue: TaskQueue; + _controls: Array; + _mapId: number; + _localIdeographFontFamily: string; + _requestManager: RequestManager; + _locale: Object; + _removed: boolean; + _clickTolerance: number; + + /** + * The map's {@link ScrollZoomHandler}, which implements zooming in and out with a scroll wheel or trackpad. + * Find more details and examples using `scrollZoom` in the {@link ScrollZoomHandler} section. + */ + scrollZoom: ScrollZoomHandler; + + /** + * The map's {@link BoxZoomHandler}, which implements zooming using a drag gesture with the Shift key pressed. + * Find more details and examples using `boxZoom` in the {@link BoxZoomHandler} section. + */ + boxZoom: BoxZoomHandler; + + /** + * The map's {@link DragRotateHandler}, which implements rotating the map while dragging with the right + * mouse button or with the Control key pressed. Find more details and examples using `dragRotate` + * in the {@link DragRotateHandler} section. + */ + dragRotate: DragRotateHandler; + + /** + * The map's {@link DragPanHandler}, which implements dragging the map with a mouse or touch gesture. + * Find more details and examples using `dragPan` in the {@link DragPanHandler} section. + */ + dragPan: DragPanHandler; + + /** + * The map's {@link KeyboardHandler}, which allows the user to zoom, rotate, and pan the map using keyboard + * shortcuts. Find more details and examples using `keyboard` in the {@link KeyboardHandler} section. + */ + keyboard: KeyboardHandler; + + /** + * The map's {@link DoubleClickZoomHandler}, which allows the user to zoom by double clicking. + * Find more details and examples using `doubleClickZoom` in the {@link DoubleClickZoomHandler} section. + */ + doubleClickZoom: DoubleClickZoomHandler; + + /** + * The map's {@link TouchZoomRotateHandler}, which allows the user to zoom or rotate the map with touch gestures. + * Find more details and examples using `touchZoomRotate` in the {@link TouchZoomRotateHandler} section. + */ + touchZoomRotate: TouchZoomRotateHandler; + + /** + * The map's {@link TouchPitchHandler}, which allows the user to pitch the map with touch gestures. + * Find more details and examples using `touchPitch` in the {@link TouchPitchHandler} section. + */ + touchPitch: TouchPitchHandler; + + constructor(options: MapOptions) { + PerformanceUtils.mark(PerformanceMarkers.create); + + options = extend({}, defaultOptions, options); + + if (options.minZoom != null && options.maxZoom != null && options.minZoom > options.maxZoom) { + throw new Error(`maxZoom must be greater than or equal to minZoom`); + } + + if (options.minPitch != null && options.maxPitch != null && options.minPitch > options.maxPitch) { + throw new Error(`maxPitch must be greater than or equal to minPitch`); + } + + if (options.minPitch != null && options.minPitch < defaultMinPitch) { + throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`); + } + + if (options.maxPitch != null && options.maxPitch > defaultMaxPitch) { + throw new Error(`maxPitch must be less than or equal to ${defaultMaxPitch}`); + } + + const transform = new Transform(options.minZoom, options.maxZoom, options.minPitch, options.maxPitch, options.renderWorldCopies); + super(transform, options); + + this._interactive = options.interactive; + this._maxTileCacheSize = options.maxTileCacheSize; + this._failIfMajorPerformanceCaveat = options.failIfMajorPerformanceCaveat; + this._preserveDrawingBuffer = options.preserveDrawingBuffer; + this._antialias = options.antialias; + this._trackResize = options.trackResize; + this._bearingSnap = options.bearingSnap; + this._refreshExpiredTiles = options.refreshExpiredTiles; + this._fadeDuration = options.fadeDuration; + this._crossSourceCollisions = options.crossSourceCollisions; + this._crossFadingFactor = 1; + this._collectResourceTiming = options.collectResourceTiming; + this._renderTaskQueue = new TaskQueue(); + this._controls = []; + this._mapId = uniqueId(); + this._locale = extend({}, defaultLocale, options.locale); + this._clickTolerance = options.clickTolerance; + + this._requestManager = new RequestManager(options.transformRequest, options.accessToken); + + if (typeof options.container === 'string') { + this._container = window.document.getElementById(options.container); + if (!this._container) { + throw new Error(`Container '${options.container}' not found.`); + } + } else if (options.container instanceof HTMLElement) { + this._container = options.container; + } else { + throw new Error(`Invalid type: 'container' must be a String or HTMLElement.`); + } + + if (options.maxBounds) { + this.setMaxBounds(options.maxBounds); + } + + bindAll([ + '_onWindowOnline', + '_onWindowResize', + '_onMapScroll', + '_contextLost', + '_contextRestored' + ], this); + + this._setupContainer(); + this._setupPainter(); + if (this.painter === undefined) { + throw new Error(`Failed to initialize WebGL.`); + } + + this.on('move', () => this._update(false)); + this.on('moveend', () => this._update(false)); + this.on('zoom', () => this._update(true)); + + if (typeof window !== 'undefined') { + window.addEventListener('online', this._onWindowOnline, false); + window.addEventListener('resize', this._onWindowResize, false); + window.addEventListener('orientationchange', this._onWindowResize, false); + } + + this.handlers = new HandlerManager(this, options); + + const hashName = (typeof options.hash === 'string' && options.hash) || undefined; + this._hash = options.hash && (new Hash(hashName)).addTo(this); + // don't set position from options if set through hash + if (!this._hash || !this._hash._onHashChange()) { + this.jumpTo({ + center: options.center, + zoom: options.zoom, + bearing: options.bearing, + pitch: options.pitch + }); + + if (options.bounds) { + this.resize(); + this.fitBounds(options.bounds, extend({}, options.fitBoundsOptions, {duration: 0})); + } + } + + this.resize(); + + this._localIdeographFontFamily = options.localIdeographFontFamily; + if (options.style) this.setStyle(options.style, {localIdeographFontFamily: options.localIdeographFontFamily}); + + if (options.attributionControl) + this.addControl(new AttributionControl({customAttribution: options.customAttribution})); + + this.addControl(new LogoControl(), options.logoPosition); + + this.on('style.load', () => { + if (this.transform.unmodified) { + this.jumpTo((this.style.stylesheet: any)); + } + }); + this.on('data', (event: MapDataEvent) => { + this._update(event.dataType === 'style'); + this.fire(new Event(`${event.dataType}data`, event)); + }); + this.on('dataloading', (event: MapDataEvent) => { + this.fire(new Event(`${event.dataType}dataloading`, event)); + }); + } + + /* + * Returns a unique number for this map instance which is used for the MapLoadEvent + * to make sure we only fire one event per instantiated map object. + * @private + * @returns {number} + */ + _getMapId() { + return this._mapId; + } + + /** + * Adds an {@link IControl} to the map, calling `control.onAdd(this)`. + * + * @param {IControl} control The {@link IControl} to add. + * @param {string} [position] position on the map to which the control will be added. + * Valid values are `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. Defaults to `'top-right'`. + * @returns {Map} `this` + * @example + * // Add zoom and rotation controls to the map. + * map.addControl(new mapboxgl.NavigationControl()); + * @see [Display map navigation controls](https://www.mapbox.com/mapbox-gl-js/example/navigation/) + */ + addControl(control: IControl, position?: ControlPosition) { + if (position === undefined) { + if (control.getDefaultPosition) { + position = control.getDefaultPosition(); + } else { + position = 'top-right'; + } + } + if (!control || !control.onAdd) { + return this.fire(new ErrorEvent(new Error( + 'Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.'))); + } + const controlElement = control.onAdd(this); + this._controls.push(control); + + const positionContainer = this._controlPositions[position]; + if (position.indexOf('bottom') !== -1) { + positionContainer.insertBefore(controlElement, positionContainer.firstChild); + } else { + positionContainer.appendChild(controlElement); + } + return this; + } + + /** + * Removes the control from the map. + * + * @param {IControl} control The {@link IControl} to remove. + * @returns {Map} `this` + * @example + * // Define a new navigation control. + * var navigation = new mapboxgl.NavigationControl(); + * // Add zoom and rotation controls to the map. + * map.addControl(navigation); + * // Remove zoom and rotation controls from the map. + * map.removeControl(navigation); + */ + removeControl(control: IControl) { + if (!control || !control.onRemove) { + return this.fire(new ErrorEvent(new Error( + 'Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.'))); + } + const ci = this._controls.indexOf(control); + if (ci > -1) this._controls.splice(ci, 1); + control.onRemove(this); + return this; + } + + /** + * Checks if a control exists on the map. + * + * @param {IControl} control The {@link IControl} to check. + * @returns {boolean} True if map contains control. + * @example + * // Define a new navigation control. + * var navigation = new mapboxgl.NavigationControl(); + * // Add zoom and rotation controls to the map. + * map.addControl(navigation); + * // Check that the navigation control exists on the map. + * map.hasControl(navigation); + */ + hasControl(control: IControl) { + return this._controls.indexOf(control) > -1; + } + + /** + * Resizes the map according to the dimensions of its + * `container` element. + * + * Checks if the map container size changed and updates the map if it has changed. + * This method must be called after the map's `container` is resized programmatically + * or when the map is shown after being initially hidden with CSS. + * + * @param eventData Additional properties to be passed to `movestart`, `move`, `resize`, and `moveend` + * events that get triggered as a result of resize. This can be useful for differentiating the + * source of an event (for example, user-initiated or programmatically-triggered events). + * @returns {Map} `this` + * @example + * // Resize the map when the map container is shown + * // after being initially hidden with CSS. + * var mapDiv = document.getElementById('map'); + * if (mapDiv.style.visibility === true) map.resize(); + */ + resize(eventData?: Object) { + const [width, height] = this._containerDimensions(); + + // do nothing if container remained the same size + if (width === this.transform.width && height === this.transform.height) return this; + + this._resizeCanvas(width, height); + this.transform.resize(width, height); + this.painter.resize(width, height); + + const fireMoving = !this._moving; + if (fireMoving) { + this.fire(new Event('movestart', eventData)) + .fire(new Event('move', eventData)); + } + + this.fire(new Event('resize', eventData)); + + if (fireMoving) this.fire(new Event('moveend', eventData)); + + return this; + } + + /** + * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not + * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region. + * @returns {LngLatBounds} The geographical bounds of the map as {@link LngLatBounds}. + * @example + * var bounds = map.getBounds(); + */ + getBounds(): LngLatBounds { + return this.transform.getBounds(); + } + + /** + * Returns the maximum geographical bounds the map is constrained to, or `null` if none set. + * @returns The map object. + * @example + * var maxBounds = map.getMaxBounds(); + */ + getMaxBounds(): LngLatBounds | null { + return this.transform.getMaxBounds(); + } + + /** + * Sets or clears the map's geographical bounds. + * + * Pan and zoom operations are constrained within these bounds. + * If a pan or zoom is performed that would + * display regions outside these bounds, the map will + * instead display a position and zoom level + * as close as possible to the operation's request while still + * remaining within the bounds. + * + * @param {LngLatBoundsLike | null | undefined} bounds The maximum bounds to set. If `null` or `undefined` is provided, the function removes the map's maximum bounds. + * @returns {Map} `this` + * @example + * // Define bounds that conform to the `LngLatBoundsLike` object. + * var bounds = [ + * [-74.04728, 40.68392], // [west, south] + * [-73.91058, 40.87764] // [east, north] + * ]; + * // Set the map's max bounds. + * map.setMaxBounds(bounds); + */ + setMaxBounds(bounds: LngLatBoundsLike) { + this.transform.setMaxBounds(LngLatBounds.convert(bounds)); + return this._update(); + } + + /** + * Sets or clears the map's minimum zoom level. + * If the map's current zoom level is lower than the new minimum, + * the map will zoom to the new minimum. + * + * It is not always possible to zoom out and reach the set `minZoom`. + * Other factors such as map height may restrict zooming. For example, + * if the map is 512px tall it will not be possible to zoom below zoom 0 + * no matter what the `minZoom` is set to. + * + * @param {number | null | undefined} minZoom The minimum zoom level to set (-2 - 24). + * If `null` or `undefined` is provided, the function removes the current minimum zoom (i.e. sets it to -2). + * @returns {Map} `this` + * @example + * map.setMinZoom(12.25); + */ + setMinZoom(minZoom?: ?number) { + + minZoom = minZoom === null || minZoom === undefined ? defaultMinZoom : minZoom; + + if (minZoom >= defaultMinZoom && minZoom <= this.transform.maxZoom) { + this.transform.minZoom = minZoom; + this._update(); + + if (this.getZoom() < minZoom) this.setZoom(minZoom); + + return this; + + } else throw new Error(`minZoom must be between ${defaultMinZoom} and the current maxZoom, inclusive`); + } + + /** + * Returns the map's minimum allowable zoom level. + * + * @returns {number} minZoom + * @example + * var minZoom = map.getMinZoom(); + */ + getMinZoom() { return this.transform.minZoom; } + + /** + * Sets or clears the map's maximum zoom level. + * If the map's current zoom level is higher than the new maximum, + * the map will zoom to the new maximum. + * + * @param {number | null | undefined} maxZoom The maximum zoom level to set. + * If `null` or `undefined` is provided, the function removes the current maximum zoom (sets it to 22). + * @returns {Map} `this` + * @example + * map.setMaxZoom(18.75); + */ + setMaxZoom(maxZoom?: ?number) { + + maxZoom = maxZoom === null || maxZoom === undefined ? defaultMaxZoom : maxZoom; + + if (maxZoom >= this.transform.minZoom) { + this.transform.maxZoom = maxZoom; + this._update(); + + if (this.getZoom() > maxZoom) this.setZoom(maxZoom); + + return this; + + } else throw new Error(`maxZoom must be greater than the current minZoom`); + } + + /** + * Returns the map's maximum allowable zoom level. + * + * @returns {number} maxZoom + * @example + * var maxZoom = map.getMaxZoom(); + */ + getMaxZoom() { return this.transform.maxZoom; } + + /** + * Sets or clears the map's minimum pitch. + * If the map's current pitch is lower than the new minimum, + * the map will pitch to the new minimum. + * + * @param {number | null | undefined} minPitch The minimum pitch to set (0-60). + * If `null` or `undefined` is provided, the function removes the current minimum pitch (i.e. sets it to 0). + * @returns {Map} `this` + */ + setMinPitch(minPitch?: ?number) { + + minPitch = minPitch === null || minPitch === undefined ? defaultMinPitch : minPitch; + + if (minPitch < defaultMinPitch) { + throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`); + } + + if (minPitch >= defaultMinPitch && minPitch <= this.transform.maxPitch) { + this.transform.minPitch = minPitch; + this._update(); + + if (this.getPitch() < minPitch) this.setPitch(minPitch); + + return this; + + } else throw new Error(`minPitch must be between ${defaultMinPitch} and the current maxPitch, inclusive`); + } + + /** + * Returns the map's minimum allowable pitch. + * + * @returns {number} minPitch + */ + getMinPitch() { return this.transform.minPitch; } + + /** + * Sets or clears the map's maximum pitch. + * If the map's current pitch is higher than the new maximum, + * the map will pitch to the new maximum. + * + * @param {number | null | undefined} maxPitch The maximum pitch to set. + * If `null` or `undefined` is provided, the function removes the current maximum pitch (sets it to 60). + * @returns {Map} `this` + */ + setMaxPitch(maxPitch?: ?number) { + + maxPitch = maxPitch === null || maxPitch === undefined ? defaultMaxPitch : maxPitch; + + if (maxPitch > defaultMaxPitch) { + throw new Error(`maxPitch must be less than or equal to ${defaultMaxPitch}`); + } + + if (maxPitch >= this.transform.minPitch) { + this.transform.maxPitch = maxPitch; + this._update(); + + if (this.getPitch() > maxPitch) this.setPitch(maxPitch); + + return this; + + } else throw new Error(`maxPitch must be greater than the current minPitch`); + } + + /** + * Returns the map's maximum allowable pitch. + * + * @returns {number} maxPitch + */ + getMaxPitch() { return this.transform.maxPitch; } + + /** + * Returns the state of `renderWorldCopies`. If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`: + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * @returns {boolean} renderWorldCopies + * @example + * var worldCopiesRendered = map.getRenderWorldCopies(); + * @see [Render world copies](https://docs.mapbox.com/mapbox-gl-js/example/render-world-copies/) + */ + getRenderWorldCopies() { return this.transform.renderWorldCopies; } + + /** + * Sets the state of `renderWorldCopies`. + * + * @param {boolean} renderWorldCopies If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`: + * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire + * container, there will be blank space beyond 180 and -180 degrees longitude. + * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the + * map and the other on the left edge of the map) at every zoom level. + * + * `undefined` is treated as `true`, `null` is treated as `false`. + * @returns {Map} `this` + * @example + * map.setRenderWorldCopies(true); + * @see [Render world copies](https://docs.mapbox.com/mapbox-gl-js/example/render-world-copies/) + */ + setRenderWorldCopies(renderWorldCopies?: ?boolean) { + this.transform.renderWorldCopies = renderWorldCopies; + return this._update(); + } + + /** + * Returns a {@link Point} representing pixel coordinates, relative to the map's `container`, + * that correspond to the specified geographical location. + * + * @param {LngLatLike} lnglat The geographical location to project. + * @returns {Point} The {@link Point} corresponding to `lnglat`, relative to the map's `container`. + * @example + * var coordinate = [-122.420679, 37.772537]; + * var point = map.project(coordinate); + */ + project(lnglat: LngLatLike) { + return this.transform.locationPoint(LngLat.convert(lnglat)); + } + + /** + * Returns a {@link LngLat} representing geographical coordinates that correspond + * to the specified pixel coordinates. + * + * @param {PointLike} point The pixel coordinates to unproject. + * @returns {LngLat} The {@link LngLat} corresponding to `point`. + * @example + * map.on('click', function(e) { + * // When the map is clicked, get the geographic coordinate. + * var coordinate = map.unproject(e.point); + * }); + */ + unproject(point: PointLike) { + return this.transform.pointLocation(Point.convert(point)); + } + + /** + * Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture. + * @returns {boolean} True if the map is moving. + * @example + * var isMoving = map.isMoving(); + */ + isMoving(): boolean { + return this._moving || this.handlers.isMoving(); + } + + /** + * Returns true if the map is zooming due to a camera animation or user gesture. + * @returns {boolean} True if the map is zooming. + * @example + * var isZooming = map.isZooming(); + */ + isZooming(): boolean { + return this._zooming || this.handlers.isZooming(); + } + + /** + * Returns true if the map is rotating due to a camera animation or user gesture. + * @returns {boolean} True if the map is rotating. + * @example + * map.isRotating(); + */ + isRotating(): boolean { + return this._rotating || this.handlers.isRotating(); + } + + _createDelegatedListener(type: MapEvent, layerId: any, listener: any) { + if (type === 'mouseenter' || type === 'mouseover') { + let mousein = false; + const mousemove = (e) => { + const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : []; + if (!features.length) { + mousein = false; + } else if (!mousein) { + mousein = true; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent, {features})); + } + }; + const mouseout = () => { + mousein = false; + }; + return {layer: layerId, listener, delegates: {mousemove, mouseout}}; + } else if (type === 'mouseleave' || type === 'mouseout') { + let mousein = false; + const mousemove = (e) => { + const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : []; + if (features.length) { + mousein = true; + } else if (mousein) { + mousein = false; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent)); + } + }; + const mouseout = (e) => { + if (mousein) { + mousein = false; + listener.call(this, new MapMouseEvent(type, this, e.originalEvent)); + } + }; + return {layer: layerId, listener, delegates: {mousemove, mouseout}}; + } else { + const delegate = (e) => { + const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : []; + if (features.length) { + // Here we need to mutate the original event, so that preventDefault works as expected. + e.features = features; + listener.call(this, e); + delete e.features; + } + }; + return {layer: layerId, listener, delegates: {[type]: delegate}}; + } + } + + /** + * Adds a listener for events of a specified type, optionally limited to features in a specified style layer. + * + * @param {string} type The event type to listen for. Events compatible with the optional `layerId` parameter are triggered + * when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas. + * + * | Event | Compatible with `layerId` | + * |-----------------------------------------------------------|---------------------------| + * | [`mousedown`](#map.event:mousedown) | yes | + * | [`mouseup`](#map.event:mouseup) | yes | + * | [`mouseover`](#map.event:mouseover) | yes | + * | [`mouseout`](#map.event:mouseout) | yes | + * | [`mousemove`](#map.event:mousemove) | yes | + * | [`mouseenter`](#map.event:mouseenter) | yes (required) | + * | [`mouseleave`](#map.event:mouseleave) | yes (required) | + * | [`click`](#map.event:click) | yes | + * | [`dblclick`](#map.event:dblclick) | yes | + * | [`contextmenu`](#map.event:contextmenu) | yes | + * | [`touchstart`](#map.event:touchstart) | yes | + * | [`touchend`](#map.event:touchend) | yes | + * | [`touchcancel`](#map.event:touchcancel) | yes | + * | [`wheel`](#map.event:wheel) | | + * | [`resize`](#map.event:resize) | | + * | [`remove`](#map.event:remove) | | + * | [`touchmove`](#map.event:touchmove) | | + * | [`movestart`](#map.event:movestart) | | + * | [`move`](#map.event:move) | | + * | [`moveend`](#map.event:moveend) | | + * | [`dragstart`](#map.event:dragstart) | | + * | [`drag`](#map.event:drag) | | + * | [`dragend`](#map.event:dragend) | | + * | [`zoomstart`](#map.event:zoomstart) | | + * | [`zoom`](#map.event:zoom) | | + * | [`zoomend`](#map.event:zoomend) | | + * | [`rotatestart`](#map.event:rotatestart) | | + * | [`rotate`](#map.event:rotate) | | + * | [`rotateend`](#map.event:rotateend) | | + * | [`pitchstart`](#map.event:pitchstart) | | + * | [`pitch`](#map.event:pitch) | | + * | [`pitchend`](#map.event:pitchend) | | + * | [`boxzoomstart`](#map.event:boxzoomstart) | | + * | [`boxzoomend`](#map.event:boxzoomend) | | + * | [`boxzoomcancel`](#map.event:boxzoomcancel) | | + * | [`webglcontextlost`](#map.event:webglcontextlost) | | + * | [`webglcontextrestored`](#map.event:webglcontextrestored) | | + * | [`load`](#map.event:load) | | + * | [`render`](#map.event:render) | | + * | [`idle`](#map.event:idle) | | + * | [`error`](#map.event:error) | | + * | [`data`](#map.event:data) | | + * | [`styledata`](#map.event:styledata) | | + * | [`sourcedata`](#map.event:sourcedata) | | + * | [`dataloading`](#map.event:dataloading) | | + * | [`styledataloading`](#map.event:styledataloading) | | + * | [`sourcedataloading`](#map.event:sourcedataloading) | | + * | [`styleimagemissing`](#map.event:styleimagemissing) | | + * + * @param {string} layerId (optional) The ID of a style layer. Event will only be triggered if its location + * is within a visible feature in this layer. The event will have a `features` property containing + * an array of the matching features. If `layerId` is not supplied, the event will not have a `features` property. + * Please note that many event types are not compatible with the optional `layerId` parameter. + * @param {Function} listener The function to be called when the event is fired. + * @returns {Map} `this` + * @example + * // Set an event listener that will fire + * // when the map has finished loading + * map.on('load', function() { + * // Once the map has finished loading, + * // add a new layer + * map.addLayer({ + * id: 'points-of-interest', + * source: { + * type: 'vector', + * url: 'mapbox://mapbox.mapbox-streets-v8' + * }, + * 'source-layer': 'poi_label', + * type: 'circle', + * paint: { + * // Mapbox Style Specification paint properties + * }, + * layout: { + * // Mapbox Style Specification layout properties + * } + * }); + * }); + * @example + * // Set an event listener that will fire + * // when a feature on the countries layer of the map is clicked + * map.on('click', 'countries', function(e) { + * new mapboxgl.Popup() + * .setLngLat(e.lngLat) + * .setHTML(`Country name: ${e.features[0].properties.name}`) + * .addTo(map); + * }); + * @see [Display popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/) + * @see [Center the map on a clicked symbol](https://docs.mapbox.com/mapbox-gl-js/example/center-on-symbol/) + * @see [Create a hover effect](https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/) + * @see [Create a draggable marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/) + */ + on(type: MapEvent, layerId: any, listener: any) { + if (listener === undefined) { + return super.on(type, layerId); + } + + const delegatedListener = this._createDelegatedListener(type, layerId, listener); + + this._delegatedListeners = this._delegatedListeners || {}; + this._delegatedListeners[type] = this._delegatedListeners[type] || []; + this._delegatedListeners[type].push(delegatedListener); + + for (const event in delegatedListener.delegates) { + this.on((event: any), delegatedListener.delegates[event]); + } + + return this; + } + + /** + * Adds a listener that will be called only once to a specified event type. + * + * @method + * @name once + * @memberof Map + * @instance + * @param {string} type The event type to add a listener for. + * @param {Function} listener The function to be called when the event is fired. + * The listener function is called with the data object passed to `fire`, + * extended with `target` and `type` properties. + * @returns {Map} `this` + */ + + /** + * Adds a listener that will be called only once to a specified event type occurring on features in a specified style layer. + * + * @param {string} type The event type to listen for; one of `'mousedown'`, `'mouseup'`, `'click'`, `'dblclick'`, + * `'mousemove'`, `'mouseenter'`, `'mouseleave'`, `'mouseover'`, `'mouseout'`, `'contextmenu'`, `'touchstart'`, + * `'touchend'`, or `'touchcancel'`. `mouseenter` and `mouseover` events are triggered when the cursor enters + * a visible portion of the specified layer from outside that layer or outside the map canvas. `mouseleave` + * and `mouseout` events are triggered when the cursor leaves a visible portion of the specified layer, or leaves + * the map canvas. + * @param {string} layerId The ID of a style layer. Only events whose location is within a visible + * feature in this layer will trigger the listener. The event will have a `features` property containing + * an array of the matching features. + * @param {Function} listener The function to be called when the event is fired. + * @returns {Map} `this` + */ + + once(type: MapEvent, layerId: any, listener: any) { + + if (listener === undefined) { + return super.once(type, layerId); + } + + const delegatedListener = this._createDelegatedListener(type, layerId, listener); + + for (const event in delegatedListener.delegates) { + this.once((event: any), delegatedListener.delegates[event]); + } + + return this; + } + + /** + * Removes an event listener previously added with `Map#on`. + * + * @method + * @name off + * @memberof Map + * @instance + * @param {string} type The event type previously used to install the listener. + * @param {Function} listener The function previously installed as a listener. + * @returns {Map} `this` + */ + + /** + * Removes an event listener for layer-specific events previously added with `Map#on`. + * + * @param {string} type The event type previously used to install the listener. + * @param {string} layerId The layer ID previously used to install the listener. + * @param {Function} listener The function previously installed as a listener. + * @returns {Map} `this` + */ + off(type: MapEvent, layerId: any, listener: any) { + if (listener === undefined) { + return super.off(type, layerId); + } + + const removeDelegatedListener = (delegatedListeners) => { + const listeners = delegatedListeners[type]; + for (let i = 0; i < listeners.length; i++) { + const delegatedListener = listeners[i]; + if (delegatedListener.layer === layerId && delegatedListener.listener === listener) { + for (const event in delegatedListener.delegates) { + this.off((event: any), delegatedListener.delegates[event]); + } + listeners.splice(i, 1); + return this; + } + } + }; + + if (this._delegatedListeners && this._delegatedListeners[type]) { + removeDelegatedListener(this._delegatedListeners); + } + + return this; + } + + /** + * Returns an array of [GeoJSON](http://geojson.org/) + * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2) + * representing visible features that satisfy the query parameters. + * + * @param {PointLike|Array} [geometry] - The geometry of the query region: + * either a single point or southwest and northeast points describing a bounding box. + * Omitting this parameter (i.e. calling {@link Map#queryRenderedFeatures} with zero arguments, + * or with only a `options` argument) is equivalent to passing a bounding box encompassing the entire + * map viewport. + * @param {Object} [options] Options object. + * @param {Array} [options.layers] An array of [style layer IDs](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-id) for the query to inspect. + * Only features within these layers will be returned. If this parameter is undefined, all layers will be checked. + * @param {Array} [options.filter] A [filter](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter) + * to limit query results. + * @param {boolean} [options.validate=true] Whether to check if the [options.filter] conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. + * + * @returns {Array} An array of [GeoJSON](http://geojson.org/) + * [feature objects](https://tools.ietf.org/html/rfc7946#section-3.2). + * + * The `properties` value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only + * string and numeric property values are supported (i.e. `null`, `Array`, and `Object` values are not supported). + * + * Each feature includes top-level `layer`, `source`, and `sourceLayer` properties. The `layer` property is an object + * representing the style layer to which the feature belongs. Layout and paint properties in this object contain values + * which are fully evaluated for the given zoom level and feature. + * + * Only features that are currently rendered are included. Some features will **not** be included, like: + * + * - Features from layers whose `visibility` property is `"none"`. + * - Features from layers whose zoom range excludes the current zoom level. + * - Symbol features that have been hidden due to text or icon collision. + * + * Features from all other layers are included, including features that may have no visible + * contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to + * 0. + * + * The topmost rendered feature appears first in the returned array, and subsequent features are sorted by + * descending z-order. Features that are rendered multiple times (due to wrapping across the antimeridian at low + * zoom levels) are returned only once (though subject to the following caveat). + * + * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature + * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple + * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. + * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding + * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile + * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple + * tiles due to tile buffering. + * + * @example + * // Find all features at a point + * var features = map.queryRenderedFeatures( + * [20, 35], + * { layers: ['my-layer-name'] } + * ); + * + * @example + * // Find all features within a static bounding box + * var features = map.queryRenderedFeatures( + * [[10, 20], [30, 50]], + * { layers: ['my-layer-name'] } + * ); + * + * @example + * // Find all features within a bounding box around a point + * var width = 10; + * var height = 20; + * var features = map.queryRenderedFeatures([ + * [point.x - width / 2, point.y - height / 2], + * [point.x + width / 2, point.y + height / 2] + * ], { layers: ['my-layer-name'] }); + * + * @example + * // Query all rendered features from a single layer + * var features = map.queryRenderedFeatures({ layers: ['my-layer-name'] }); + * @see [Get features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures/) + * @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/) + * @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/) + */ + queryRenderedFeatures(geometry?: PointLike | [PointLike, PointLike], options?: Object) { + // The first parameter can be omitted entirely, making this effectively an overloaded method + // with two signatures: + // + // queryRenderedFeatures(geometry: PointLike | [PointLike, PointLike], options?: Object) + // queryRenderedFeatures(options?: Object) + // + // There no way to express that in a way that's compatible with both flow and documentation.js. + // Related: https://github.com/facebook/flow/issues/1556 + + if (!this.style) { + return []; + } + + if (options === undefined && geometry !== undefined && !(geometry instanceof Point) && !Array.isArray(geometry)) { + options = (geometry: Object); + geometry = undefined; + } + + options = options || {}; + geometry = geometry || [[0, 0], [this.transform.width, this.transform.height]]; + + let queryGeometry; + if (geometry instanceof Point || typeof geometry[0] === 'number') { + queryGeometry = [Point.convert(geometry)]; + } else { + const tl = Point.convert(geometry[0]); + const br = Point.convert(geometry[1]); + queryGeometry = [tl, new Point(br.x, tl.y), br, new Point(tl.x, br.y), tl]; + } + + return this.style.queryRenderedFeatures(queryGeometry, options, this.transform); + } + + /** + * Returns an array of [GeoJSON](http://geojson.org/) + * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2) + * representing features within the specified vector tile or GeoJSON source that satisfy the query parameters. + * + * @param {string} sourceId The ID of the vector tile or GeoJSON source to query. + * @param {Object} [parameters] Options object. + * @param {string} [parameters.sourceLayer] The name of the [source layer](https://docs.mapbox.com/help/glossary/source-layer/) + * to query. *For vector tile sources, this parameter is required.* For GeoJSON sources, it is ignored. + * @param {Array} [parameters.filter] A [filter](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter) + * to limit query results. + * @param {boolean} [parameters.validate=true] Whether to check if the [parameters.filter] conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. + * + * @returns {Array} An array of [GeoJSON](http://geojson.org/) + * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2). + * + * In contrast to {@link Map#queryRenderedFeatures}, this function returns all features matching the query parameters, + * whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded + * vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently + * visible viewport. + * + * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature + * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple + * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. + * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding + * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile + * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple + * tiles due to tile buffering. + * + * @example + * // Find all features in one source layer in a vector source + * var features = map.querySourceFeatures('your-source-id', { + * sourceLayer: 'your-source-layer' + * }); + * + * @see [Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/) + */ + querySourceFeatures(sourceId: string, parameters: ?{sourceLayer: ?string, filter: ?Array, validate?: boolean}) { + return this.style.querySourceFeatures(sourceId, parameters); + } + + /** + * Updates the map's Mapbox style object with a new value. + * + * If a style is already set when this is used and options.diff is set to true, the map renderer will attempt to compare the given style + * against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites + * (images used for icons and patterns) and glyphs (fonts for label text) **cannot** be diffed. If the sprites or fonts used in the current + * style and the given style are different in any way, the map renderer will force a full update, removing the current style and building + * the given one from scratch. + * + * + * @param style A JSON object conforming to the schema described in the + * [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/), or a URL to such JSON. + * @param {Object} [options] Options object. + * @param {boolean} [options.diff=true] If false, force a 'full' update, removing the current style + * and building the given one instead of attempting a diff-based update. + * @param {string} [options.localIdeographFontFamily='sans-serif'] Defines a CSS + * font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' and 'Hangul Syllables' ranges. + * In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold). + * Set to `false`, to enable font settings from the map's style for these glyph ranges. + * Forces a full update. + * @returns {Map} `this` + * + * @example + * map.setStyle("mapbox://styles/mapbox/streets-v11"); + * + * @see [Change a map's style](https://www.mapbox.com/mapbox-gl-js/example/setstyle/) + */ + setStyle(style: StyleSpecification | string | null, options?: {diff?: boolean} & StyleOptions) { + options = extend({}, {localIdeographFontFamily: this._localIdeographFontFamily}, options); + + if ((options.diff !== false && options.localIdeographFontFamily === this._localIdeographFontFamily) && this.style && style) { + this._diffStyle(style, options); + return this; + } else { + this._localIdeographFontFamily = options.localIdeographFontFamily; + return this._updateStyle(style, options); + } + } + + _getUIString(key: string) { + const str = this._locale[key]; + if (str == null) { + throw new Error(`Missing UI string '${key}'`); + } + + return str; + } + + _updateStyle(style: StyleSpecification | string | null, options?: {diff?: boolean} & StyleOptions) { + if (this.style) { + this.style.setEventedParent(null); + this.style._remove(); + } + + if (!style) { + delete this.style; + return this; + } else { + this.style = new Style(this, options || {}); + } + + this.style.setEventedParent(this, {style: this.style}); + + if (typeof style === 'string') { + this.style.loadURL(style); + } else { + this.style.loadJSON(style); + } + + return this; + } + + _lazyInitEmptyStyle() { + if (!this.style) { + this.style = new Style(this, {}); + this.style.setEventedParent(this, {style: this.style}); + this.style.loadEmpty(); + } + } + + _diffStyle(style: StyleSpecification | string, options?: {diff?: boolean} & StyleOptions) { + if (typeof style === 'string') { + const url = this._requestManager.normalizeStyleURL(style); + const request = this._requestManager.transformRequest(url, ResourceType.Style); + getJSON(request, (error: ?Error, json: ?Object) => { + if (error) { + this.fire(new ErrorEvent(error)); + } else if (json) { + this._updateDiff(json, options); + } + }); + } else if (typeof style === 'object') { + this._updateDiff(style, options); + } + } + + _updateDiff(style: StyleSpecification, options?: {diff?: boolean} & StyleOptions) { + try { + if (this.style.setState(style)) { + this._update(true); + } + } catch (e) { + warnOnce( + `Unable to perform style diff: ${e.message || e.error || e}. Rebuilding the style from scratch.` + ); + this._updateStyle(style, options); + } + } + + /** + * Returns the map's Mapbox [style](https://docs.mapbox.com/help/glossary/style/) object, a JSON object which can be used to recreate the map's style. + * + * @returns {Object} The map's style JSON object. + * + * @example + * var styleJson = map.getStyle(); + * + */ + getStyle() { + if (this.style) { + return this.style.serialize(); + } + } + + /** + * Returns a Boolean indicating whether the map's style is fully loaded. + * + * @returns {boolean} A Boolean indicating whether the style is fully loaded. + * + * @example + * var styleLoadStatus = map.isStyleLoaded(); + */ + isStyleLoaded() { + if (!this.style) return warnOnce('There is no style added to the map.'); + return this.style.loaded(); + } + + /** + * Adds a source to the map's style. + * + * @param {string} id The ID of the source to add. Must not conflict with existing sources. + * @param {Object} source The source object, conforming to the + * Mapbox Style Specification's [source definition](https://www.mapbox.com/mapbox-gl-style-spec/#sources) or + * {@link CanvasSourceOptions}. + * @fires source.add + * @returns {Map} `this` + * @example + * map.addSource('my-data', { + * type: 'vector', + * url: 'mapbox://myusername.tilesetid' + * }); + * @example + * map.addSource('my-data', { + * "type": "geojson", + * "data": { + * "type": "Feature", + * "geometry": { + * "type": "Point", + * "coordinates": [-77.0323, 38.9131] + * }, + * "properties": { + * "title": "Mapbox DC", + * "marker-symbol": "monument" + * } + * } + * }); + * @see Vector source: [Show and hide layers](https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/) + * @see GeoJSON source: [Add live realtime data](https://docs.mapbox.com/mapbox-gl-js/example/live-geojson/) + * @see Raster DEM source: [Add hillshading](https://docs.mapbox.com/mapbox-gl-js/example/hillshade/) + */ + addSource(id: string, source: SourceSpecification) { + this._lazyInitEmptyStyle(); + this.style.addSource(id, source); + return this._update(true); + } + + /** + * Returns a Boolean indicating whether the source is loaded. Returns `true` if the source with + * the given ID in the map's style has no outstanding network requests, otherwise `false`. + * + * @param {string} id The ID of the source to be checked. + * @returns {boolean} A Boolean indicating whether the source is loaded. + * @example + * var sourceLoaded = map.isSourceLoaded('bathymetry-data'); + */ + isSourceLoaded(id: string) { + const source = this.style && this.style.sourceCaches[id]; + if (source === undefined) { + this.fire(new ErrorEvent(new Error(`There is no source with ID '${id}'`))); + return; + } + return source.loaded(); + } + + /** + * Returns a Boolean indicating whether all tiles in the viewport from all sources on + * the style are loaded. + * + * @returns {boolean} A Boolean indicating whether all tiles are loaded. + * @example + * var tilesLoaded = map.areTilesLoaded(); + */ + + areTilesLoaded() { + const sources = this.style && this.style.sourceCaches; + for (const id in sources) { + const source = sources[id]; + const tiles = source._tiles; + for (const t in tiles) { + const tile = tiles[t]; + if (!(tile.state === 'loaded' || tile.state === 'errored')) return false; + } + } + return true; + } + + /** + * Adds a [custom source type](#Custom Sources), making it available for use with + * {@link Map#addSource}. + * @private + * @param {string} name The name of the source type; source definition objects use this name in the `{type: ...}` field. + * @param {Function} SourceType A {@link Source} constructor. + * @param {Function} callback Called when the source type is ready or with an error argument if there is an error. + */ + addSourceType(name: string, SourceType: any, callback: Function) { + this._lazyInitEmptyStyle(); + return this.style.addSourceType(name, SourceType, callback); + } + + /** + * Removes a source from the map's style. + * + * @param {string} id The ID of the source to remove. + * @returns {Map} `this` + * @example + * map.removeSource('bathymetry-data'); + */ + removeSource(id: string) { + this.style.removeSource(id); + return this._update(true); + } + + /** + * Returns the source with the specified ID in the map's style. + * + * This method is often used to update a source using the instance members for the relevant + * source type as defined in [Sources](#sources). + * For example, setting the `data` for a GeoJSON source or updating the `url` and `coordinates` + * of an image source. + * + * @param {string} id The ID of the source to get. + * @returns {?Object} The style source with the specified ID or `undefined` if the ID + * corresponds to no existing sources. + * The shape of the object varies by source type. + * A list of options for each source type is available on the Mapbox Style Specification's + * [Sources](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/) page. + * @example + * var sourceObject = map.getSource('points'); + * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/) + * @see [Animate a point](https://docs.mapbox.com/mapbox-gl-js/example/animate-point-along-line/) + * @see [Add live realtime data](https://docs.mapbox.com/mapbox-gl-js/example/live-geojson/) + */ + getSource(id: string) { + return this.style.getSource(id); + } + + // eslint-disable-next-line jsdoc/require-returns + /** + * Add an image to the style. This image can be displayed on the map like any other icon in the style's + * [sprite](https://docs.mapbox.com/help/glossary/sprite/) using the image's ID with + * [`icon-image`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-icon-image), + * [`background-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-background-background-pattern), + * [`fill-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-fill-fill-pattern), + * or [`line-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-line-line-pattern). + * A {@link Map.event:error} event will be fired if there is not enough space in the sprite to add this image. + * + * @param id The ID of the image. + * @param image The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data` + * properties with the same format as `ImageData`. + * @param options Options object. + * @param options.pixelRatio The ratio of pixels in the image to physical pixels on the screen + * @param options.sdf Whether the image should be interpreted as an SDF image + * @param options.content `[x1, y1, x2, y2]` If `icon-text-fit` is used in a layer with this image, this option defines the part of the image that can be covered by the content in `text-field`. + * @param options.stretchX `[[x1, x2], ...]` If `icon-text-fit` is used in a layer with this image, this option defines the part(s) of the image that can be stretched horizontally. + * @param options.stretchY `[[y1, y2], ...]` If `icon-text-fit` is used in a layer with this image, this option defines the part(s) of the image that can be stretched vertically. + * + * @example + * // If the style's sprite does not already contain an image with ID 'cat', + * // add the image 'cat-icon.png' to the style's sprite with the ID 'cat'. + * map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png', function(error, image) { + * if (error) throw error; + * if (!map.hasImage('cat')) map.addImage('cat', image); + * }); + * + * + * // Add a stretchable image that can be used with `icon-text-fit` + * // In this example, the image is 600px wide by 400px high. + * map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png', function(error, image) { + * if (error) throw error; + * if (!map.hasImage('border-image')) { + * map.addImage('border-image', image, { + * content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border + * stretchX: [[16, 584]], // stretch everything horizontally except the 16px border + * stretchY: [[16, 384]], // stretch everything vertically except the 16px border + * }); + * } + * }); + * + * + * @see Use `HTMLImageElement`: [Add an icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image/) + * @see Use `ImageData`: [Add a generated icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image-generated/) + */ + addImage(id: string, + image: HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: Uint8Array | Uint8ClampedArray} | StyleImageInterface, + {pixelRatio = 1, sdf = false, stretchX, stretchY, content}: $Shape = {}) { + this._lazyInitEmptyStyle(); + const version = 0; + + if (image instanceof HTMLImageElement || (ImageBitmap && image instanceof ImageBitmap)) { + const {width, height, data} = browser.getImageData(image); + this.style.addImage(id, {data: new RGBAImage({width, height}, data), pixelRatio, stretchX, stretchY, content, sdf, version}); + } else if (image.width === undefined || image.height === undefined) { + return this.fire(new ErrorEvent(new Error( + 'Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' + + 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`'))); + } else { + const {width, height, data} = image; + const userImage = ((image: any): StyleImageInterface); + + this.style.addImage(id, { + data: new RGBAImage({width, height}, new Uint8Array(data)), + pixelRatio, + stretchX, + stretchY, + content, + sdf, + version, + userImage + }); + + if (userImage.onAdd) { + userImage.onAdd(this, id); + } + } + } + + // eslint-disable-next-line jsdoc/require-returns + /** + * Update an existing image in a style. This image can be displayed on the map like any other icon in the style's + * [sprite](https://docs.mapbox.com/help/glossary/sprite/) using the image's ID with + * [`icon-image`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-icon-image), + * [`background-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-background-background-pattern), + * [`fill-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-fill-fill-pattern), + * or [`line-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-line-line-pattern). + * + * @param id The ID of the image. + * @param image The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data` + * properties with the same format as `ImageData`. + * + * @example + * // If an image with the ID 'cat' already exists in the style's sprite, + * // replace that image with a new image, 'other-cat-icon.png'. + * if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png'); + */ + updateImage(id: string, + image: HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: Uint8Array | Uint8ClampedArray} | StyleImageInterface) { + + const existingImage = this.style.getImage(id); + if (!existingImage) { + return this.fire(new ErrorEvent(new Error( + 'The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.'))); + } + const imageData = (image instanceof HTMLImageElement || (ImageBitmap && image instanceof ImageBitmap)) ? browser.getImageData(image) : image; + const {width, height, data} = imageData; + + if (width === undefined || height === undefined) { + return this.fire(new ErrorEvent(new Error( + 'Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' + + 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`'))); + } + + if (width !== existingImage.data.width || height !== existingImage.data.height) { + return this.fire(new ErrorEvent(new Error( + 'The width and height of the updated image must be that same as the previous version of the image'))); + } + + const copy = !(image instanceof HTMLImageElement || (ImageBitmap && image instanceof ImageBitmap)); + existingImage.data.replace(data, copy); + + this.style.updateImage(id, existingImage); + } + + /** + * Check whether or not an image with a specific ID exists in the style. This checks both images + * in the style's original [sprite](https://docs.mapbox.com/help/glossary/sprite/) and any images + * that have been added at runtime using {@link Map#addImage}. + * + * @param id The ID of the image. + * + * @returns {boolean} A Boolean indicating whether the image exists. + * @example + * // Check if an image with the ID 'cat' exists in + * // the style's sprite. + * var catIconExists = map.hasImage('cat'); + */ + hasImage(id: string): boolean { + if (!id) { + this.fire(new ErrorEvent(new Error('Missing required image id'))); + return false; + } + + return !!this.style.getImage(id); + } + + /** + * Remove an image from a style. This can be an image from the style's original + * [sprite](https://docs.mapbox.com/help/glossary/sprite/) or any images + * that have been added at runtime using {@link Map#addImage}. + * + * @param id The ID of the image. + * + * @example + * // If an image with the ID 'cat' exists in + * // the style's sprite, remove it. + * if (map.hasImage('cat')) map.removeImage('cat'); + */ + removeImage(id: string) { + this.style.removeImage(id); + } + + /** + * Load an image from an external URL to be used with {@link Map#addImage}. External + * domains must support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS). + * + * @param {string} url The URL of the image file. Image file must be in png, webp, or jpg format. + * @param {Function} callback Expecting `callback(error, data)`. Called when the image has loaded or with an error argument if there is an error. + * + * @example + * // Load an image from an external URL. + * map.loadImage('http://placekitten.com/50/50', function(error, image) { + * if (error) throw error; + * // Add the loaded image to the style's sprite with the ID 'kitten'. + * map.addImage('kitten', image); + * }); + * + * @see [Add an icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image/) + */ + loadImage(url: string, callback: Function) { + getImage(this._requestManager.transformRequest(url, ResourceType.Image), callback); + } + + /** + * Returns an Array of strings containing the IDs of all images currently available in the map. + * This includes both images from the style's original [sprite](https://docs.mapbox.com/help/glossary/sprite/) + * and any images that have been added at runtime using {@link Map#addImage}. + * + * @returns {Array} An Array of strings containing the names of all sprites/images currently available in the map. + * + * @example + * var allImages = map.listImages(); + * + */ + listImages() { + return this.style.listImages(); + } + + /** + * Adds a [Mapbox style layer](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers) + * to the map's style. + * + * A layer defines how data from a specified source will be styled. Read more about layer types + * and available paint and layout properties in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers). + * + * @param {Object | CustomLayerInterface} layer The layer to add, conforming to either the Mapbox Style Specification's [layer definition](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers) or, less commonly, the {@link CustomLayerInterface} specification. + * The Mapbox Style Specification's layer definition is appropriate for most layers. + * + * @param {string} layer.id A unique idenfier that you define. + * @param {string} layer.type The type of layer (for example `fill` or `symbol`). + * A list of layer types is available in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#type). + * + * (This can also be `custom`. For more information, see {@link CustomLayerInterface}.) + * @param {string | Object} [layer.source] The data source for the layer. + * Reference a source that has _already been defined_ using the source's unique id. + * Reference a _new source_ using a source object (as defined in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/)) directly. + * This is **required** for all `layer.type` options _except_ for `custom`. + * @param {string} [layer.sourceLayer] (optional) The name of the [source layer](https://docs.mapbox.com/help/glossary/source-layer/) within the specified `layer.source` to use for this style layer. + * This is only applicable for vector tile sources and is **required** when `layer.source` is of the type `vector`. + * @param {array} [layer.filter] (optional) An expression specifying conditions on source features. + * Only features that match the filter are displayed. + * The Mapbox Style Specification includes more information on the limitations of the [`filter`](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter) parameter + * and a complete list of available [expressions](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/). + * If no filter is provided, all features in the source (or source layer for vector tilesets) will be displayed. + * @param {Object} [layer.paint] (optional) Paint properties for the layer. + * Available paint properties vary by `layer.type`. + * A full list of paint properties for each layer type is available in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/). + * If no paint properties are specified, default values will be used. + * @param {Object} [layer.layout] (optional) Layout properties for the layer. + * Available layout properties vary by `layer.type`. + * A full list of layout properties for each layer type is available in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/). + * If no layout properties are specified, default values will be used. + * @param {number} [layer.maxzoom] (optional) The maximum zoom level for the layer. + * At zoom levels equal to or greater than the maxzoom, the layer will be hidden. + * The value can be any number between `0` and `24` (inclusive). + * If no maxzoom is provided, the layer will be visible at all zoom levels for which there are tiles available. + * @param {number} [layer.minzoom] (optional) The minimum zoom level for the layer. + * At zoom levels less than the minzoom, the layer will be hidden. + * The value can be any number between `0` and `24` (inclusive). + * If no minzoom is provided, the layer will be visible at all zoom levels for which there are tiles available. + * @param {Object} [layer.metadata] (optional) Arbitrary properties useful to track with the layer, but do not influence rendering. + * @param {string} [layer.renderingMode] This is only applicable for layers with the type `custom`. + * See {@link CustomLayerInterface} for more information. + * @param {string} [beforeId] The ID of an existing layer to insert the new layer before, + * resulting in the new layer appearing visually beneath the existing layer. + * If this argument is not specified, the layer will be appended to the end of the layers array + * and appear visually above all other layers. + * + * @returns {Map} `this` + * + * @example + * // Add a circle layer with a vector source + * map.addLayer({ + * id: 'points-of-interest', + * source: { + * type: 'vector', + * url: 'mapbox://mapbox.mapbox-streets-v8' + * }, + * 'source-layer': 'poi_label', + * type: 'circle', + * paint: { + * // Mapbox Style Specification paint properties + * }, + * layout: { + * // Mapbox Style Specification layout properties + * } + * }); + * + * @example + * // Define a source before using it to create a new layer + * map.addSource('state-data', { + * type: 'geojson', + * data: 'path/to/data.geojson' + * }); + * + * map.addLayer({ + * id: 'states', + * // References the GeoJSON source defined above + * // and does not require a `source-layer` + * source: 'state-data', + * type: 'symbol', + * layout: { + * // Set the label content to the + * // feature's `name` property + * text-field: ['get', 'name'] + * } + * }); + * + * @example + * // Add a new symbol layer before an existing layer + * map.addLayer({ + * id: 'states', + * // References a source that's already been defined + * source: 'state-data', + * type: 'symbol', + * layout: { + * // Set the label content to the + * // feature's `name` property + * text-field: ['get', 'name'] + * } + * // Add the layer before the existing `cities` layer + * }, 'cities'); + * + * @see [Create and style clusters](https://docs.mapbox.com/mapbox-gl-js/example/cluster/) + * @see [Add a vector tile source](https://docs.mapbox.com/mapbox-gl-js/example/vector-source/) + * @see [Add a WMS source](https://docs.mapbox.com/mapbox-gl-js/example/wms/) + */ + addLayer(layer: LayerSpecification | CustomLayerInterface, beforeId?: string) { + this._lazyInitEmptyStyle(); + this.style.addLayer(layer, beforeId); + return this._update(true); + } + + /** + * Moves a layer to a different z-position. + * + * @param {string} id The ID of the layer to move. + * @param {string} [beforeId] The ID of an existing layer to insert the new layer before. When viewing the map, the `id` layer will appear beneath the `beforeId` layer. If `beforeId` is omitted, the layer will be appended to the end of the layers array and appear above all other layers on the map. + * @returns {Map} `this` + * + * @example + * // Move a layer with ID 'polygon' before the layer with ID 'country-label'. The `polygon` layer will appear beneath the `country-label` layer on the map. + * map.moveLayer('polygon', 'country-label'); + */ + moveLayer(id: string, beforeId?: string) { + this.style.moveLayer(id, beforeId); + return this._update(true); + } + + // eslint-disable-next-line jsdoc/require-returns + /** + * Removes the layer with the given ID from the map's style. + * + * If no such layer exists, an `error` event is fired. + * + * @param {string} id id of the layer to remove + * @fires error + * + * @example + * // If a layer with ID 'state-data' exists, remove it. + * if (map.getLayer('state-data')) map.removeLayer('state-data'); + */ + removeLayer(id: string) { + this.style.removeLayer(id); + return this._update(true); + } + + /** + * Returns the layer with the specified ID in the map's style. + * + * @param {string} id The ID of the layer to get. + * @returns {?Object} The layer with the specified ID, or `undefined` + * if the ID corresponds to no existing layers. + * + * @example + * var stateDataLayer = map.getLayer('state-data'); + * + * @see [Filter symbols by toggling a list](https://www.mapbox.com/mapbox-gl-js/example/filter-markers/) + * @see [Filter symbols by text input](https://www.mapbox.com/mapbox-gl-js/example/filter-markers-by-input/) + */ + getLayer(id: string) { + return this.style.getLayer(id); + } + + /** + * Sets the zoom extent for the specified style layer. The zoom extent includes the + * [minimum zoom level](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-minzoom) + * and [maximum zoom level](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-maxzoom)) + * at which the layer will be rendered. + * + * Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the + * minimum zoom level of the _source layer_ because the data does not exist at those zoom levels. If the minimum + * zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style + * layer will not be rendered at all zoom levels in the zoom range. + * + * @param {string} layerId The ID of the layer to which the zoom extent will be applied. + * @param {number} minzoom The minimum zoom to set (0-24). + * @param {number} maxzoom The maximum zoom to set (0-24). + * @returns {Map} `this` + * + * @example + * map.setLayerZoomRange('my-layer', 2, 5); + * + */ + setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number) { + this.style.setLayerZoomRange(layerId, minzoom, maxzoom); + return this._update(true); + } + + /** + * Sets the filter for the specified style layer. + * + * Filters control which features a style layer renders from its source. + * Any feature for which the filter expression evaluates to `true` will be + * rendered on the map. Those that are false will be hidden. + * + * Use `setFilter` to show a subset of your source data. + * + * To clear the filter, pass `null` or `undefined` as the second parameter. + * + * @param {string} layerId The ID of the layer to which the filter will be applied. + * @param {Array | null | undefined} filter The filter, conforming to the Mapbox Style Specification's + * [filter definition](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter). If `null` or `undefined` is provided, the function removes any existing filter from the layer. + * @param {Object} [options] Options object. + * @param {boolean} [options.validate=true] Whether to check if the filter conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. + * @returns {Map} `this` + * + * @example + * // display only features with the 'name' property 'USA' + * map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']); + * @example + * // display only features with five or more 'available-spots' + * map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]); + * @example + * // remove the filter for the 'bike-docks' style layer + * map.setFilter('bike-docks', null); + * + * @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/) + * @see [Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/) + * @see [Create a timeline animation](https://www.mapbox.com/mapbox-gl-js/example/timeline-animation/) + * @see Tutorial: [Show changes over time](https://docs.mapbox.com/help/tutorials/show-changes-over-time/) + */ + setFilter(layerId: string, filter: ?FilterSpecification, options: StyleSetterOptions = {}) { + this.style.setFilter(layerId, filter, options); + return this._update(true); + } + + /** + * Returns the filter applied to the specified style layer. + * + * @param {string} layerId The ID of the style layer whose filter to get. + * @returns {Array} The layer's filter. + */ + getFilter(layerId: string) { + return this.style.getFilter(layerId); + } + + /** + * Sets the value of a paint property in the specified style layer. + * + * @param {string} layerId The ID of the layer to set the paint property in. + * @param {string} name The name of the paint property to set. + * @param {*} value The value of the paint property to set. + * Must be of a type appropriate for the property, as defined in the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/). + * @param {Object} [options] Options object. + * @param {boolean} [options.validate=true] Whether to check if `value` conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. + * @returns {Map} `this` + * @example + * map.setPaintProperty('my-layer', 'fill-color', '#faafee'); + * @see [Change a layer's color with buttons](https://www.mapbox.com/mapbox-gl-js/example/color-switcher/) + * @see [Adjust a layer's opacity](https://www.mapbox.com/mapbox-gl-js/example/adjust-layer-opacity/) + * @see [Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/) + */ + setPaintProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) { + this.style.setPaintProperty(layerId, name, value, options); + return this._update(true); + } + + /** + * Returns the value of a paint property in the specified style layer. + * + * @param {string} layerId The ID of the layer to get the paint property from. + * @param {string} name The name of a paint property to get. + * @returns {*} The value of the specified paint property. + */ + getPaintProperty(layerId: string, name: string) { + return this.style.getPaintProperty(layerId, name); + } + + /** + * Sets the value of a layout property in the specified style layer. + * + * @param {string} layerId The ID of the layer to set the layout property in. + * @param {string} name The name of the layout property to set. + * @param {*} value The value of the layout property. Must be of a type appropriate for the property, as defined in the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/). + * @param {Object} [options] Options object. + * @param {boolean} [options.validate=true] Whether to check if `value` conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. + * @returns {Map} `this` + * @example + * map.setLayoutProperty('my-layer', 'visibility', 'none'); + * @see [Show and hide layers](https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/) + */ + setLayoutProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) { + this.style.setLayoutProperty(layerId, name, value, options); + return this._update(true); + } + + /** + * Returns the value of a layout property in the specified style layer. + * + * @param {string} layerId The ID of the layer to get the layout property from. + * @param {string} name The name of the layout property to get. + * @returns {*} The value of the specified layout property. + */ + getLayoutProperty(layerId: string, name: string) { + return this.style.getLayoutProperty(layerId, name); + } + + /** + * Sets the any combination of light values. + * + * @param light Light properties to set. Must conform to the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#light). + * @param {Object} [options] Options object. + * @param {boolean} [options.validate=true] Whether to check if the filter conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. + * @returns {Map} `this` + * @example + * var layerVisibility = map.getLayoutProperty('my-layer', 'visibility'); + * @see [Show and hide layers](https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/) + */ + setLight(light: LightSpecification, options: StyleSetterOptions = {}) { + this._lazyInitEmptyStyle(); + this.style.setLight(light, options); + return this._update(true); + } + + /** + * Returns the value of the light object. + * + * @returns {Object} light Light properties of the style. + */ + getLight() { + return this.style.getLight(); + } + + // eslint-disable-next-line jsdoc/require-returns + /** + * Sets the `state` of a feature. + * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime. + * When using this method, the `state` object is merged with any existing key-value pairs in the feature's state. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * This method can only be used with sources that have a `feature.id` attribute. The `feature.id` attribute can be defined in three ways: + * - For vector or GeoJSON sources, including an `id` attribute in the original data file. + * - For vector or GeoJSON sources, using the [`promoteId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector-promoteId) option at the time the source is defined. + * - For GeoJSON sources, using the [`generateId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#geojson-generateId) option to auto-assign an `id` based on the feature's index in the source data. If you change feature data using `map.getSource('some id').setData(..)`, you may need to re-apply state taking into account updated `id` values. + * + * _Note: You can use the [`feature-state` expression](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#feature-state) to access the values in a feature's state object for the purposes of styling._ + * + * @param {Object} feature Feature identifier. Feature objects returned from + * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @param {string | number} feature.id Unique id of the feature. + * @param {string} feature.source The id of the vector or GeoJSON source for the feature. + * @param {string} [feature.sourceLayer] (optional) *For vector tile sources, `sourceLayer` is required.* + * @param {Object} state A set of key-value pairs. The values should be valid JSON types. + * + * @example + * // When the mouse moves over the `my-layer` layer, update + * // the feature state for the feature under the mouse + * map.on('mousemove', 'my-layer', function(e) { + * if (e.features.length > 0) { + * map.setFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id, + * }, { + * hover: true + * }); + * } + * }); + * + * @see [Create a hover effect](https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/) + * @see Tutorial: [Create interactive hover effects with Mapbox GL JS](https://docs.mapbox.com/help/tutorials/create-interactive-hover-effects-with-mapbox-gl-js/) + */ + setFeatureState(feature: { source: string; sourceLayer?: string; id: string | number; }, state: Object) { + this.style.setFeatureState(feature, state); + return this._update(); + } + + // eslint-disable-next-line jsdoc/require-returns + /** + * Removes the `state` of a feature, setting it back to the default behavior. + * If only a `target.source` is specified, it will remove the state for all features from that source. + * If `target.id` is also specified, it will remove all keys for that feature's state. + * If `key` is also specified, it removes only that key from that feature's state. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * @param {Object} target Identifier of where to remove state. It can be a source, a feature, or a specific key of feature. + * Feature objects returned from {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @param {string | number} target.id (optional) Unique id of the feature. Optional if key is not specified. + * @param {string} target.source The id of the vector or GeoJSON source for the feature. + * @param {string} [target.sourceLayer] (optional) *For vector tile sources, `sourceLayer` is required.* + * @param {string} key (optional) The key in the feature state to reset. + * + * @example + * // Reset the entire state object for all features + * // in the `my-source` source + * map.removeFeatureState({ + * source: 'my-source' + * }); + * + * @example + * // When the mouse leaves the `my-layer` layer, + * // reset the entire state object for the + * // feature under the mouse + * map.on('mouseleave', 'my-layer', function(e) { + * map.removeFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }); + * }); + * + * @example + * // When the mouse leaves the `my-layer` layer, + * // reset only the `hover` key-value pair in the + * // state for the feature under the mouse + * map.on('mouseleave', 'my-layer', function(e) { + * map.removeFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }, 'hover'); + * }); + * + */ + removeFeatureState(target: { source: string; sourceLayer?: string; id?: string | number; }, key?: string) { + this.style.removeFeatureState(target, key); + return this._update(); + } + + /** + * Gets the `state` of a feature. + * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime. + * Features are identified by their `feature.id` attribute, which can be any number or string. + * + * _Note: To access the values in a feature's state object for the purposes of styling the feature, use the [`feature-state` expression](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#feature-state)._ + * + * @param {Object} feature Feature identifier. Feature objects returned from + * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers. + * @param {string | number} feature.id Unique id of the feature. + * @param {string} feature.source The id of the vector or GeoJSON source for the feature. + * @param {string} [feature.sourceLayer] (optional) *For vector tile sources, `sourceLayer` is required.* + * + * @returns {Object} The state of the feature: a set of key-value pairs that was assigned to the feature at runtime. + * + * @example + * // When the mouse moves over the `my-layer` layer, + * // get the feature state for the feature under the mouse + * map.on('mousemove', 'my-layer', function(e) { + * if (e.features.length > 0) { + * map.getFeatureState({ + * source: 'my-source', + * sourceLayer: 'my-source-layer', + * id: e.features[0].id + * }); + * } + * }); + * + */ + getFeatureState(feature: { source: string; sourceLayer?: string; id: string | number; }): any { + return this.style.getFeatureState(feature); + } + + /** + * Returns the map's containing HTML element. + * + * @returns {HTMLElement} The map's container. + */ + getContainer() { + return this._container; + } + + /** + * Returns the HTML element containing the map's `` element. + * + * If you want to add non-GL overlays to the map, you should append them to this element. + * + * This is the element to which event bindings for map interactivity (such as panning and zooming) are + * attached. It will receive bubbled events from child elements such as the ``, but not from + * map controls. + * + * @returns {HTMLElement} The container of the map's ``. + * @see [Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/) + * @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/) + */ + getCanvasContainer() { + return this._canvasContainer; + } + + /** + * Returns the map's `` element. + * + * @returns {HTMLCanvasElement} The map's `` element. + * @see [Measure distances](https://www.mapbox.com/mapbox-gl-js/example/measure/) + * @see [Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/) + * @see [Center the map on a clicked symbol](https://www.mapbox.com/mapbox-gl-js/example/center-on-symbol/) + */ + getCanvas() { + return this._canvas; + } + + _containerDimensions() { + let width = 0; + let height = 0; + + if (this._container) { + width = this._container.clientWidth || 400; + height = this._container.clientHeight || 300; + } + + return [width, height]; + } + + _detectMissingCSS(): void { + const computedColor = window.getComputedStyle(this._missingCSSCanary).getPropertyValue('background-color'); + if (computedColor !== 'rgb(250, 128, 114)') { + warnOnce('This page appears to be missing CSS declarations for ' + + 'Mapbox GL JS, which may cause the map to display incorrectly. ' + + 'Please ensure your page includes mapbox-gl.css, as described ' + + 'in https://www.mapbox.com/mapbox-gl-js/api/.'); + } + } + + _setupContainer() { + const container = this._container; + container.classList.add('mapboxgl-map'); + + const missingCSSCanary = this._missingCSSCanary = DOM.create('div', 'mapboxgl-canary', container); + missingCSSCanary.style.visibility = 'hidden'; + this._detectMissingCSS(); + + const canvasContainer = this._canvasContainer = DOM.create('div', 'mapboxgl-canvas-container', container); + if (this._interactive) { + canvasContainer.classList.add('mapboxgl-interactive'); + } + + this._canvas = DOM.create('canvas', 'mapboxgl-canvas', canvasContainer); + this._canvas.addEventListener('webglcontextlost', this._contextLost, false); + this._canvas.addEventListener('webglcontextrestored', this._contextRestored, false); + this._canvas.setAttribute('tabindex', '0'); + this._canvas.setAttribute('aria-label', 'Map'); + this._canvas.setAttribute('role', 'region'); + + const dimensions = this._containerDimensions(); + this._resizeCanvas(dimensions[0], dimensions[1]); + + const controlContainer = this._controlContainer = DOM.create('div', 'mapboxgl-control-container', container); + const positions = this._controlPositions = {}; + ['top-left', 'top-right', 'bottom-left', 'bottom-right'].forEach((positionName) => { + positions[positionName] = DOM.create('div', `mapboxgl-ctrl-${positionName}`, controlContainer); + }); + + this._container.addEventListener('scroll', this._onMapScroll, false); + } + + _resizeCanvas(width: number, height: number) { + const pixelRatio = browser.devicePixelRatio || 1; + + // Request the required canvas size taking the pixelratio into account. + this._canvas.width = pixelRatio * width; + this._canvas.height = pixelRatio * height; + + // Maintain the same canvas size, potentially downscaling it for HiDPI displays + this._canvas.style.width = `${width}px`; + this._canvas.style.height = `${height}px`; + } + + _setupPainter() { + const attributes = extend({}, isSupported.webGLContextAttributes, { + failIfMajorPerformanceCaveat: this._failIfMajorPerformanceCaveat, + preserveDrawingBuffer: this._preserveDrawingBuffer, + antialias: this._antialias || false + }); + + const gl = this._canvas.getContext('webgl', attributes) || + this._canvas.getContext('experimental-webgl', attributes); + + if (!gl) { + this.fire(new ErrorEvent(new Error('Failed to initialize WebGL'))); + return; + } + + this.painter = new Painter(gl, this.transform); + + webpSupported.testSupport(gl); + } + + _contextLost(event: *) { + event.preventDefault(); + if (this._frame) { + this._frame.cancel(); + this._frame = null; + } + this.fire(new Event('webglcontextlost', {originalEvent: event})); + } + + _contextRestored(event: *) { + this._setupPainter(); + this.resize(); + this._update(); + this.fire(new Event('webglcontextrestored', {originalEvent: event})); + } + + _onMapScroll(event: *) { + if (event.target !== this._container) return; + + // Revert any scroll which would move the canvas outside of the view + this._container.scrollTop = 0; + this._container.scrollLeft = 0; + return false; + } + + /** + * Returns a Boolean indicating whether the map is fully loaded. + * + * Returns `false` if the style is not yet fully loaded, + * or if there has been a change to the sources or style that + * has not yet fully loaded. + * + * @returns {boolean} A Boolean indicating whether the map is fully loaded. + */ + loaded() { + return !this._styleDirty && !this._sourcesDirty && !!this.style && this.style.loaded(); + } + + /** + * Update this map's style and sources, and re-render the map. + * + * @param {boolean} updateStyle mark the map's style for reprocessing as + * well as its sources + * @returns {Map} this + * @private + */ + _update(updateStyle?: boolean) { + if (!this.style) return this; + + this._styleDirty = this._styleDirty || updateStyle; + this._sourcesDirty = true; + this.triggerRepaint(); + + return this; + } + + /** + * Request that the given callback be executed during the next render + * frame. Schedule a render frame if one is not already scheduled. + * @returns An id that can be used to cancel the callback + * @private + */ + _requestRenderFrame(callback: () => void): TaskID { + this._update(); + return this._renderTaskQueue.add(callback); + } + + _cancelRenderFrame(id: TaskID) { + this._renderTaskQueue.remove(id); + } + + /** + * Call when a (re-)render of the map is required: + * - The style has changed (`setPaintProperty()`, etc.) + * - Source data has changed (e.g. tiles have finished loading) + * - The map has is moving (or just finished moving) + * - A transition is in progress + * + * @param {number} paintStartTimeStamp The time when the animation frame began executing. + * + * @returns {Map} this + * @private + */ + _render(paintStartTimeStamp: number) { + let gpuTimer, frameStartTime = 0; + const extTimerQuery = this.painter.context.extTimerQuery; + if (this.listens('gpu-timing-frame')) { + gpuTimer = extTimerQuery.createQueryEXT(); + extTimerQuery.beginQueryEXT(extTimerQuery.TIME_ELAPSED_EXT, gpuTimer); + frameStartTime = browser.now(); + } + + // A custom layer may have used the context asynchronously. Mark the state as dirty. + this.painter.context.setDirty(); + this.painter.setBaseState(); + + this._renderTaskQueue.run(paintStartTimeStamp); + // A task queue callback may have fired a user event which may have removed the map + if (this._removed) return; + + let crossFading = false; + + // If the style has changed, the map is being zoomed, or a transition or fade is in progress: + // - Apply style changes (in a batch) + // - Recalculate paint properties. + if (this.style && this._styleDirty) { + this._styleDirty = false; + + const zoom = this.transform.zoom; + const now = browser.now(); + this.style.zoomHistory.update(zoom, now); + + const parameters = new EvaluationParameters(zoom, { + now, + fadeDuration: this._fadeDuration, + zoomHistory: this.style.zoomHistory, + transition: this.style.getTransition() + }); + + const factor = parameters.crossFadingFactor(); + if (factor !== 1 || factor !== this._crossFadingFactor) { + crossFading = true; + this._crossFadingFactor = factor; + } + + this.style.update(parameters); + } + + // If we are in _render for any reason other than an in-progress paint + // transition, update source caches to check for and load any tiles we + // need for the current transform + if (this.style && this._sourcesDirty) { + this._sourcesDirty = false; + this.style._updateSources(this.transform); + } + + this._placementDirty = this.style && this.style._updatePlacement(this.painter.transform, this.showCollisionBoxes, this._fadeDuration, this._crossSourceCollisions); + + // Actually draw + this.painter.render(this.style, { + showTileBoundaries: this.showTileBoundaries, + showOverdrawInspector: this._showOverdrawInspector, + rotating: this.isRotating(), + zooming: this.isZooming(), + moving: this.isMoving(), + fadeDuration: this._fadeDuration, + showPadding: this.showPadding, + gpuTiming: !!this.listens('gpu-timing-layer'), + }); + + this.fire(new Event('render')); + + if (this.loaded() && !this._loaded) { + this._loaded = true; + PerformanceUtils.mark(PerformanceMarkers.load); + this.fire(new Event('load')); + } + + if (this.style && (this.style.hasTransitions() || crossFading)) { + this._styleDirty = true; + } + + if (this.style && !this._placementDirty) { + // Since no fade operations are in progress, we can release + // all tiles held for fading. If we didn't do this, the tiles + // would just sit in the SourceCaches until the next render + this.style._releaseSymbolFadeTiles(); + } + + if (this.listens('gpu-timing-frame')) { + const renderCPUTime = browser.now() - frameStartTime; + extTimerQuery.endQueryEXT(extTimerQuery.TIME_ELAPSED_EXT, gpuTimer); + setTimeout(() => { + const renderGPUTime = extTimerQuery.getQueryObjectEXT(gpuTimer, extTimerQuery.QUERY_RESULT_EXT) / (1000 * 1000); + extTimerQuery.deleteQueryEXT(gpuTimer); + this.fire(new Event('gpu-timing-frame', { + cpuTime: renderCPUTime, + gpuTime: renderGPUTime + })); + }, 50); // Wait 50ms to give time for all GPU calls to finish before querying + } + + if (this.listens('gpu-timing-layer')) { + // Resetting the Painter's per-layer timing queries here allows us to isolate + // the queries to individual frames. + const frameLayerQueries = this.painter.collectGpuTimers(); + + setTimeout(() => { + const renderedLayerTimes = this.painter.queryGpuTimers(frameLayerQueries); + + this.fire(new Event('gpu-timing-layer', { + layerTimes: renderedLayerTimes + })); + }, 50); // Wait 50ms to give time for all GPU calls to finish before querying + } + + // Schedule another render frame if it's needed. + // + // Even though `_styleDirty` and `_sourcesDirty` are reset in this + // method, synchronous events fired during Style#update or + // Style#_updateSources could have caused them to be set again. + const somethingDirty = this._sourcesDirty || this._styleDirty || this._placementDirty; + if (somethingDirty || this._repaint) { + this.triggerRepaint(); + } else if (!this.isMoving() && this.loaded()) { + this.fire(new Event('idle')); + } + + if (this._loaded && !this._fullyLoaded && !somethingDirty) { + this._fullyLoaded = true; + PerformanceUtils.mark(PerformanceMarkers.fullLoad); + } + + return this; + } + + /** + * Clean up and release all internal resources associated with this map. + * + * This includes DOM elements, event bindings, web workers, and WebGL resources. + * + * Use this method when you are done using the map and wish to ensure that it no + * longer consumes browser resources. Afterwards, you must not call any other + * methods on the map. + */ + remove() { + if (this._hash) this._hash.remove(); + + for (const control of this._controls) control.onRemove(this); + this._controls = []; + + if (this._frame) { + this._frame.cancel(); + this._frame = null; + } + this._renderTaskQueue.clear(); + this.painter.destroy(); + this.handlers.destroy(); + delete this.handlers; + this.setStyle(null); + if (typeof window !== 'undefined') { + window.removeEventListener('resize', this._onWindowResize, false); + window.removeEventListener('orientationchange', this._onWindowResize, false); + window.removeEventListener('online', this._onWindowOnline, false); + } + + const extension = this.painter.context.gl.getExtension('WEBGL_lose_context'); + if (extension) extension.loseContext(); + removeNode(this._canvasContainer); + removeNode(this._controlContainer); + removeNode(this._missingCSSCanary); + this._container.classList.remove('mapboxgl-map'); + + PerformanceUtils.clearMetrics(); + + this._removed = true; + this.fire(new Event('remove')); + } + + /** + * Trigger the rendering of a single frame. Use this method with custom layers to + * repaint the map when the layer changes. Calling this multiple times before the + * next frame is rendered will still result in only a single frame being rendered. + * @example + * map.triggerRepaint(); + * @see [Add a 3D model](https://docs.mapbox.com/mapbox-gl-js/example/add-3d-model/) + * @see [Add an animated icon to the map](https://docs.mapbox.com/mapbox-gl-js/example/add-image-animated/) + */ + triggerRepaint() { + if (this.style && !this._frame) { + this._frame = browser.frame((paintStartTimeStamp: number) => { + PerformanceUtils.frame(paintStartTimeStamp); + this._frame = null; + this._render(paintStartTimeStamp); + }); + } + } + + _onWindowOnline() { + this._update(); + } + + _onWindowResize(event: Event) { + if (this._trackResize) { + this.resize({originalEvent: event})._update(); + } + } + + /** + * Gets and sets a Boolean indicating whether the map will render an outline + * around each tile and the tile ID. These tile boundaries are useful for + * debugging. + * + * The uncompressed file size of the first vector source is drawn in the top left + * corner of each tile, next to the tile ID. + * + * @name showTileBoundaries + * @type {boolean} + * @instance + * @memberof Map + * @example + * map.showTileBoundaries = true; + */ + get showTileBoundaries(): boolean { return !!this._showTileBoundaries; } + set showTileBoundaries(value: boolean) { + if (this._showTileBoundaries === value) return; + this._showTileBoundaries = value; + this._update(); + } + + /** + * Gets and sets a Boolean indicating whether the map will visualize + * the padding offsets. + * + * @name showPadding + * @type {boolean} + * @instance + * @memberof Map + */ + get showPadding(): boolean { return !!this._showPadding; } + set showPadding(value: boolean) { + if (this._showPadding === value) return; + this._showPadding = value; + this._update(); + } + + /** + * Gets and sets a Boolean indicating whether the map will render boxes + * around all symbols in the data source, revealing which symbols + * were rendered or which were hidden due to collisions. + * This information is useful for debugging. + * + * @name showCollisionBoxes + * @type {boolean} + * @instance + * @memberof Map + */ + get showCollisionBoxes(): boolean { return !!this._showCollisionBoxes; } + set showCollisionBoxes(value: boolean) { + if (this._showCollisionBoxes === value) return; + this._showCollisionBoxes = value; + if (value) { + // When we turn collision boxes on we have to generate them for existing tiles + // When we turn them off, there's no cost to leaving existing boxes in place + this.style._generateCollisionBoxes(); + } else { + // Otherwise, call an update to remove collision boxes + this._update(); + } + } + + /* + * Gets and sets a Boolean indicating whether the map should color-code + * each fragment to show how many times it has been shaded. + * White fragments have been shaded 8 or more times. + * Black fragments have been shaded 0 times. + * This information is useful for debugging. + * + * @name showOverdraw + * @type {boolean} + * @instance + * @memberof Map + */ + get showOverdrawInspector(): boolean { return !!this._showOverdrawInspector; } + set showOverdrawInspector(value: boolean) { + if (this._showOverdrawInspector === value) return; + this._showOverdrawInspector = value; + this._update(); + } + + /** + * Gets and sets a Boolean indicating whether the map will + * continuously repaint. This information is useful for analyzing performance. + * + * @name repaint + * @type {boolean} + * @instance + * @memberof Map + */ + get repaint(): boolean { return !!this._repaint; } + set repaint(value: boolean) { + if (this._repaint !== value) { + this._repaint = value; + this.triggerRepaint(); + } + } + // show vertices + get vertices(): boolean { return !!this._vertices; } + set vertices(value: boolean) { this._vertices = value; this._update(); } + + // for cache browser tests + _setCacheLimits(limit: number, checkThreshold: number) { + setCacheLimits(limit, checkThreshold); + } + + /** + * The version of Mapbox GL JS in use as specified in package.json, CHANGELOG.md, and the GitHub release. + * + * @name version + * @instance + * @memberof Map + * @var {string} version + */ + + get version(): string { return version; } +} + +export default Map; + +function removeNode(node) { + if (node.parentNode) { + node.parentNode.removeChild(node); + } +} + +/** + * Interface for interactive controls added to the map. This is a + * specification for implementers to model: it is not + * an exported method or class. + * + * Controls must implement `onAdd` and `onRemove`, and must own an + * element, which is often a `div` element. To use Mapbox GL JS's + * default control styling, add the `mapboxgl-ctrl` class to your control's + * node. + * + * @interface IControl + * @example + * // Control implemented as ES6 class + * class HelloWorldControl { + * onAdd(map) { + * this._map = map; + * this._container = document.createElement('div'); + * this._container.className = 'mapboxgl-ctrl'; + * this._container.textContent = 'Hello, world'; + * return this._container; + * } + * + * onRemove() { + * this._container.parentNode.removeChild(this._container); + * this._map = undefined; + * } + * } + * + * // Control implemented as ES5 prototypical class + * function HelloWorldControl() { } + * + * HelloWorldControl.prototype.onAdd = function(map) { + * this._map = map; + * this._container = document.createElement('div'); + * this._container.className = 'mapboxgl-ctrl'; + * this._container.textContent = 'Hello, world'; + * return this._container; + * }; + * + * HelloWorldControl.prototype.onRemove = function () { + * this._container.parentNode.removeChild(this._container); + * this._map = undefined; + * }; + */ + +/** + * Register a control on the map and give it a chance to register event listeners + * and resources. This method is called by {@link Map#addControl} + * internally. + * + * @function + * @memberof IControl + * @instance + * @name onAdd + * @param {Map} map the Map this control will be added to + * @returns {HTMLElement} The control's container element. This should + * be created by the control and returned by onAdd without being attached + * to the DOM: the map will insert the control's element into the DOM + * as necessary. + */ + +/** + * Unregister a control on the map and give it a chance to detach event listeners + * and resources. This method is called by {@link Map#removeControl} + * internally. + * + * @function + * @memberof IControl + * @instance + * @name onRemove + * @param {Map} map the Map this control will be removed from + * @returns {undefined} there is no required return value for this method + */ + +/** + * Optionally provide a default position for this control. If this method + * is implemented and {@link Map#addControl} is called without the `position` + * parameter, the value returned by getDefaultPosition will be used as the + * control's position. + * + * @function + * @memberof IControl + * @instance + * @name getDefaultPosition + * @returns {string} a control position, one of the values valid in addControl. + */ + +/** + * A [`Point` geometry](https://github.com/mapbox/point-geometry) object, which has + * `x` and `y` properties representing screen coordinates in pixels. + * + * @typedef {Object} Point + * @example + * var point = new mapboxgl.Point(-77, 38); + */ + +/** + * A {@link Point} or an array of two numbers representing `x` and `y` screen coordinates in pixels. + * + * @typedef {(Point | Array)} PointLike + * @example + * var p1 = new mapboxgl.Point(-77, 38); // a PointLike which is a Point + * var p2 = [-77, 38]; // a PointLike which is an array of two numbers + */ diff --git a/node_modules/mapbox-gl/src/ui/marker.js b/node_modules/mapbox-gl/src/ui/marker.js new file mode 100644 index 0000000000000000000000000000000000000000..75d2de3d787e3de2ec16e7f6d16c4bc5d1ebe7da --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/marker.js @@ -0,0 +1,672 @@ +// @flow + +import DOM from '../util/dom'; +import window from '../util/window'; +import LngLat from '../geo/lng_lat'; +import Point from '@mapbox/point-geometry'; +import smartWrap from '../util/smart_wrap'; +import {bindAll, extend} from '../util/util'; +import {type Anchor, anchorTranslate, applyAnchorClass} from './anchor'; +import {Event, Evented} from '../util/evented'; +import type Map from './map'; +import type Popup from './popup'; +import type {LngLatLike} from "../geo/lng_lat"; +import type {MapMouseEvent, MapTouchEvent} from './events'; +import type {PointLike} from '@mapbox/point-geometry'; + +type Options = { + element?: HTMLElement, + offset?: PointLike, + anchor?: Anchor, + color?: string, + scale?: number, + draggable?: boolean, + clickTolerance?: number, + rotation?: number, + rotationAlignment?: string, + pitchAlignment?: string +}; + +/** + * Creates a marker component + * @param {Object} [options] + * @param {HTMLElement} [options.element] DOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker. + * @param {string} [options.anchor='center'] A string indicating the part of the Marker that should be positioned closest to the coordinate set via {@link Marker#setLngLat}. + * Options are `'center'`, `'top'`, `'bottom'`, `'left'`, `'right'`, `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. + * @param {PointLike} [options.offset] The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up. + * @param {string} [options.color='#3FB1CE'] The color to use for the default marker if options.element is not provided. The default is light blue. + * @param {number} [options.scale=1] The scale to use for the default marker if options.element is not provided. The default scale corresponds to a height of `41px` and a width of `27px`. + * @param {boolean} [options.draggable=false] A boolean indicating whether or not a marker is able to be dragged to a new position on the map. + * @param {number} [options.clickTolerance=0] The max number of pixels a user can shift the mouse pointer during a click on the marker for it to be considered a valid click (as opposed to a marker drag). The default is to inherit map's clickTolerance. + * @param {number} [options.rotation=0] The rotation angle of the marker in degrees, relative to its respective `rotationAlignment` setting. A positive value will rotate the marker clockwise. + * @param {string} [options.pitchAlignment='auto'] `map` aligns the `Marker` to the plane of the map. `viewport` aligns the `Marker` to the plane of the viewport. `auto` automatically matches the value of `rotationAlignment`. + * @param {string} [options.rotationAlignment='auto'] `map` aligns the `Marker`'s rotation relative to the map, maintaining a bearing as the map rotates. `viewport` aligns the `Marker`'s rotation relative to the viewport, agnostic to map rotations. `auto` is equivalent to `viewport`. + * @example + * var marker = new mapboxgl.Marker() + * .setLngLat([30.5, 50.5]) + * .addTo(map); + * @example + * // Set options + * var marker = new mapboxgl.Marker({ + * color: "#FFFFFF", + * draggable: true + * }).setLngLat([30.5, 50.5]) + * .addTo(map); + * @see [Add custom icons with Markers](https://www.mapbox.com/mapbox-gl-js/example/custom-marker-icons/) + * @see [Create a draggable Marker](https://www.mapbox.com/mapbox-gl-js/example/drag-a-marker/) + */ +export default class Marker extends Evented { + _map: Map; + _anchor: Anchor; + _offset: Point; + _element: HTMLElement; + _popup: ?Popup; + _lngLat: LngLat; + _pos: ?Point; + _color: ?string; + _scale: number; + _defaultMarker: boolean; + _draggable: boolean; + _clickTolerance: number; + _isDragging: boolean; + _state: 'inactive' | 'pending' | 'active'; // used for handling drag events + _positionDelta: ?Point; + _pointerdownPos: ?Point; + _rotation: number; + _pitchAlignment: string; + _rotationAlignment: string; + _originalTabIndex: ?string; // original tabindex of _element + + constructor(options?: Options, legacyOptions?: Options) { + super(); + // For backward compatibility -- the constructor used to accept the element as a + // required first argument, before it was made optional. + if (options instanceof window.HTMLElement || legacyOptions) { + options = extend({element: options}, legacyOptions); + } + + bindAll([ + '_update', + '_onMove', + '_onUp', + '_addDragHandler', + '_onMapClick', + '_onKeyPress' + ], this); + + this._anchor = options && options.anchor || 'center'; + this._color = options && options.color || '#3FB1CE'; + this._scale = options && options.scale || 1; + this._draggable = options && options.draggable || false; + this._clickTolerance = options && options.clickTolerance || 0; + this._isDragging = false; + this._state = 'inactive'; + this._rotation = options && options.rotation || 0; + this._rotationAlignment = options && options.rotationAlignment || 'auto'; + this._pitchAlignment = options && options.pitchAlignment && options.pitchAlignment !== 'auto' ? options.pitchAlignment : this._rotationAlignment; + + if (!options || !options.element) { + this._defaultMarker = true; + this._element = DOM.create('div'); + this._element.setAttribute('aria-label', 'Map marker'); + + // create default map marker SVG + const svg = DOM.createNS('http://www.w3.org/2000/svg', 'svg'); + const defaultHeight = 41; + const defaultWidth = 27; + svg.setAttributeNS(null, 'display', 'block'); + svg.setAttributeNS(null, 'height', `${defaultHeight}px`); + svg.setAttributeNS(null, 'width', `${defaultWidth}px`); + svg.setAttributeNS(null, 'viewBox', `0 0 ${defaultWidth} ${defaultHeight}`); + + const markerLarge = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + markerLarge.setAttributeNS(null, 'stroke', 'none'); + markerLarge.setAttributeNS(null, 'stroke-width', '1'); + markerLarge.setAttributeNS(null, 'fill', 'none'); + markerLarge.setAttributeNS(null, 'fill-rule', 'evenodd'); + + const page1 = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + page1.setAttributeNS(null, 'fill-rule', 'nonzero'); + + const shadow = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + shadow.setAttributeNS(null, 'transform', 'translate(3.0, 29.0)'); + shadow.setAttributeNS(null, 'fill', '#000000'); + + const ellipses = [ + {'rx': '10.5', 'ry': '5.25002273'}, + {'rx': '10.5', 'ry': '5.25002273'}, + {'rx': '9.5', 'ry': '4.77275007'}, + {'rx': '8.5', 'ry': '4.29549936'}, + {'rx': '7.5', 'ry': '3.81822308'}, + {'rx': '6.5', 'ry': '3.34094679'}, + {'rx': '5.5', 'ry': '2.86367051'}, + {'rx': '4.5', 'ry': '2.38636864'} + ]; + + for (const data of ellipses) { + const ellipse = DOM.createNS('http://www.w3.org/2000/svg', 'ellipse'); + ellipse.setAttributeNS(null, 'opacity', '0.04'); + ellipse.setAttributeNS(null, 'cx', '10.5'); + ellipse.setAttributeNS(null, 'cy', '5.80029008'); + ellipse.setAttributeNS(null, 'rx', data['rx']); + ellipse.setAttributeNS(null, 'ry', data['ry']); + shadow.appendChild(ellipse); + } + + const background = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + background.setAttributeNS(null, 'fill', this._color); + + const bgPath = DOM.createNS('http://www.w3.org/2000/svg', 'path'); + bgPath.setAttributeNS(null, 'd', 'M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z'); + + background.appendChild(bgPath); + + const border = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + border.setAttributeNS(null, 'opacity', '0.25'); + border.setAttributeNS(null, 'fill', '#000000'); + + const borderPath = DOM.createNS('http://www.w3.org/2000/svg', 'path'); + borderPath.setAttributeNS(null, 'd', 'M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z'); + + border.appendChild(borderPath); + + const maki = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + maki.setAttributeNS(null, 'transform', 'translate(6.0, 7.0)'); + maki.setAttributeNS(null, 'fill', '#FFFFFF'); + + const circleContainer = DOM.createNS('http://www.w3.org/2000/svg', 'g'); + circleContainer.setAttributeNS(null, 'transform', 'translate(8.0, 8.0)'); + + const circle1 = DOM.createNS('http://www.w3.org/2000/svg', 'circle'); + circle1.setAttributeNS(null, 'fill', '#000000'); + circle1.setAttributeNS(null, 'opacity', '0.25'); + circle1.setAttributeNS(null, 'cx', '5.5'); + circle1.setAttributeNS(null, 'cy', '5.5'); + circle1.setAttributeNS(null, 'r', '5.4999962'); + + const circle2 = DOM.createNS('http://www.w3.org/2000/svg', 'circle'); + circle2.setAttributeNS(null, 'fill', '#FFFFFF'); + circle2.setAttributeNS(null, 'cx', '5.5'); + circle2.setAttributeNS(null, 'cy', '5.5'); + circle2.setAttributeNS(null, 'r', '5.4999962'); + + circleContainer.appendChild(circle1); + circleContainer.appendChild(circle2); + + page1.appendChild(shadow); + page1.appendChild(background); + page1.appendChild(border); + page1.appendChild(maki); + page1.appendChild(circleContainer); + + svg.appendChild(page1); + + svg.setAttributeNS(null, 'height', `${defaultHeight * this._scale}px`); + svg.setAttributeNS(null, 'width', `${defaultWidth * this._scale}px`); + + this._element.appendChild(svg); + + // if no element and no offset option given apply an offset for the default marker + // the -14 as the y value of the default marker offset was determined as follows + // + // the marker tip is at the center of the shadow ellipse from the default svg + // the y value of the center of the shadow ellipse relative to the svg top left is "shadow transform translate-y (29.0) + ellipse cy (5.80029008)" + // offset to the svg center "height (41 / 2)" gives (29.0 + 5.80029008) - (41 / 2) and rounded for an integer pixel offset gives 14 + // negative is used to move the marker up from the center so the tip is at the Marker lngLat + this._offset = Point.convert(options && options.offset || [0, -14]); + } else { + this._element = options.element; + this._offset = Point.convert(options && options.offset || [0, 0]); + } + + this._element.classList.add('mapboxgl-marker'); + this._element.addEventListener('dragstart', (e: DragEvent) => { + e.preventDefault(); + }); + this._element.addEventListener('mousedown', (e: MouseEvent) => { + // prevent focusing on click + e.preventDefault(); + }); + applyAnchorClass(this._element, this._anchor, 'marker'); + + this._popup = null; + } + + /** + * Attaches the `Marker` to a `Map` object. + * @param {Map} map The Mapbox GL JS map to add the marker to. + * @returns {Marker} `this` + * @example + * var marker = new mapboxgl.Marker() + * .setLngLat([30.5, 50.5]) + * .addTo(map); // add the marker to the map + */ + addTo(map: Map) { + this.remove(); + this._map = map; + map.getCanvasContainer().appendChild(this._element); + map.on('move', this._update); + map.on('moveend', this._update); + this.setDraggable(this._draggable); + this._update(); + + // If we attached the `click` listener to the marker element, the popup + // would close once the event propogated to `map` due to the + // `Popup#_onClickClose` listener. + this._map.on('click', this._onMapClick); + + return this; + } + + /** + * Removes the marker from a map + * @example + * var marker = new mapboxgl.Marker().addTo(map); + * marker.remove(); + * @returns {Marker} `this` + */ + remove() { + if (this._map) { + this._map.off('click', this._onMapClick); + this._map.off('move', this._update); + this._map.off('moveend', this._update); + this._map.off('mousedown', this._addDragHandler); + this._map.off('touchstart', this._addDragHandler); + this._map.off('mouseup', this._onUp); + this._map.off('touchend', this._onUp); + this._map.off('mousemove', this._onMove); + this._map.off('touchmove', this._onMove); + delete this._map; + } + DOM.remove(this._element); + if (this._popup) this._popup.remove(); + return this; + } + + /** + * Get the marker's geographical location. + * + * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously + * set by `setLngLat` because `Marker` wraps the anchor longitude across copies of the world to keep + * the marker on screen. + * + * @returns {LngLat} A {@link LngLat} describing the marker's location. + * @example + * // Store the marker's longitude and latitude coordinates in a variable + * var lngLat = marker.getLngLat(); + * // Print the marker's longitude and latitude values in the console + * console.log('Longitude: ' + lngLat.lng + ', Latitude: ' + lngLat.lat ) + * @see [Create a draggable Marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-marker/) + */ + getLngLat() { + return this._lngLat; + } + + /** + * Set the marker's geographical position and move it. + * @param {LngLat} lnglat A {@link LngLat} describing where the marker should be located. + * @returns {Marker} `this` + * @example + * // Create a new marker, set the longitude and latitude, and add it to the map + * new mapboxgl.Marker() + * .setLngLat([-65.017, -16.457]) + * .addTo(map); + * @see [Add custom icons with Markers](https://docs.mapbox.com/mapbox-gl-js/example/custom-marker-icons/) + * @see [Create a draggable Marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-marker/) + * @see [Add a marker using a place name](https://docs.mapbox.com/mapbox-gl-js/example/marker-from-geocode/) + */ + setLngLat(lnglat: LngLatLike) { + this._lngLat = LngLat.convert(lnglat); + this._pos = null; + if (this._popup) this._popup.setLngLat(this._lngLat); + this._update(); + return this; + } + + /** + * Returns the `Marker`'s HTML element. + * @returns {HTMLElement} element + */ + getElement() { + return this._element; + } + + /** + * Binds a {@link Popup} to the {@link Marker}. + * @param popup An instance of the {@link Popup} class. If undefined or null, any popup + * set on this {@link Marker} instance is unset. + * @returns {Marker} `this` + * @example + * var marker = new mapboxgl.Marker() + * .setLngLat([0, 0]) + * .setPopup(new mapboxgl.Popup().setHTML("

Hello World!

")) // add popup + * .addTo(map); + * @see [Attach a popup to a marker instance](https://docs.mapbox.com/mapbox-gl-js/example/set-popup/) + */ + setPopup(popup: ?Popup) { + if (this._popup) { + this._popup.remove(); + this._popup = null; + this._element.removeEventListener('keypress', this._onKeyPress); + + if (!this._originalTabIndex) { + this._element.removeAttribute('tabindex'); + } + } + + if (popup) { + if (!('offset' in popup.options)) { + const markerHeight = 41 - (5.8 / 2); + const markerRadius = 13.5; + const linearOffset = Math.sqrt(Math.pow(markerRadius, 2) / 2); + popup.options.offset = this._defaultMarker ? { + 'top': [0, 0], + 'top-left': [0, 0], + 'top-right': [0, 0], + 'bottom': [0, -markerHeight], + 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + 'left': [markerRadius, (markerHeight - markerRadius) * -1], + 'right': [-markerRadius, (markerHeight - markerRadius) * -1] + } : this._offset; + } + this._popup = popup; + if (this._lngLat) this._popup.setLngLat(this._lngLat); + + this._originalTabIndex = this._element.getAttribute('tabindex'); + if (!this._originalTabIndex) { + this._element.setAttribute('tabindex', '0'); + } + this._element.addEventListener('keypress', this._onKeyPress); + } + + return this; + } + + _onKeyPress(e: KeyboardEvent) { + const code = e.code; + const legacyCode = e.charCode || e.keyCode; + + if ( + (code === 'Space') || (code === 'Enter') || + (legacyCode === 32) || (legacyCode === 13) // space or enter + ) { + this.togglePopup(); + } + } + + _onMapClick(e: MapMouseEvent) { + const targetElement = e.originalEvent.target; + const element = this._element; + + if (this._popup && (targetElement === element || element.contains((targetElement: any)))) { + this.togglePopup(); + } + } + + /** + * Returns the {@link Popup} instance that is bound to the {@link Marker}. + * @returns {Popup} popup + * @example + * var marker = new mapboxgl.Marker() + * .setLngLat([0, 0]) + * .setPopup(new mapboxgl.Popup().setHTML("

Hello World!

")) + * .addTo(map); + * + * console.log(marker.getPopup()); // return the popup instance + */ + getPopup() { + return this._popup; + } + + /** + * Opens or closes the {@link Popup} instance that is bound to the {@link Marker}, depending on the current state of the {@link Popup}. + * @returns {Marker} `this` + * @example + * var marker = new mapboxgl.Marker() + * .setLngLat([0, 0]) + * .setPopup(new mapboxgl.Popup().setHTML("

Hello World!

")) + * .addTo(map); + * + * marker.togglePopup(); // toggle popup open or closed + */ + togglePopup() { + const popup = this._popup; + + if (!popup) return this; + else if (popup.isOpen()) popup.remove(); + else popup.addTo(this._map); + return this; + } + + _update(e?: {type: 'move' | 'moveend'}) { + if (!this._map) return; + + if (this._map.transform.renderWorldCopies) { + this._lngLat = smartWrap(this._lngLat, this._pos, this._map.transform); + } + + this._pos = this._map.project(this._lngLat)._add(this._offset); + + let rotation = ""; + if (this._rotationAlignment === "viewport" || this._rotationAlignment === "auto") { + rotation = `rotateZ(${this._rotation}deg)`; + } else if (this._rotationAlignment === "map") { + rotation = `rotateZ(${this._rotation - this._map.getBearing()}deg)`; + } + + let pitch = ""; + if (this._pitchAlignment === "viewport" || this._pitchAlignment === "auto") { + pitch = "rotateX(0deg)"; + } else if (this._pitchAlignment === "map") { + pitch = `rotateX(${this._map.getPitch()}deg)`; + } + + // because rounding the coordinates at every `move` event causes stuttered zooming + // we only round them when _update is called with `moveend` or when its called with + // no arguments (when the Marker is initialized or Marker#setLngLat is invoked). + if (!e || e.type === "moveend") { + this._pos = this._pos.round(); + } + + DOM.setTransform(this._element, `${anchorTranslate[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${pitch} ${rotation}`); + } + + /** + * Get the marker's offset. + * @returns {Point} The marker's screen coordinates in pixels. + */ + getOffset() { + return this._offset; + } + + /** + * Sets the offset of the marker + * @param {PointLike} offset The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up. + * @returns {Marker} `this` + */ + setOffset(offset: PointLike) { + this._offset = Point.convert(offset); + this._update(); + return this; + } + + _onMove(e: MapMouseEvent | MapTouchEvent) { + if (!this._isDragging) { + const clickTolerance = this._clickTolerance || this._map._clickTolerance; + this._isDragging = e.point.dist(this._pointerdownPos) >= clickTolerance; + } + if (!this._isDragging) return; + + this._pos = e.point.sub(this._positionDelta); + this._lngLat = this._map.unproject(this._pos); + this.setLngLat(this._lngLat); + // suppress click event so that popups don't toggle on drag + this._element.style.pointerEvents = 'none'; + + // make sure dragstart only fires on the first move event after mousedown. + // this can't be on mousedown because that event doesn't necessarily + // imply that a drag is about to happen. + if (this._state === 'pending') { + this._state = 'active'; + + /** + * Fired when dragging starts + * + * @event dragstart + * @memberof Marker + * @instance + * @type {Object} + * @property {Marker} marker object that is being dragged + */ + this.fire(new Event('dragstart')); + } + + /** + * Fired while dragging + * + * @event drag + * @memberof Marker + * @instance + * @type {Object} + * @property {Marker} marker object that is being dragged + */ + this.fire(new Event('drag')); + } + + _onUp() { + // revert to normal pointer event handling + this._element.style.pointerEvents = 'auto'; + this._positionDelta = null; + this._pointerdownPos = null; + this._isDragging = false; + this._map.off('mousemove', this._onMove); + this._map.off('touchmove', this._onMove); + + // only fire dragend if it was preceded by at least one drag event + if (this._state === 'active') { + /** + * Fired when the marker is finished being dragged + * + * @event dragend + * @memberof Marker + * @instance + * @type {Object} + * @property {Marker} marker object that was dragged + */ + this.fire(new Event('dragend')); + } + + this._state = 'inactive'; + } + + _addDragHandler(e: MapMouseEvent | MapTouchEvent) { + if (this._element.contains((e.originalEvent.target: any))) { + e.preventDefault(); + + // We need to calculate the pixel distance between the click point + // and the marker position, with the offset accounted for. Then we + // can subtract this distance from the mousemove event's position + // to calculate the new marker position. + // If we don't do this, the marker 'jumps' to the click position + // creating a jarring UX effect. + this._positionDelta = e.point.sub(this._pos).add(this._offset); + + this._pointerdownPos = e.point; + + this._state = 'pending'; + this._map.on('mousemove', this._onMove); + this._map.on('touchmove', this._onMove); + this._map.once('mouseup', this._onUp); + this._map.once('touchend', this._onUp); + } + } + + /** + * Sets the `draggable` property and functionality of the marker + * @param {boolean} [shouldBeDraggable=false] Turns drag functionality on/off + * @returns {Marker} `this` + */ + setDraggable(shouldBeDraggable: boolean) { + this._draggable = !!shouldBeDraggable; // convert possible undefined value to false + + // handle case where map may not exist yet + // e.g. when setDraggable is called before addTo + if (this._map) { + if (shouldBeDraggable) { + this._map.on('mousedown', this._addDragHandler); + this._map.on('touchstart', this._addDragHandler); + } else { + this._map.off('mousedown', this._addDragHandler); + this._map.off('touchstart', this._addDragHandler); + } + } + + return this; + } + + /** + * Returns true if the marker can be dragged + * @returns {boolean} True if the marker is draggable. + */ + isDraggable() { + return this._draggable; + } + + /** + * Sets the `rotation` property of the marker. + * @param {number} [rotation=0] The rotation angle of the marker (clockwise, in degrees), relative to its respective {@link Marker#setRotationAlignment} setting. + * @returns {Marker} `this` + */ + setRotation(rotation: number) { + this._rotation = rotation || 0; + this._update(); + return this; + } + + /** + * Returns the current rotation angle of the marker (in degrees). + * @returns {number} The current rotation angle of the marker. + */ + getRotation() { + return this._rotation; + } + + /** + * Sets the `rotationAlignment` property of the marker. + * @param {string} [alignment='auto'] Sets the `rotationAlignment` property of the marker. + * @returns {Marker} `this` + */ + setRotationAlignment(alignment: string) { + this._rotationAlignment = alignment || 'auto'; + this._update(); + return this; + } + + /** + * Returns the current `rotationAlignment` property of the marker. + * @returns {string} The current rotational alignment of the marker. + */ + getRotationAlignment() { + return this._rotationAlignment; + } + + /** + * Sets the `pitchAlignment` property of the marker. + * @param {string} [alignment] Sets the `pitchAlignment` property of the marker. If alignment is 'auto', it will automatically match `rotationAlignment`. + * @returns {Marker} `this` + */ + setPitchAlignment(alignment: string) { + this._pitchAlignment = alignment && alignment !== 'auto' ? alignment : this._rotationAlignment; + this._update(); + return this; + } + + /** + * Returns the current `pitchAlignment` property of the marker. + * @returns {string} The current pitch alignment of the marker in degrees. + */ + getPitchAlignment() { + return this._pitchAlignment; + } +} diff --git a/node_modules/mapbox-gl/src/ui/popup.js b/node_modules/mapbox-gl/src/ui/popup.js new file mode 100644 index 0000000000000000000000000000000000000000..8636862dc2feee85c999212b5a8ea9116106b04d --- /dev/null +++ b/node_modules/mapbox-gl/src/ui/popup.js @@ -0,0 +1,640 @@ +// @flow + +import {extend, bindAll} from '../util/util'; +import {Event, Evented} from '../util/evented'; +import {MapMouseEvent} from '../ui/events'; +import DOM from '../util/dom'; +import LngLat from '../geo/lng_lat'; +import Point from '@mapbox/point-geometry'; +import window from '../util/window'; +import smartWrap from '../util/smart_wrap'; +import {type Anchor, anchorTranslate, applyAnchorClass} from './anchor'; + +import type Map from './map'; +import type {LngLatLike} from '../geo/lng_lat'; +import type {PointLike} from '@mapbox/point-geometry'; + +const defaultOptions = { + closeButton: true, + closeOnClick: true, + focusAfterOpen: true, + className: '', + maxWidth: "240px" +}; + +export type Offset = number | PointLike | {[_: Anchor]: PointLike}; + +export type PopupOptions = { + closeButton?: boolean, + closeOnClick?: boolean, + closeOnMove?: boolean, + focusAfterOpen?: boolean, + anchor?: Anchor, + offset?: Offset, + className?: string, + maxWidth?: string +}; + +const focusQuerySelector = [ + "a[href]", + "[tabindex]:not([tabindex='-1'])", + "[contenteditable]:not([contenteditable='false'])", + "button:not([disabled])", + "input:not([disabled])", + "select:not([disabled])", + "textarea:not([disabled])", +].join(", "); + +/** + * A popup component. + * + * @param {Object} [options] + * @param {boolean} [options.closeButton=true] If `true`, a close button will appear in the + * top right corner of the popup. + * @param {boolean} [options.closeOnClick=true] If `true`, the popup will closed when the + * map is clicked. + * @param {boolean} [options.closeOnMove=false] If `true`, the popup will closed when the + * map moves. + * @param {boolean} [options.focusAfterOpen=true] If `true`, the popup will try to focus the + * first focusable element inside the popup. + * @param {string} [options.anchor] - A string indicating the part of the Popup that should + * be positioned closest to the coordinate set via {@link Popup#setLngLat}. + * Options are `'center'`, `'top'`, `'bottom'`, `'left'`, `'right'`, `'top-left'`, + * `'top-right'`, `'bottom-left'`, and `'bottom-right'`. If unset the anchor will be + * dynamically set to ensure the popup falls within the map container with a preference + * for `'bottom'`. + * @param {number|PointLike|Object} [options.offset] - + * A pixel offset applied to the popup's location specified as: + * - a single number specifying a distance from the popup's location + * - a {@link PointLike} specifying a constant offset + * - an object of {@link Point}s specifing an offset for each anchor position + * Negative offsets indicate left and up. + * @param {string} [options.className] Space-separated CSS class names to add to popup container + * @param {string} [options.maxWidth='240px'] - + * A string that sets the CSS property of the popup's maximum width, eg `'300px'`. + * To ensure the popup resizes to fit its content, set this property to `'none'`. + * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width + * @example + * var markerHeight = 50, markerRadius = 10, linearOffset = 25; + * var popupOffsets = { + * 'top': [0, 0], + * 'top-left': [0,0], + * 'top-right': [0,0], + * 'bottom': [0, -markerHeight], + * 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + * 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1], + * 'left': [markerRadius, (markerHeight - markerRadius) * -1], + * 'right': [-markerRadius, (markerHeight - markerRadius) * -1] + * }; + * var popup = new mapboxgl.Popup({offset: popupOffsets, className: 'my-class'}) + * .setLngLat(e.lngLat) + * .setHTML("

Hello World!

") + * .setMaxWidth("300px") + * .addTo(map); + * @see [Display a popup](https://www.mapbox.com/mapbox-gl-js/example/popup/) + * @see [Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/) + * @see [Display a popup on click](https://www.mapbox.com/mapbox-gl-js/example/popup-on-click/) + * @see [Attach a popup to a marker instance](https://www.mapbox.com/mapbox-gl-js/example/set-popup/) + */ +export default class Popup extends Evented { + _map: Map; + options: PopupOptions; + _content: HTMLElement; + _container: HTMLElement; + _closeButton: HTMLElement; + _tip: HTMLElement; + _lngLat: LngLat; + _trackPointer: boolean; + _pos: ?Point; + + constructor(options: PopupOptions) { + super(); + this.options = extend(Object.create(defaultOptions), options); + bindAll(['_update', '_onClose', 'remove', '_onMouseMove', '_onMouseUp', '_onDrag'], this); + } + + /** + * Adds the popup to a map. + * + * @param {Map} map The Mapbox GL JS map to add the popup to. + * @returns {Popup} `this` + * @example + * new mapboxgl.Popup() + * .setLngLat([0, 0]) + * .setHTML("

Null Island

") + * .addTo(map); + * @see [Display a popup](https://docs.mapbox.com/mapbox-gl-js/example/popup/) + * @see [Display a popup on hover](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-hover/) + * @see [Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/) + * @see [Show polygon information on click](https://docs.mapbox.com/mapbox-gl-js/example/polygon-popup-on-click/) + */ + addTo(map: Map) { + if (this._map) this.remove(); + + this._map = map; + if (this.options.closeOnClick) { + this._map.on('click', this._onClose); + } + + if (this.options.closeOnMove) { + this._map.on('move', this._onClose); + } + + this._map.on('remove', this.remove); + this._update(); + this._focusFirstElement(); + + if (this._trackPointer) { + this._map.on('mousemove', this._onMouseMove); + this._map.on('mouseup', this._onMouseUp); + if (this._container) { + this._container.classList.add('mapboxgl-popup-track-pointer'); + } + this._map._canvasContainer.classList.add('mapboxgl-track-pointer'); + } else { + this._map.on('move', this._update); + } + + /** + * Fired when the popup is opened manually or programatically. + * + * @event open + * @memberof Popup + * @instance + * @type {Object} + * @property {Popup} popup object that was opened + * + * @example + * // Create a popup + * var popup = new mapboxgl.Popup(); + * // Set an event listener that will fire + * // any time the popup is opened + * popup.on('open', function(){ + * console.log('popup was opened'); + * }); + * + */ + this.fire(new Event('open')); + + return this; + } + + /** + * @returns {boolean} `true` if the popup is open, `false` if it is closed. + */ + isOpen() { + return !!this._map; + } + + /** + * Removes the popup from the map it has been added to. + * + * @example + * var popup = new mapboxgl.Popup().addTo(map); + * popup.remove(); + * @returns {Popup} `this` + */ + remove() { + if (this._content) { + DOM.remove(this._content); + } + + if (this._container) { + DOM.remove(this._container); + delete this._container; + } + + if (this._map) { + this._map.off('move', this._update); + this._map.off('move', this._onClose); + this._map.off('click', this._onClose); + this._map.off('remove', this.remove); + this._map.off('mousemove', this._onMouseMove); + this._map.off('mouseup', this._onMouseUp); + this._map.off('drag', this._onDrag); + delete this._map; + } + + /** + * Fired when the popup is closed manually or programatically. + * + * @event close + * @memberof Popup + * @instance + * @type {Object} + * @property {Popup} popup object that was closed + * + * @example + * // Create a popup + * var popup = new mapboxgl.Popup(); + * // Set an event listener that will fire + * // any time the popup is closed + * popup.on('close', function(){ + * console.log('popup was closed'); + * }); + * + */ + this.fire(new Event('close')); + + return this; + } + + /** + * Returns the geographical location of the popup's anchor. + * + * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously + * set by `setLngLat` because `Popup` wraps the anchor longitude across copies of the world to keep + * the popup on screen. + * + * @returns {LngLat} The geographical location of the popup's anchor. + */ + getLngLat() { + return this._lngLat; + } + + /** + * Sets the geographical location of the popup's anchor, and moves the popup to it. Replaces trackPointer() behavior. + * + * @param lnglat The geographical location to set as the popup's anchor. + * @returns {Popup} `this` + */ + setLngLat(lnglat: LngLatLike) { + this._lngLat = LngLat.convert(lnglat); + this._pos = null; + + this._trackPointer = false; + + this._update(); + + if (this._map) { + this._map.on('move', this._update); + this._map.off('mousemove', this._onMouseMove); + if (this._container) { + this._container.classList.remove('mapboxgl-popup-track-pointer'); + } + this._map._canvasContainer.classList.remove('mapboxgl-track-pointer'); + } + + return this; + } + + /** + * Tracks the popup anchor to the cursor position on screens with a pointer device (it will be hidden on touchscreens). Replaces the `setLngLat` behavior. + * For most use cases, set `closeOnClick` and `closeButton` to `false`. + * @example + * var popup = new mapboxgl.Popup({ closeOnClick: false, closeButton: false }) + * .setHTML("

Hello World!

") + * .trackPointer() + * .addTo(map); + * @returns {Popup} `this` + */ + trackPointer() { + this._trackPointer = true; + this._pos = null; + this._update(); + if (this._map) { + this._map.off('move', this._update); + this._map.on('mousemove', this._onMouseMove); + this._map.on('drag', this._onDrag); + if (this._container) { + this._container.classList.add('mapboxgl-popup-track-pointer'); + } + this._map._canvasContainer.classList.add('mapboxgl-track-pointer'); + } + + return this; + + } + + /** + * Returns the `Popup`'s HTML element. + * @example + * // Change the `Popup` element's font size + * var popup = new mapboxgl.Popup() + * .setLngLat([-96, 37.8]) + * .setHTML("

Hello World!

") + * .addTo(map); + * var popupElem = popup.getElement(); + * popupElem.style.fontSize = "25px"; + * @returns {HTMLElement} element + */ + getElement() { + return this._container; + } + + /** + * Sets the popup's content to a string of text. + * + * This function creates a [Text](https://developer.mozilla.org/en-US/docs/Web/API/Text) node in the DOM, + * so it cannot insert raw HTML. Use this method for security against XSS + * if the popup content is user-provided. + * + * @param text Textual content for the popup. + * @returns {Popup} `this` + * @example + * var popup = new mapboxgl.Popup() + * .setLngLat(e.lngLat) + * .setText('Hello, world!') + * .addTo(map); + */ + setText(text: string) { + return this.setDOMContent(window.document.createTextNode(text)); + } + + /** + * Sets the popup's content to the HTML provided as a string. + * + * This method does not perform HTML filtering or sanitization, and must be + * used only with trusted content. Consider {@link Popup#setText} if + * the content is an untrusted text string. + * + * @param html A string representing HTML content for the popup. + * @returns {Popup} `this` + * @example + * var popup = new mapboxgl.Popup() + * .setLngLat(e.lngLat) + * .setHTML("

Hello World!

") + * .addTo(map); + * @see [Display a popup](https://docs.mapbox.com/mapbox-gl-js/example/popup/) + * @see [Display a popup on hover](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-hover/) + * @see [Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/) + * @see [Attach a popup to a marker instance](https://docs.mapbox.com/mapbox-gl-js/example/set-popup/) + */ + setHTML(html: string) { + const frag = window.document.createDocumentFragment(); + const temp = window.document.createElement('body'); + let child; + temp.innerHTML = html; + while (true) { + child = temp.firstChild; + if (!child) break; + frag.appendChild(child); + } + + return this.setDOMContent(frag); + } + + /** + * Returns the popup's maximum width. + * + * @returns {string} The maximum width of the popup. + */ + getMaxWidth() { + return this._container && this._container.style.maxWidth; + } + + /** + * Sets the popup's maximum width. This is setting the CSS property `max-width`. + * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width + * + * @param maxWidth A string representing the value for the maximum width. + * @returns {Popup} `this` + */ + setMaxWidth(maxWidth: string) { + this.options.maxWidth = maxWidth; + this._update(); + return this; + } + + /** + * Sets the popup's content to the element provided as a DOM node. + * + * @param htmlNode A DOM node to be used as content for the popup. + * @returns {Popup} `this` + * @example + * // create an element with the popup content + * var div = window.document.createElement('div'); + * div.innerHTML = 'Hello, world!'; + * var popup = new mapboxgl.Popup() + * .setLngLat(e.lngLat) + * .setDOMContent(div) + * .addTo(map); + */ + setDOMContent(htmlNode: Node) { + if (this._content) { + // Clear out children first. + while (this._content.hasChildNodes()) { + if (this._content.firstChild) { + this._content.removeChild(this._content.firstChild); + } + } + } else { + this._content = DOM.create('div', 'mapboxgl-popup-content', this._container); + } + + // The close button should be the last tabbable element inside the popup for a good keyboard UX. + this._content.appendChild(htmlNode); + this._createCloseButton(); + this._update(); + this._focusFirstElement(); + return this; + } + + /** + * Adds a CSS class to the popup container element. + * + * @param {string} className Non-empty string with CSS class name to add to popup container + * + * @example + * let popup = new mapboxgl.Popup() + * popup.addClassName('some-class') + */ + addClassName(className: string) { + if (this._container) { + this._container.classList.add(className); + } + } + + /** + * Removes a CSS class from the popup container element. + * + * @param {string} className Non-empty string with CSS class name to remove from popup container + * + * @example + * let popup = new mapboxgl.Popup() + * popup.removeClassName('some-class') + */ + removeClassName(className: string) { + if (this._container) { + this._container.classList.remove(className); + } + } + + /** + * Sets the popup's offset. + * + * @param offset Sets the popup's offset. + * @returns {Popup} `this` + */ + setOffset (offset?: Offset) { + this.options.offset = offset; + this._update(); + return this; + } + + /** + * Add or remove the given CSS class on the popup container, depending on whether the container currently has that class. + * + * @param {string} className Non-empty string with CSS class name to add/remove + * + * @returns {boolean} if the class was removed return false, if class was added, then return true + * + * @example + * let popup = new mapboxgl.Popup() + * popup.toggleClassName('toggleClass') + */ + toggleClassName(className: string) { + if (this._container) { + return this._container.classList.toggle(className); + } + } + + _createCloseButton() { + if (this.options.closeButton) { + this._closeButton = DOM.create('button', 'mapboxgl-popup-close-button', this._content); + this._closeButton.type = 'button'; + this._closeButton.setAttribute('aria-label', 'Close popup'); + this._closeButton.innerHTML = '×'; + this._closeButton.addEventListener('click', this._onClose); + } + } + + _onMouseUp(event: MapMouseEvent) { + this._update(event.point); + } + + _onMouseMove(event: MapMouseEvent) { + this._update(event.point); + } + + _onDrag(event: MapMouseEvent) { + this._update(event.point); + } + + _update(cursor: ?PointLike) { + const hasPosition = this._lngLat || this._trackPointer; + + if (!this._map || !hasPosition || !this._content) { return; } + + if (!this._container) { + this._container = DOM.create('div', 'mapboxgl-popup', this._map.getContainer()); + this._tip = DOM.create('div', 'mapboxgl-popup-tip', this._container); + this._container.appendChild(this._content); + if (this.options.className) { + this.options.className.split(' ').forEach(name => + this._container.classList.add(name)); + } + + if (this._trackPointer) { + this._container.classList.add('mapboxgl-popup-track-pointer'); + } + } + + if (this.options.maxWidth && this._container.style.maxWidth !== this.options.maxWidth) { + this._container.style.maxWidth = this.options.maxWidth; + } + + if (this._map.transform.renderWorldCopies && !this._trackPointer) { + this._lngLat = smartWrap(this._lngLat, this._pos, this._map.transform); + } + + if (this._trackPointer && !cursor) return; + + const pos = this._pos = this._trackPointer && cursor ? cursor : this._map.project(this._lngLat); + + let anchor: ?Anchor = this.options.anchor; + const offset = normalizeOffset(this.options.offset); + + if (!anchor) { + const width = this._container.offsetWidth; + const height = this._container.offsetHeight; + let anchorComponents; + + if (pos.y + offset.bottom.y < height) { + anchorComponents = ['top']; + } else if (pos.y > this._map.transform.height - height) { + anchorComponents = ['bottom']; + } else { + anchorComponents = []; + } + + if (pos.x < width / 2) { + anchorComponents.push('left'); + } else if (pos.x > this._map.transform.width - width / 2) { + anchorComponents.push('right'); + } + + if (anchorComponents.length === 0) { + anchor = 'bottom'; + } else { + anchor = (anchorComponents.join('-'): any); + } + } + + const offsetedPos = pos.add(offset[anchor]).round(); + DOM.setTransform(this._container, `${anchorTranslate[anchor]} translate(${offsetedPos.x}px,${offsetedPos.y}px)`); + applyAnchorClass(this._container, anchor, 'popup'); + } + + _focusFirstElement() { + if (!this.options.focusAfterOpen || !this._container) return; + + const firstFocusable = this._container.querySelector(focusQuerySelector); + + if (firstFocusable) firstFocusable.focus(); + } + + _onClose() { + this.remove(); + } +} + +function normalizeOffset(offset: ?Offset) { + if (!offset) { + return normalizeOffset(new Point(0, 0)); + + } else if (typeof offset === 'number') { + // input specifies a radius from which to calculate offsets at all positions + const cornerOffset = Math.round(Math.sqrt(0.5 * Math.pow(offset, 2))); + return { + 'center': new Point(0, 0), + 'top': new Point(0, offset), + 'top-left': new Point(cornerOffset, cornerOffset), + 'top-right': new Point(-cornerOffset, cornerOffset), + 'bottom': new Point(0, -offset), + 'bottom-left': new Point(cornerOffset, -cornerOffset), + 'bottom-right': new Point(-cornerOffset, -cornerOffset), + 'left': new Point(offset, 0), + 'right': new Point(-offset, 0) + }; + + } else if (offset instanceof Point || Array.isArray(offset)) { + // input specifies a single offset to be applied to all positions + const convertedOffset = Point.convert(offset); + return { + 'center': convertedOffset, + 'top': convertedOffset, + 'top-left': convertedOffset, + 'top-right': convertedOffset, + 'bottom': convertedOffset, + 'bottom-left': convertedOffset, + 'bottom-right': convertedOffset, + 'left': convertedOffset, + 'right': convertedOffset + }; + + } else { + // input specifies an offset per position + return { + 'center': Point.convert(offset['center'] || [0, 0]), + 'top': Point.convert(offset['top'] || [0, 0]), + 'top-left': Point.convert(offset['top-left'] || [0, 0]), + 'top-right': Point.convert(offset['top-right'] || [0, 0]), + 'bottom': Point.convert(offset['bottom'] || [0, 0]), + 'bottom-left': Point.convert(offset['bottom-left'] || [0, 0]), + 'bottom-right': Point.convert(offset['bottom-right'] || [0, 0]), + 'left': Point.convert(offset['left'] || [0, 0]), + 'right': Point.convert(offset['right'] || [0, 0]) + }; + } +} diff --git a/node_modules/mapbox-gl/src/util/actor.js b/node_modules/mapbox-gl/src/util/actor.js new file mode 100644 index 0000000000000000000000000000000000000000..ac441726c417ecb1fdc15c7c14db4a589f84f785 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/actor.js @@ -0,0 +1,212 @@ +// @flow + +import {bindAll, isWorker, isSafari} from './util'; +import window from './window'; +import {serialize, deserialize} from './web_worker_transfer'; +import ThrottledInvoker from './throttled_invoker'; + +import type {Transferable} from '../types/transferable'; +import type {Cancelable} from '../types/cancelable'; + +/** + * An implementation of the [Actor design pattern](http://en.wikipedia.org/wiki/Actor_model) + * that maintains the relationship between asynchronous tasks and the objects + * that spin them off - in this case, tasks like parsing parts of styles, + * owned by the styles + * + * @param {WebWorker} target + * @param {WebWorker} parent + * @param {string|number} mapId A unique identifier for the Map instance using this Actor. + * @private + */ +class Actor { + target: any; + parent: any; + mapId: ?number; + callbacks: { number: any }; + name: string; + tasks: { number: any }; + taskQueue: Array; + cancelCallbacks: { number: Cancelable }; + invoker: ThrottledInvoker; + globalScope: any; + + constructor(target: any, parent: any, mapId: ?number) { + this.target = target; + this.parent = parent; + this.mapId = mapId; + this.callbacks = {}; + this.tasks = {}; + this.taskQueue = []; + this.cancelCallbacks = {}; + bindAll(['receive', 'process'], this); + this.invoker = new ThrottledInvoker(this.process); + this.target.addEventListener('message', this.receive, false); + this.globalScope = isWorker() ? target : window; + } + + /** + * Sends a message from a main-thread map to a Worker or from a Worker back to + * a main-thread map instance. + * + * @param type The name of the target method to invoke or '[source-type].[source-name].name' for a method on a WorkerSource. + * @param targetMapId A particular mapId to which to send this message. + * @private + */ + send(type: string, data: mixed, callback: ?Function, targetMapId: ?string, mustQueue: boolean = false): ?Cancelable { + // We're using a string ID instead of numbers because they are being used as object keys + // anyway, and thus stringified implicitly. We use random IDs because an actor may receive + // message from multiple other actors which could run in different execution context. A + // linearly increasing ID could produce collisions. + const id = Math.round((Math.random() * 1e18)).toString(36).substring(0, 10); + if (callback) { + this.callbacks[id] = callback; + } + const buffers: ?Array = isSafari(this.globalScope) ? undefined : []; + this.target.postMessage({ + id, + type, + hasCallback: !!callback, + targetMapId, + mustQueue, + sourceMapId: this.mapId, + data: serialize(data, buffers) + }, buffers); + return { + cancel: () => { + if (callback) { + // Set the callback to null so that it never fires after the request is aborted. + delete this.callbacks[id]; + } + this.target.postMessage({ + id, + type: '', + targetMapId, + sourceMapId: this.mapId + }); + } + }; + } + + receive(message: Object) { + const data = message.data, + id = data.id; + + if (!id) { + return; + } + + if (data.targetMapId && this.mapId !== data.targetMapId) { + return; + } + + if (data.type === '') { + // Remove the original request from the queue. This is only possible if it + // hasn't been kicked off yet. The id will remain in the queue, but because + // there is no associated task, it will be dropped once it's time to execute it. + delete this.tasks[id]; + const cancel = this.cancelCallbacks[id]; + delete this.cancelCallbacks[id]; + if (cancel) { + cancel(); + } + } else { + if (isWorker() || data.mustQueue) { + // In workers, store the tasks that we need to process before actually processing them. This + // is necessary because we want to keep receiving messages, and in particular, + // messages. Some tasks may take a while in the worker thread, so before + // executing the next task in our queue, postMessage preempts this and + // messages can be processed. We're using a MessageChannel object to get throttle the + // process() flow to one at a time. + this.tasks[id] = data; + this.taskQueue.push(id); + this.invoker.trigger(); + } else { + // In the main thread, process messages immediately so that other work does not slip in + // between getting partial data back from workers. + this.processTask(id, data); + } + } + } + + process() { + if (!this.taskQueue.length) { + return; + } + const id = this.taskQueue.shift(); + const task = this.tasks[id]; + delete this.tasks[id]; + // Schedule another process call if we know there's more to process _before_ invoking the + // current task. This is necessary so that processing continues even if the current task + // doesn't execute successfully. + if (this.taskQueue.length) { + this.invoker.trigger(); + } + if (!task) { + // If the task ID doesn't have associated task data anymore, it was canceled. + return; + } + + this.processTask(id, task); + } + + processTask(id: number, task: any) { + if (task.type === '') { + // The done() function in the counterpart has been called, and we are now + // firing the callback in the originating actor, if there is one. + const callback = this.callbacks[id]; + delete this.callbacks[id]; + if (callback) { + // If we get a response, but don't have a callback, the request was canceled. + if (task.error) { + callback(deserialize(task.error)); + } else { + callback(null, deserialize(task.data)); + } + } + } else { + let completed = false; + const buffers: ?Array = isSafari(this.globalScope) ? undefined : []; + const done = task.hasCallback ? (err, data) => { + completed = true; + delete this.cancelCallbacks[id]; + this.target.postMessage({ + id, + type: '', + sourceMapId: this.mapId, + error: err ? serialize(err) : null, + data: serialize(data, buffers) + }, buffers); + } : (_) => { + completed = true; + }; + + let callback = null; + const params = (deserialize(task.data): any); + if (this.parent[task.type]) { + // task.type == 'loadTile', 'removeTile', etc. + callback = this.parent[task.type](task.sourceMapId, params, done); + } else if (this.parent.getWorkerSource) { + // task.type == sourcetype.method + const keys = task.type.split('.'); + const scope = (this.parent: any).getWorkerSource(task.sourceMapId, keys[0], params.source); + callback = scope[keys[1]](params, done); + } else { + // No function was found. + done(new Error(`Could not find function ${task.type}`)); + } + + if (!completed && callback && callback.cancel) { + // Allows canceling the task as long as it hasn't been completed yet. + this.cancelCallbacks[id] = callback.cancel; + } + } + } + + remove() { + this.invoker.remove(); + this.target.removeEventListener('message', this.receive, false); + } +} + +export default Actor; diff --git a/node_modules/mapbox-gl/src/util/ajax.js b/node_modules/mapbox-gl/src/util/ajax.js new file mode 100644 index 0000000000000000000000000000000000000000..e3dfeeef0e905f40488b4de0689155ab793e540d --- /dev/null +++ b/node_modules/mapbox-gl/src/util/ajax.js @@ -0,0 +1,388 @@ +// @flow + +import window from './window'; +import {extend, warnOnce, isWorker} from './util'; +import {isMapboxHTTPURL, hasCacheDefeatingSku} from './mapbox'; +import config from './config'; +import assert from 'assert'; +import {cacheGet, cachePut} from './tile_request_cache'; +import webpSupported from './webp_supported'; +import offscreenCanvasSupported from './offscreen_canvas_supported'; + +import type {Callback} from '../types/callback'; +import type {Cancelable} from '../types/cancelable'; + +/** + * The type of a resource. + * @private + * @readonly + * @enum {string} + */ +const ResourceType = { + Unknown: 'Unknown', + Style: 'Style', + Source: 'Source', + Tile: 'Tile', + Glyphs: 'Glyphs', + SpriteImage: 'SpriteImage', + SpriteJSON: 'SpriteJSON', + Image: 'Image' +}; +export {ResourceType}; + +if (typeof Object.freeze == 'function') { + Object.freeze(ResourceType); +} + +/** + * A `RequestParameters` object to be returned from Map.options.transformRequest callbacks. + * @typedef {Object} RequestParameters + * @property {string} url The URL to be requested. + * @property {Object} headers The headers to be sent with the request. + * @property {string} method Request method `'GET' | 'POST' | 'PUT'`. + * @property {string} body Request body. + * @property {string} type Response body type to be returned `'string' | 'json' | 'arrayBuffer'`. + * @property {string} credentials `'same-origin'|'include'` Use 'include' to send cookies with cross-origin requests. + * @property {boolean} collectResourceTiming If true, Resource Timing API information will be collected for these transformed requests and returned in a resourceTiming property of relevant data events. + * @example + * // use transformRequest to modify requests that begin with `http://myHost` + * transformRequest: function(url, resourceType) { + * if (resourceType === 'Source' && url.indexOf('http://myHost') > -1) { + * return { + * url: url.replace('http', 'https'), + * headers: { 'my-custom-header': true }, + * credentials: 'include' // Include cookies for cross-origin requests + * } + * } + * } + * + */ +export type RequestParameters = { + url: string, + headers?: Object, + method?: 'GET' | 'POST' | 'PUT', + body?: string, + type?: 'string' | 'json' | 'arrayBuffer', + credentials?: 'same-origin' | 'include', + collectResourceTiming?: boolean +}; + +export type ResponseCallback = (error: ?Error, data: ?T, cacheControl: ?string, expires: ?string) => void; + +class AJAXError extends Error { + status: number; + url: string; + constructor(message: string, status: number, url: string) { + if (status === 401 && isMapboxHTTPURL(url)) { + message += ': you may have provided an invalid Mapbox access token. See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes'; + } + super(message); + this.status = status; + this.url = url; + + // work around for https://github.com/Rich-Harris/buble/issues/40 + this.name = this.constructor.name; + this.message = message; + } + + toString() { + return `${this.name}: ${this.message} (${this.status}): ${this.url}`; + } +} + +// Ensure that we're sending the correct referrer from blob URL worker bundles. +// For files loaded from the local file system, `location.origin` will be set +// to the string(!) "null" (Firefox), or "file://" (Chrome, Safari, Edge, IE), +// and we will set an empty referrer. Otherwise, we're using the document's URL. +/* global self */ +export const getReferrer = isWorker() ? + () => self.worker && self.worker.referrer : + () => (window.location.protocol === 'blob:' ? window.parent : window).location.href; + +// Determines whether a URL is a file:// URL. This is obviously the case if it begins +// with file://. Relative URLs are also file:// URLs iff the original document was loaded +// via a file:// URL. +const isFileURL = url => /^file:/.test(url) || (/^file:/.test(getReferrer()) && !/^\w+:/.test(url)); + +function makeFetchRequest(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable { + const controller = new window.AbortController(); + const request = new window.Request(requestParameters.url, { + method: requestParameters.method || 'GET', + body: requestParameters.body, + credentials: requestParameters.credentials, + headers: requestParameters.headers, + referrer: getReferrer(), + signal: controller.signal + }); + let complete = false; + let aborted = false; + + const cacheIgnoringSearch = hasCacheDefeatingSku(request.url); + + if (requestParameters.type === 'json') { + request.headers.set('Accept', 'application/json'); + } + + const validateOrFetch = (err, cachedResponse, responseIsFresh) => { + if (aborted) return; + + if (err) { + // Do fetch in case of cache error. + // HTTP pages in Edge trigger a security error that can be ignored. + if (err.message !== 'SecurityError') { + warnOnce(err); + } + } + + if (cachedResponse && responseIsFresh) { + return finishRequest(cachedResponse); + } + + if (cachedResponse) { + // We can't do revalidation with 'If-None-Match' because then the + // request doesn't have simple cors headers. + } + + const requestTime = Date.now(); + + window.fetch(request).then(response => { + if (response.ok) { + const cacheableResponse = cacheIgnoringSearch ? response.clone() : null; + return finishRequest(response, cacheableResponse, requestTime); + + } else { + return callback(new AJAXError(response.statusText, response.status, requestParameters.url)); + } + }).catch(error => { + if (error.code === 20) { + // silence expected AbortError + return; + } + callback(new Error(error.message)); + }); + }; + + const finishRequest = (response, cacheableResponse, requestTime) => { + ( + requestParameters.type === 'arrayBuffer' ? response.arrayBuffer() : + requestParameters.type === 'json' ? response.json() : + response.text() + ).then(result => { + if (aborted) return; + if (cacheableResponse && requestTime) { + // The response needs to be inserted into the cache after it has completely loaded. + // Until it is fully loaded there is a chance it will be aborted. Aborting while + // reading the body can cause the cache insertion to error. We could catch this error + // in most browsers but in Firefox it seems to sometimes crash the tab. Adding + // it to the cache here avoids that error. + cachePut(request, cacheableResponse, requestTime); + } + complete = true; + callback(null, result, response.headers.get('Cache-Control'), response.headers.get('Expires')); + }).catch(err => { + if (!aborted) callback(new Error(err.message)); + }); + }; + + if (cacheIgnoringSearch) { + cacheGet(request, validateOrFetch); + } else { + validateOrFetch(null, null); + } + + return {cancel: () => { + aborted = true; + if (!complete) controller.abort(); + }}; +} + +function makeXMLHttpRequest(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable { + const xhr: XMLHttpRequest = new window.XMLHttpRequest(); + + xhr.open(requestParameters.method || 'GET', requestParameters.url, true); + if (requestParameters.type === 'arrayBuffer') { + xhr.responseType = 'arraybuffer'; + } + for (const k in requestParameters.headers) { + xhr.setRequestHeader(k, requestParameters.headers[k]); + } + if (requestParameters.type === 'json') { + xhr.responseType = 'text'; + xhr.setRequestHeader('Accept', 'application/json'); + } + xhr.withCredentials = requestParameters.credentials === 'include'; + xhr.onerror = () => { + callback(new Error(xhr.statusText)); + }; + xhr.onload = () => { + if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response !== null) { + let data: mixed = xhr.response; + if (requestParameters.type === 'json') { + // We're manually parsing JSON here to get better error messages. + try { + data = JSON.parse(xhr.response); + } catch (err) { + return callback(err); + } + } + callback(null, data, xhr.getResponseHeader('Cache-Control'), xhr.getResponseHeader('Expires')); + } else { + callback(new AJAXError(xhr.statusText, xhr.status, requestParameters.url)); + } + }; + xhr.send(requestParameters.body); + return {cancel: () => xhr.abort()}; +} + +export const makeRequest = function(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable { + // We're trying to use the Fetch API if possible. However, in some situations we can't use it: + // - IE11 doesn't support it at all. In this case, we dispatch the request to the main thread so + // that we can get an accruate referrer header. + // - Safari exposes window.AbortController, but it doesn't work actually abort any requests in + // some versions (see https://bugs.webkit.org/show_bug.cgi?id=174980#c2) + // - Requests for resources with the file:// URI scheme don't work with the Fetch API either. In + // this case we unconditionally use XHR on the current thread since referrers don't matter. + if (!isFileURL(requestParameters.url)) { + if (window.fetch && window.Request && window.AbortController && window.Request.prototype.hasOwnProperty('signal')) { + return makeFetchRequest(requestParameters, callback); + } + if (isWorker() && self.worker && self.worker.actor) { + const queueOnMainThread = true; + return self.worker.actor.send('getResource', requestParameters, callback, undefined, queueOnMainThread); + } + } + return makeXMLHttpRequest(requestParameters, callback); +}; + +export const getJSON = function(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable { + return makeRequest(extend(requestParameters, {type: 'json'}), callback); +}; + +export const getArrayBuffer = function(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable { + return makeRequest(extend(requestParameters, {type: 'arrayBuffer'}), callback); +}; + +export const postData = function(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable { + return makeRequest(extend(requestParameters, {method: 'POST'}), callback); +}; + +function sameOrigin(url) { + const a: HTMLAnchorElement = window.document.createElement('a'); + a.href = url; + return a.protocol === window.document.location.protocol && a.host === window.document.location.host; +} + +const transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII='; + +function arrayBufferToImage(data: ArrayBuffer, callback: (err: ?Error, image: ?HTMLImageElement) => void, cacheControl: ?string, expires: ?string) { + const img: HTMLImageElement = new window.Image(); + const URL = window.URL; + img.onload = () => { + callback(null, img); + URL.revokeObjectURL(img.src); + // prevent image dataURI memory leak in Safari; + // but don't free the image immediately because it might be uploaded in the next frame + // https://github.com/mapbox/mapbox-gl-js/issues/10226 + img.onload = null; + window.requestAnimationFrame(() => { img.src = transparentPngUrl; }); + }; + img.onerror = () => callback(new Error('Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.')); + const blob: Blob = new window.Blob([new Uint8Array(data)], {type: 'image/png'}); + (img: any).cacheControl = cacheControl; + (img: any).expires = expires; + img.src = data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl; +} + +function arrayBufferToImageBitmap(data: ArrayBuffer, callback: (err: ?Error, image: ?ImageBitmap) => void) { + const blob: Blob = new window.Blob([new Uint8Array(data)], {type: 'image/png'}); + window.createImageBitmap(blob).then((imgBitmap) => { + callback(null, imgBitmap); + }).catch((e) => { + callback(new Error(`Could not load image because of ${e.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)); + }); +} + +let imageQueue, numImageRequests; +export const resetImageRequestQueue = () => { + imageQueue = []; + numImageRequests = 0; +}; +resetImageRequestQueue(); + +export const getImage = function(requestParameters: RequestParameters, callback: Callback): Cancelable { + if (webpSupported.supported) { + if (!requestParameters.headers) { + requestParameters.headers = {}; + } + requestParameters.headers.accept = 'image/webp,*/*'; + } + + // limit concurrent image loads to help with raster sources performance on big screens + if (numImageRequests >= config.MAX_PARALLEL_IMAGE_REQUESTS) { + const queued = { + requestParameters, + callback, + cancelled: false, + cancel() { this.cancelled = true; } + }; + imageQueue.push(queued); + return queued; + } + numImageRequests++; + + let advanced = false; + const advanceImageRequestQueue = () => { + if (advanced) return; + advanced = true; + numImageRequests--; + assert(numImageRequests >= 0); + while (imageQueue.length && numImageRequests < config.MAX_PARALLEL_IMAGE_REQUESTS) { // eslint-disable-line + const request = imageQueue.shift(); + const {requestParameters, callback, cancelled} = request; + if (!cancelled) { + request.cancel = getImage(requestParameters, callback).cancel; + } + } + }; + + // request the image with XHR to work around caching issues + // see https://github.com/mapbox/mapbox-gl-js/issues/1470 + const request = getArrayBuffer(requestParameters, (err: ?Error, data: ?ArrayBuffer, cacheControl: ?string, expires: ?string) => { + + advanceImageRequestQueue(); + + if (err) { + callback(err); + } else if (data) { + if (offscreenCanvasSupported()) { + arrayBufferToImageBitmap(data, callback); + } else { + arrayBufferToImage(data, callback, cacheControl, expires); + } + } + }); + + return { + cancel: () => { + request.cancel(); + advanceImageRequestQueue(); + } + }; +}; + +export const getVideo = function(urls: Array, callback: Callback): Cancelable { + const video: HTMLVideoElement = window.document.createElement('video'); + video.muted = true; + video.onloadstart = function() { + callback(null, video); + }; + for (let i = 0; i < urls.length; i++) { + const s: HTMLSourceElement = window.document.createElement('source'); + if (!sameOrigin(urls[i])) { + video.crossOrigin = 'Anonymous'; + } + s.src = urls[i]; + video.appendChild(s); + } + return {cancel: () => {}}; +}; diff --git a/node_modules/mapbox-gl/src/util/browser.js b/node_modules/mapbox-gl/src/util/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..808a6fcc5c44eb44aa431312058d28fb8bac2cf1 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/browser.js @@ -0,0 +1,70 @@ +// @flow strict + +import window from './window'; +import type {Cancelable} from '../types/cancelable'; + +const now = window.performance && window.performance.now ? + window.performance.now.bind(window.performance) : + Date.now.bind(Date); + +const raf = window.requestAnimationFrame || + window.mozRequestAnimationFrame || + window.webkitRequestAnimationFrame || + window.msRequestAnimationFrame; + +const cancel = window.cancelAnimationFrame || + window.mozCancelAnimationFrame || + window.webkitCancelAnimationFrame || + window.msCancelAnimationFrame; + +let linkEl; + +let reducedMotionQuery: MediaQueryList; + +/** + * @private + */ +const exported = { + /** + * Provides a function that outputs milliseconds: either performance.now() + * or a fallback to Date.now() + */ + now, + + frame(fn: (paintStartTimestamp: number) => void): Cancelable { + const frame = raf(fn); + return {cancel: () => cancel(frame)}; + }, + + getImageData(img: CanvasImageSource, padding?: number = 0): ImageData { + const canvas = window.document.createElement('canvas'); + const context = canvas.getContext('2d'); + if (!context) { + throw new Error('failed to create canvas 2d context'); + } + canvas.width = img.width; + canvas.height = img.height; + context.drawImage(img, 0, 0, img.width, img.height); + return context.getImageData(-padding, -padding, img.width + 2 * padding, img.height + 2 * padding); + }, + + resolveURL(path: string) { + if (!linkEl) linkEl = window.document.createElement('a'); + linkEl.href = path; + return linkEl.href; + }, + + hardwareConcurrency: window.navigator && window.navigator.hardwareConcurrency || 4, + + get devicePixelRatio() { return window.devicePixelRatio; }, + get prefersReducedMotion(): boolean { + if (!window.matchMedia) return false; + //Lazily initialize media query + if (reducedMotionQuery == null) { + reducedMotionQuery = window.matchMedia('(prefers-reduced-motion: reduce)'); + } + return reducedMotionQuery.matches; + }, +}; + +export default exported; diff --git a/node_modules/mapbox-gl/src/util/browser/web_worker.js b/node_modules/mapbox-gl/src/util/browser/web_worker.js new file mode 100644 index 0000000000000000000000000000000000000000..3d1314da10c67709e05333e8abfc470ee45862fa --- /dev/null +++ b/node_modules/mapbox-gl/src/util/browser/web_worker.js @@ -0,0 +1,10 @@ +// @flow + +import window from '../window'; +import mapboxgl from '../../'; + +import type {WorkerInterface} from '../web_worker'; + +export default function (): WorkerInterface { + return (new window.Worker(mapboxgl.workerUrl): any); +} diff --git a/node_modules/mapbox-gl/src/util/browser/window.js b/node_modules/mapbox-gl/src/util/browser/window.js new file mode 100644 index 0000000000000000000000000000000000000000..d2ceea5613a7aa964d4c7ba5cdb4093428359836 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/browser/window.js @@ -0,0 +1,6 @@ +// @flow +/* eslint-env browser */ +import type {Window} from '../../types/window'; + +// shim window for the case of requiring the browser bundle in Node +export default typeof self !== 'undefined' ? (self: Window) : (({}: any): Window); diff --git a/node_modules/mapbox-gl/src/util/classify_rings.js b/node_modules/mapbox-gl/src/util/classify_rings.js new file mode 100644 index 0000000000000000000000000000000000000000..3d18b60fcab59e7c232e67815b505123e77eabcf --- /dev/null +++ b/node_modules/mapbox-gl/src/util/classify_rings.js @@ -0,0 +1,52 @@ +// @flow + +import quickselect from 'quickselect'; + +import {calculateSignedArea} from './util'; + +import type Point from '@mapbox/point-geometry'; + +// classifies an array of rings into polygons with outer rings and holes +export default function classifyRings(rings: Array>, maxRings: number) { + const len = rings.length; + + if (len <= 1) return [rings]; + + const polygons = []; + let polygon, + ccw; + + for (let i = 0; i < len; i++) { + const area = calculateSignedArea(rings[i]); + if (area === 0) continue; + + (rings[i]: any).area = Math.abs(area); + + if (ccw === undefined) ccw = area < 0; + + if (ccw === area < 0) { + if (polygon) polygons.push(polygon); + polygon = [rings[i]]; + + } else { + (polygon: any).push(rings[i]); + } + } + if (polygon) polygons.push(polygon); + + // Earcut performance degrades with the # of rings in a polygon. For this + // reason, we limit strip out all but the `maxRings` largest rings. + if (maxRings > 1) { + for (let j = 0; j < polygons.length; j++) { + if (polygons[j].length <= maxRings) continue; + quickselect(polygons[j], maxRings, 1, polygons[j].length - 1, compareAreas); + polygons[j] = polygons[j].slice(0, maxRings); + } + } + + return polygons; +} + +function compareAreas(a, b) { + return b.area - a.area; +} diff --git a/node_modules/mapbox-gl/src/util/color_ramp.js b/node_modules/mapbox-gl/src/util/color_ramp.js new file mode 100644 index 0000000000000000000000000000000000000000..24dc0758699865939ac88d23c97124c18ac9621a --- /dev/null +++ b/node_modules/mapbox-gl/src/util/color_ramp.js @@ -0,0 +1,61 @@ +// @flow + +import {RGBAImage} from './image'; +import {isPowerOfTwo} from './util'; +import assert from 'assert'; + +import type {StylePropertyExpression} from '../style-spec/expression/index'; + +export type ColorRampParams = { + expression: StylePropertyExpression; + evaluationKey: string; + resolution?: number; + image?: RGBAImage; + clips?: Array; +} + +/** + * Given an expression that should evaluate to a color ramp, + * return a RGBA image representing that ramp expression. + * + * @private + */ +export function renderColorRamp(params: ColorRampParams): RGBAImage { + const evaluationGlobals = {}; + const width = params.resolution || 256; + const height = params.clips ? params.clips.length : 1; + const image = params.image || new RGBAImage({width, height}); + + assert(isPowerOfTwo(width)); + + const renderPixel = (stride, index, progress) => { + evaluationGlobals[params.evaluationKey] = progress; + const pxColor = params.expression.evaluate((evaluationGlobals: any)); + // the colors are being unpremultiplied because Color uses + // premultiplied values, and the Texture class expects unpremultiplied ones + image.data[stride + index + 0] = Math.floor(pxColor.r * 255 / pxColor.a); + image.data[stride + index + 1] = Math.floor(pxColor.g * 255 / pxColor.a); + image.data[stride + index + 2] = Math.floor(pxColor.b * 255 / pxColor.a); + image.data[stride + index + 3] = Math.floor(pxColor.a * 255); + }; + + if (!params.clips) { + for (let i = 0, j = 0; i < width; i++, j += 4) { + const progress = i / (width - 1); + + renderPixel(0, j, progress); + } + } else { + for (let clip = 0, stride = 0; clip < height; ++clip, stride += width * 4) { + for (let i = 0, j = 0; i < width; i++, j += 4) { + // Remap progress between clips + const progress = i / (width - 1); + const {start, end} = params.clips[clip]; + const evaluationProgress = start * (1 - progress) + end * progress; + renderPixel(stride, j, evaluationProgress); + } + } + } + + return image; +} diff --git a/node_modules/mapbox-gl/src/util/config.js b/node_modules/mapbox-gl/src/util/config.js new file mode 100644 index 0000000000000000000000000000000000000000..8c9872d1d2092fa6ef8eeef9d9d049d842154416 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/config.js @@ -0,0 +1,30 @@ +// @flow strict + +type Config = {| + API_URL: string, + EVENTS_URL: ?string, + FEEDBACK_URL: string, + REQUIRE_ACCESS_TOKEN: boolean, + ACCESS_TOKEN: ?string, + MAX_PARALLEL_IMAGE_REQUESTS: number +|}; + +const config: Config = { + API_URL: 'https://api.mapbox.com', + get EVENTS_URL() { + if (!this.API_URL) { return null; } + if (this.API_URL.indexOf('https://api.mapbox.cn') === 0) { + return 'https://events.mapbox.cn/events/v2'; + } else if (this.API_URL.indexOf('https://api.mapbox.com') === 0) { + return 'https://events.mapbox.com/events/v2'; + } else { + return null; + } + }, + FEEDBACK_URL: 'https://apps.mapbox.com/feedback', + REQUIRE_ACCESS_TOKEN: true, + ACCESS_TOKEN: null, + MAX_PARALLEL_IMAGE_REQUESTS: 16 +}; + +export default config; diff --git a/node_modules/mapbox-gl/src/util/debug.js b/node_modules/mapbox-gl/src/util/debug.js new file mode 100644 index 0000000000000000000000000000000000000000..e26672e7472602c1fe2f250d797770b58ebcdb42 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/debug.js @@ -0,0 +1,28 @@ +// @flow +import {extend} from './util'; +import window from './window'; + +/** + * This is a private namespace for utility functions that will get automatically stripped + * out in production builds. + * + * @private + */ +export const Debug = { + extend(dest: Object, ...sources: Array): Object { + return extend(dest, ...sources); + }, + + run(fn: () => any) { + fn(); + }, + + logToElement(message: string, overwrite: boolean = false, id: string = "log") { + const el = window.document.getElementById(id); + if (el) { + if (overwrite) el.innerHTML = ''; + el.innerHTML += `
${message}`; + } + + } +}; diff --git a/node_modules/mapbox-gl/src/util/dictionary_coder.js b/node_modules/mapbox-gl/src/util/dictionary_coder.js new file mode 100644 index 0000000000000000000000000000000000000000..320eb3548f8040169669be827d2c60df58f9d542 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/dictionary_coder.js @@ -0,0 +1,30 @@ +// @flow strict + +import assert from 'assert'; + +class DictionaryCoder { + _stringToNumber: {[_: string]: number }; + _numberToString: Array; + + constructor(strings: Array) { + this._stringToNumber = {}; + this._numberToString = []; + for (let i = 0; i < strings.length; i++) { + const string = strings[i]; + this._stringToNumber[string] = i; + this._numberToString[i] = string; + } + } + + encode(string: string) { + assert(string in this._stringToNumber); + return this._stringToNumber[string]; + } + + decode(n: number) { + assert(n < this._numberToString.length); + return this._numberToString[n]; + } +} + +export default DictionaryCoder; diff --git a/node_modules/mapbox-gl/src/util/dispatcher.js b/node_modules/mapbox-gl/src/util/dispatcher.js new file mode 100644 index 0000000000000000000000000000000000000000..7a184f8489eb33baf223c83cf53086eb42ae9ee7 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/dispatcher.js @@ -0,0 +1,70 @@ +// @flow + +import {uniqueId, asyncAll} from './util'; +import Actor from './actor'; +import assert from 'assert'; + +import type WorkerPool from './worker_pool'; + +/** + * Responsible for sending messages from a {@link Source} to an associated + * {@link WorkerSource}. + * + * @private + */ +class Dispatcher { + workerPool: WorkerPool; + actors: Array; + currentActor: number; + id: number; + + // exposed to allow stubbing in unit tests + static Actor: Class; + + constructor(workerPool: WorkerPool, parent: any) { + this.workerPool = workerPool; + this.actors = []; + this.currentActor = 0; + this.id = uniqueId(); + const workers = this.workerPool.acquire(this.id); + for (let i = 0; i < workers.length; i++) { + const worker = workers[i]; + const actor = new Dispatcher.Actor(worker, parent, this.id); + actor.name = `Worker ${i}`; + this.actors.push(actor); + } + assert(this.actors.length); + } + + /** + * Broadcast a message to all Workers. + * @private + */ + broadcast(type: string, data: mixed, cb?: Function) { + assert(this.actors.length); + cb = cb || function () {}; + asyncAll(this.actors, (actor, done) => { + actor.send(type, data, done); + }, cb); + } + + /** + * Acquires an actor to dispatch messages to. The actors are distributed in round-robin fashion. + * @returns An actor object backed by a web worker for processing messages. + */ + getActor(): Actor { + assert(this.actors.length); + this.currentActor = (this.currentActor + 1) % this.actors.length; + return this.actors[this.currentActor]; + } + + remove() { + this.actors.forEach((actor) => { actor.remove(); }); + this.actors = []; + this.workerPool.release(this.id); + } +} + +Dispatcher.Actor = Actor; + +export default Dispatcher; diff --git a/node_modules/mapbox-gl/src/util/dom.js b/node_modules/mapbox-gl/src/util/dom.js new file mode 100644 index 0000000000000000000000000000000000000000..34e2af64f8ba70058d13cb72f2f6dd1e91be6acc --- /dev/null +++ b/node_modules/mapbox-gl/src/util/dom.js @@ -0,0 +1,142 @@ +// @flow strict + +import Point from '@mapbox/point-geometry'; + +import window from './window'; +import assert from 'assert'; + +const DOM = {}; +export default DOM; + +DOM.create = function (tagName: string, className: ?string, container?: HTMLElement) { + const el = window.document.createElement(tagName); + if (className !== undefined) el.className = className; + if (container) container.appendChild(el); + return el; +}; + +DOM.createNS = function (namespaceURI: string, tagName: string) { + const el = window.document.createElementNS(namespaceURI, tagName); + return el; +}; + +const docStyle = window.document && window.document.documentElement.style; + +function testProp(props) { + if (!docStyle) return props[0]; + for (let i = 0; i < props.length; i++) { + if (props[i] in docStyle) { + return props[i]; + } + } + return props[0]; +} + +const selectProp = testProp(['userSelect', 'MozUserSelect', 'WebkitUserSelect', 'msUserSelect']); +let userSelect; + +DOM.disableDrag = function () { + if (docStyle && selectProp) { + userSelect = docStyle[selectProp]; + docStyle[selectProp] = 'none'; + } +}; + +DOM.enableDrag = function () { + if (docStyle && selectProp) { + docStyle[selectProp] = userSelect; + } +}; + +const transformProp = testProp(['transform', 'WebkitTransform']); + +DOM.setTransform = function(el: HTMLElement, value: string) { + // https://github.com/facebook/flow/issues/7754 + // $FlowFixMe + el.style[transformProp] = value; +}; + +// Feature detection for {passive: false} support in add/removeEventListener. +let passiveSupported = false; + +try { + // https://github.com/facebook/flow/issues/285 + // $FlowFixMe + const options = Object.defineProperty({}, "passive", { + get() { // eslint-disable-line + passiveSupported = true; + } + }); + window.addEventListener("test", options, options); + window.removeEventListener("test", options, options); +} catch (err) { + passiveSupported = false; +} + +DOM.addEventListener = function(target: *, type: *, callback: *, options: {passive?: boolean, capture?: boolean} = {}) { + if ('passive' in options && passiveSupported) { + target.addEventListener(type, callback, options); + } else { + target.addEventListener(type, callback, options.capture); + } +}; + +DOM.removeEventListener = function(target: *, type: *, callback: *, options: {passive?: boolean, capture?: boolean} = {}) { + if ('passive' in options && passiveSupported) { + target.removeEventListener(type, callback, options); + } else { + target.removeEventListener(type, callback, options.capture); + } +}; + +// Suppress the next click, but only if it's immediate. +const suppressClick: MouseEventListener = function (e) { + e.preventDefault(); + e.stopPropagation(); + window.removeEventListener('click', suppressClick, true); +}; + +DOM.suppressClick = function() { + window.addEventListener('click', suppressClick, true); + window.setTimeout(() => { + window.removeEventListener('click', suppressClick, true); + }, 0); +}; + +DOM.mousePos = function (el: HTMLElement, e: MouseEvent | window.TouchEvent | Touch) { + const rect = el.getBoundingClientRect(); + return new Point( + e.clientX - rect.left - el.clientLeft, + e.clientY - rect.top - el.clientTop + ); +}; + +DOM.touchPos = function (el: HTMLElement, touches: TouchList) { + const rect = el.getBoundingClientRect(), + points = []; + for (let i = 0; i < touches.length; i++) { + points.push(new Point( + touches[i].clientX - rect.left - el.clientLeft, + touches[i].clientY - rect.top - el.clientTop + )); + } + return points; +}; + +DOM.mouseButton = function (e: MouseEvent) { + assert(e.type === 'mousedown' || e.type === 'mouseup'); + if (typeof window.InstallTrigger !== 'undefined' && e.button === 2 && e.ctrlKey && + window.navigator.platform.toUpperCase().indexOf('MAC') >= 0) { + // Fix for https://github.com/mapbox/mapbox-gl-js/issues/3131: + // Firefox (detected by InstallTrigger) on Mac determines e.button = 2 when + // using Control + left click + return 0; + } + return e.button; +}; + +DOM.remove = function(node: HTMLElement) { + if (node.parentNode) { + node.parentNode.removeChild(node); + } +}; diff --git a/node_modules/mapbox-gl/src/util/evented.js b/node_modules/mapbox-gl/src/util/evented.js new file mode 100644 index 0000000000000000000000000000000000000000..de05d10921961a979013dc9cc3e3dc5a243cb8a2 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/evented.js @@ -0,0 +1,174 @@ +// @flow + +import {extend} from './util'; + +type Listener = (Object) => any; +type Listeners = {[_: string]: Array }; + +function _addEventListener(type: string, listener: Listener, listenerList: Listeners) { + const listenerExists = listenerList[type] && listenerList[type].indexOf(listener) !== -1; + if (!listenerExists) { + listenerList[type] = listenerList[type] || []; + listenerList[type].push(listener); + } +} + +function _removeEventListener(type: string, listener: Listener, listenerList: Listeners) { + if (listenerList && listenerList[type]) { + const index = listenerList[type].indexOf(listener); + if (index !== -1) { + listenerList[type].splice(index, 1); + } + } +} + +export class Event { + +type: string; + + constructor(type: string, data: Object = {}) { + extend(this, data); + this.type = type; + } +} + +interface ErrorLike { + message: string; +} + +export class ErrorEvent extends Event { + error: ErrorLike; + + constructor(error: ErrorLike, data: Object = {}) { + super('error', extend({error}, data)); + } +} + +/** + * Methods mixed in to other classes for event capabilities. + * + * @mixin Evented + */ +export class Evented { + _listeners: Listeners; + _oneTimeListeners: Listeners; + _eventedParent: ?Evented; + _eventedParentData: ?(Object | () => Object); + + /** + * Adds a listener to a specified event type. + * + * @param {string} type The event type to add a listen for. + * @param {Function} listener The function to be called when the event is fired. + * The listener function is called with the data object passed to `fire`, + * extended with `target` and `type` properties. + * @returns {Object} `this` + */ + on(type: *, listener: Listener): this { + this._listeners = this._listeners || {}; + _addEventListener(type, listener, this._listeners); + + return this; + } + + /** + * Removes a previously registered event listener. + * + * @param {string} type The event type to remove listeners for. + * @param {Function} listener The listener function to remove. + * @returns {Object} `this` + */ + off(type: *, listener: Listener) { + _removeEventListener(type, listener, this._listeners); + _removeEventListener(type, listener, this._oneTimeListeners); + + return this; + } + + /** + * Adds a listener that will be called only once to a specified event type. + * + * The listener will be called first time the event fires after the listener is registered. + * + * @param {string} type The event type to listen for. + * @param {Function} listener The function to be called when the event is fired the first time. + * @returns {Object} `this` + */ + once(type: *, listener: Listener) { + this._oneTimeListeners = this._oneTimeListeners || {}; + _addEventListener(type, listener, this._oneTimeListeners); + + return this; + } + + fire(event: Event, properties?: Object) { + // Compatibility with (type: string, properties: Object) signature from previous versions. + // See https://github.com/mapbox/mapbox-gl-js/issues/6522, + // https://github.com/mapbox/mapbox-gl-draw/issues/766 + if (typeof event === 'string') { + event = new Event(event, properties || {}); + } + + const type = event.type; + + if (this.listens(type)) { + (event: any).target = this; + + // make sure adding or removing listeners inside other listeners won't cause an infinite loop + const listeners = this._listeners && this._listeners[type] ? this._listeners[type].slice() : []; + for (const listener of listeners) { + listener.call(this, event); + } + + const oneTimeListeners = this._oneTimeListeners && this._oneTimeListeners[type] ? this._oneTimeListeners[type].slice() : []; + for (const listener of oneTimeListeners) { + _removeEventListener(type, listener, this._oneTimeListeners); + listener.call(this, event); + } + + const parent = this._eventedParent; + if (parent) { + extend( + event, + typeof this._eventedParentData === 'function' ? this._eventedParentData() : this._eventedParentData + ); + parent.fire(event); + } + + // To ensure that no error events are dropped, print them to the + // console if they have no listeners. + } else if (event instanceof ErrorEvent) { + console.error(event.error); + } + + return this; + } + + /** + * Returns a true if this instance of Evented or any forwardeed instances of Evented have a listener for the specified type. + * + * @param {string} type The event type + * @returns {boolean} `true` if there is at least one registered listener for specified event type, `false` otherwise + * @private + */ + listens(type: string) { + return ( + (this._listeners && this._listeners[type] && this._listeners[type].length > 0) || + (this._oneTimeListeners && this._oneTimeListeners[type] && this._oneTimeListeners[type].length > 0) || + (this._eventedParent && this._eventedParent.listens(type)) + ); + } + + /** + * Bubble all events fired by this instance of Evented to this parent instance of Evented. + * + * @private + * @returns {Object} `this` + * @private + */ + setEventedParent(parent: ?Evented, data?: Object | () => Object) { + this._eventedParent = parent; + this._eventedParentData = data; + + return this; + } +} diff --git a/node_modules/mapbox-gl/src/util/find_pole_of_inaccessibility.js b/node_modules/mapbox-gl/src/util/find_pole_of_inaccessibility.js new file mode 100644 index 0000000000000000000000000000000000000000..5bf8c1c44c852215229c3ce8b17da668124ce834 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/find_pole_of_inaccessibility.js @@ -0,0 +1,129 @@ +// @flow + +import Queue from 'tinyqueue'; + +import Point from '@mapbox/point-geometry'; +import {distToSegmentSquared} from './intersection_tests'; + +/** + * Finds an approximation of a polygon's Pole Of Inaccessibiliy https://en.wikipedia.org/wiki/Pole_of_inaccessibility + * This is a copy of http://github.com/mapbox/polylabel adapted to use Points + * + * @param polygonRings first item in array is the outer ring followed optionally by the list of holes, should be an element of the result of util/classify_rings + * @param precision Specified in input coordinate units. If 0 returns after first run, if > 0 repeatedly narrows the search space until the radius of the area searched for the best pole is less than precision + * @param debug Print some statistics to the console during execution + * @returns Pole of Inaccessibiliy. + * @private + */ +export default function (polygonRings: Array>, precision?: number = 1, debug?: boolean = false): Point { + // find the bounding box of the outer ring + let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + const outerRing = polygonRings[0]; + for (let i = 0; i < outerRing.length; i++) { + const p = outerRing[i]; + if (!i || p.x < minX) minX = p.x; + if (!i || p.y < minY) minY = p.y; + if (!i || p.x > maxX) maxX = p.x; + if (!i || p.y > maxY) maxY = p.y; + } + + const width = maxX - minX; + const height = maxY - minY; + const cellSize = Math.min(width, height); + let h = cellSize / 2; + + // a priority queue of cells in order of their "potential" (max distance to polygon) + const cellQueue = new Queue([], compareMax); + + if (cellSize === 0) return new Point(minX, minY); + + // cover polygon with initial cells + for (let x = minX; x < maxX; x += cellSize) { + for (let y = minY; y < maxY; y += cellSize) { + cellQueue.push(new Cell(x + h, y + h, h, polygonRings)); + } + } + + // take centroid as the first best guess + let bestCell = getCentroidCell(polygonRings); + let numProbes = cellQueue.length; + + while (cellQueue.length) { + // pick the most promising cell from the queue + const cell = cellQueue.pop(); + + // update the best cell if we found a better one + if (cell.d > bestCell.d || !bestCell.d) { + bestCell = cell; + if (debug) console.log('found best %d after %d probes', Math.round(1e4 * cell.d) / 1e4, numProbes); + } + + // do not drill down further if there's no chance of a better solution + if (cell.max - bestCell.d <= precision) continue; + + // split the cell into four cells + h = cell.h / 2; + cellQueue.push(new Cell(cell.p.x - h, cell.p.y - h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x + h, cell.p.y - h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x - h, cell.p.y + h, h, polygonRings)); + cellQueue.push(new Cell(cell.p.x + h, cell.p.y + h, h, polygonRings)); + numProbes += 4; + } + + if (debug) { + console.log(`num probes: ${numProbes}`); + console.log(`best distance: ${bestCell.d}`); + } + + return bestCell.p; +} + +function compareMax(a, b) { + return b.max - a.max; +} + +function Cell(x, y, h, polygon) { + this.p = new Point(x, y); + this.h = h; // half the cell size + this.d = pointToPolygonDist(this.p, polygon); // distance from cell center to polygon + this.max = this.d + this.h * Math.SQRT2; // max distance to polygon within a cell +} + +// signed distance from point to polygon outline (negative if point is outside) +function pointToPolygonDist(p, polygon) { + let inside = false; + let minDistSq = Infinity; + + for (let k = 0; k < polygon.length; k++) { + const ring = polygon[k]; + + for (let i = 0, len = ring.length, j = len - 1; i < len; j = i++) { + const a = ring[i]; + const b = ring[j]; + + if ((a.y > p.y !== b.y > p.y) && + (p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x)) inside = !inside; + + minDistSq = Math.min(minDistSq, distToSegmentSquared(p, a, b)); + } + } + + return (inside ? 1 : -1) * Math.sqrt(minDistSq); +} + +// get polygon centroid +function getCentroidCell(polygon) { + let area = 0; + let x = 0; + let y = 0; + const points = polygon[0]; + for (let i = 0, len = points.length, j = len - 1; i < len; j = i++) { + const a = points[i]; + const b = points[j]; + const f = a.x * b.y - b.x * a.y; + x += (a.x + b.x) * f; + y += (a.y + b.y) * f; + area += f * 3; + } + return new Cell(x / area, y / area, 0, polygon); +} diff --git a/node_modules/mapbox-gl/src/util/global_worker_pool.js b/node_modules/mapbox-gl/src/util/global_worker_pool.js new file mode 100644 index 0000000000000000000000000000000000000000..3fb1d06258d70b8ea10a99845419e03158bd7961 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/global_worker_pool.js @@ -0,0 +1,35 @@ +// @flow + +import WorkerPool, {PRELOAD_POOL_ID} from './worker_pool'; + +let globalWorkerPool; + +/** + * Creates (if necessary) and returns the single, global WorkerPool instance + * to be shared across each Map + * @private + */ +export default function getGlobalWorkerPool () { + if (!globalWorkerPool) { + globalWorkerPool = new WorkerPool(); + } + return globalWorkerPool; +} + +export function prewarm() { + const workerPool = getGlobalWorkerPool(); + workerPool.acquire(PRELOAD_POOL_ID); +} + +export function clearPrewarmedResources() { + const pool = globalWorkerPool; + if (pool) { + // Remove the pool only if all maps that referenced the preloaded global worker pool have been removed. + if (pool.isPreloaded() && pool.numActive() === 1) { + pool.release(PRELOAD_POOL_ID); + globalWorkerPool = null; + } else { + console.warn('Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()'); + } + } +} diff --git a/node_modules/mapbox-gl/src/util/image.js b/node_modules/mapbox-gl/src/util/image.js new file mode 100644 index 0000000000000000000000000000000000000000..2ef55d01391913a59e6e59953a0b8f944b20b8d5 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/image.js @@ -0,0 +1,142 @@ +// @flow + +import assert from 'assert'; + +import {register} from './web_worker_transfer'; + +export type Size = { + width: number, + height: number +}; + +type Point = { + x: number, + y: number +}; + +function createImage(image: *, {width, height}: Size, channels: number, data?: Uint8Array | Uint8ClampedArray) { + if (!data) { + data = new Uint8Array(width * height * channels); + } else if (data instanceof Uint8ClampedArray) { + data = new Uint8Array(data.buffer); + } else if (data.length !== width * height * channels) { + throw new RangeError('mismatched image size'); + } + image.width = width; + image.height = height; + image.data = data; + return image; +} + +function resizeImage(image: *, {width, height}: Size, channels: number) { + if (width === image.width && height === image.height) { + return; + } + + const newImage = createImage({}, {width, height}, channels); + + copyImage(image, newImage, {x: 0, y: 0}, {x: 0, y: 0}, { + width: Math.min(image.width, width), + height: Math.min(image.height, height) + }, channels); + + image.width = width; + image.height = height; + image.data = newImage.data; +} + +function copyImage(srcImg: *, dstImg: *, srcPt: Point, dstPt: Point, size: Size, channels: number) { + if (size.width === 0 || size.height === 0) { + return dstImg; + } + + if (size.width > srcImg.width || + size.height > srcImg.height || + srcPt.x > srcImg.width - size.width || + srcPt.y > srcImg.height - size.height) { + throw new RangeError('out of range source coordinates for image copy'); + } + + if (size.width > dstImg.width || + size.height > dstImg.height || + dstPt.x > dstImg.width - size.width || + dstPt.y > dstImg.height - size.height) { + throw new RangeError('out of range destination coordinates for image copy'); + } + + const srcData = srcImg.data; + const dstData = dstImg.data; + + assert(srcData !== dstData); + + for (let y = 0; y < size.height; y++) { + const srcOffset = ((srcPt.y + y) * srcImg.width + srcPt.x) * channels; + const dstOffset = ((dstPt.y + y) * dstImg.width + dstPt.x) * channels; + for (let i = 0; i < size.width * channels; i++) { + dstData[dstOffset + i] = srcData[srcOffset + i]; + } + } + return dstImg; +} + +export class AlphaImage { + width: number; + height: number; + data: Uint8Array; + + constructor(size: Size, data?: Uint8Array | Uint8ClampedArray) { + createImage(this, size, 1, data); + } + + resize(size: Size) { + resizeImage(this, size, 1); + } + + clone() { + return new AlphaImage({width: this.width, height: this.height}, new Uint8Array(this.data)); + } + + static copy(srcImg: AlphaImage, dstImg: AlphaImage, srcPt: Point, dstPt: Point, size: Size) { + copyImage(srcImg, dstImg, srcPt, dstPt, size, 1); + } +} + +// Not premultiplied, because ImageData is not premultiplied. +// UNPACK_PREMULTIPLY_ALPHA_WEBGL must be used when uploading to a texture. +export class RGBAImage { + width: number; + height: number; + + // data must be a Uint8Array instead of Uint8ClampedArray because texImage2D does not + // support Uint8ClampedArray in all browsers + data: Uint8Array; + + constructor(size: Size, data?: Uint8Array | Uint8ClampedArray) { + createImage(this, size, 4, data); + } + + resize(size: Size) { + resizeImage(this, size, 4); + } + + replace(data: Uint8Array | Uint8ClampedArray, copy?: boolean) { + if (copy) { + this.data.set(data); + } else if (data instanceof Uint8ClampedArray) { + this.data = new Uint8Array(data.buffer); + } else { + this.data = data; + } + } + + clone() { + return new RGBAImage({width: this.width, height: this.height}, new Uint8Array(this.data)); + } + + static copy(srcImg: RGBAImage | ImageData, dstImg: RGBAImage, srcPt: Point, dstPt: Point, size: Size) { + copyImage(srcImg, dstImg, srcPt, dstPt, size, 4); + } +} + +register('AlphaImage', AlphaImage); +register('RGBAImage', RGBAImage); diff --git a/node_modules/mapbox-gl/src/util/intersection_tests.js b/node_modules/mapbox-gl/src/util/intersection_tests.js new file mode 100644 index 0000000000000000000000000000000000000000..d79f6f744b341f8de6c389a63be8cc9b375e0fa9 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/intersection_tests.js @@ -0,0 +1,208 @@ +// @flow + +import {isCounterClockwise} from './util'; + +import Point from '@mapbox/point-geometry'; + +export {polygonIntersectsBufferedPoint, polygonIntersectsMultiPolygon, polygonIntersectsBufferedMultiLine, polygonIntersectsPolygon, distToSegmentSquared, polygonIntersectsBox}; + +type Line = Array; +type MultiLine = Array; +type Ring = Array; +type Polygon = Array; +type MultiPolygon = Array; + +function polygonIntersectsPolygon(polygonA: Polygon, polygonB: Polygon) { + for (let i = 0; i < polygonA.length; i++) { + if (polygonContainsPoint(polygonB, polygonA[i])) return true; + } + + for (let i = 0; i < polygonB.length; i++) { + if (polygonContainsPoint(polygonA, polygonB[i])) return true; + } + + if (lineIntersectsLine(polygonA, polygonB)) return true; + + return false; +} + +function polygonIntersectsBufferedPoint(polygon: Polygon, point: Point, radius: number) { + if (polygonContainsPoint(polygon, point)) return true; + if (pointIntersectsBufferedLine(point, polygon, radius)) return true; + return false; +} + +function polygonIntersectsMultiPolygon(polygon: Polygon, multiPolygon: MultiPolygon) { + + if (polygon.length === 1) { + return multiPolygonContainsPoint(multiPolygon, polygon[0]); + } + + for (let m = 0; m < multiPolygon.length; m++) { + const ring = multiPolygon[m]; + for (let n = 0; n < ring.length; n++) { + if (polygonContainsPoint(polygon, ring[n])) return true; + } + } + + for (let i = 0; i < polygon.length; i++) { + if (multiPolygonContainsPoint(multiPolygon, polygon[i])) return true; + } + + for (let k = 0; k < multiPolygon.length; k++) { + if (lineIntersectsLine(polygon, multiPolygon[k])) return true; + } + + return false; +} + +function polygonIntersectsBufferedMultiLine(polygon: Polygon, multiLine: MultiLine, radius: number) { + for (let i = 0; i < multiLine.length; i++) { + const line = multiLine[i]; + + if (polygon.length >= 3) { + for (let k = 0; k < line.length; k++) { + if (polygonContainsPoint(polygon, line[k])) return true; + } + } + + if (lineIntersectsBufferedLine(polygon, line, radius)) return true; + } + return false; +} + +function lineIntersectsBufferedLine(lineA: Line, lineB: Line, radius: number) { + + if (lineA.length > 1) { + if (lineIntersectsLine(lineA, lineB)) return true; + + // Check whether any point in either line is within radius of the other line + for (let j = 0; j < lineB.length; j++) { + if (pointIntersectsBufferedLine(lineB[j], lineA, radius)) return true; + } + } + + for (let k = 0; k < lineA.length; k++) { + if (pointIntersectsBufferedLine(lineA[k], lineB, radius)) return true; + } + + return false; +} + +function lineIntersectsLine(lineA: Line, lineB: Line) { + if (lineA.length === 0 || lineB.length === 0) return false; + for (let i = 0; i < lineA.length - 1; i++) { + const a0 = lineA[i]; + const a1 = lineA[i + 1]; + for (let j = 0; j < lineB.length - 1; j++) { + const b0 = lineB[j]; + const b1 = lineB[j + 1]; + if (lineSegmentIntersectsLineSegment(a0, a1, b0, b1)) return true; + } + } + return false; +} + +function lineSegmentIntersectsLineSegment(a0: Point, a1: Point, b0: Point, b1: Point) { + return isCounterClockwise(a0, b0, b1) !== isCounterClockwise(a1, b0, b1) && + isCounterClockwise(a0, a1, b0) !== isCounterClockwise(a0, a1, b1); +} + +function pointIntersectsBufferedLine(p: Point, line: Line, radius: number) { + const radiusSquared = radius * radius; + + if (line.length === 1) return p.distSqr(line[0]) < radiusSquared; + + for (let i = 1; i < line.length; i++) { + // Find line segments that have a distance <= radius^2 to p + // In that case, we treat the line as "containing point p". + const v = line[i - 1], w = line[i]; + if (distToSegmentSquared(p, v, w) < radiusSquared) return true; + } + return false; +} + +// Code from http://stackoverflow.com/a/1501725/331379. +function distToSegmentSquared(p: Point, v: Point, w: Point) { + const l2 = v.distSqr(w); + if (l2 === 0) return p.distSqr(v); + const t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2; + if (t < 0) return p.distSqr(v); + if (t > 1) return p.distSqr(w); + return p.distSqr(w.sub(v)._mult(t)._add(v)); +} + +// point in polygon ray casting algorithm +function multiPolygonContainsPoint(rings: Array, p: Point) { + let c = false, + ring, p1, p2; + + for (let k = 0; k < rings.length; k++) { + ring = rings[k]; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + if (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) { + c = !c; + } + } + } + return c; +} + +function polygonContainsPoint(ring: Ring, p: Point) { + let c = false; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const p1 = ring[i]; + const p2 = ring[j]; + if (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) { + c = !c; + } + } + return c; +} + +function polygonIntersectsBox(ring: Ring, boxX1: number, boxY1: number, boxX2: number, boxY2: number) { + for (const p of ring) { + if (boxX1 <= p.x && + boxY1 <= p.y && + boxX2 >= p.x && + boxY2 >= p.y) return true; + } + + const corners = [ + new Point(boxX1, boxY1), + new Point(boxX1, boxY2), + new Point(boxX2, boxY2), + new Point(boxX2, boxY1)]; + + if (ring.length > 2) { + for (const corner of corners) { + if (polygonContainsPoint(ring, corner)) return true; + } + } + + for (let i = 0; i < ring.length - 1; i++) { + const p1 = ring[i]; + const p2 = ring[i + 1]; + if (edgeIntersectsBox(p1, p2, corners)) return true; + } + + return false; +} + +function edgeIntersectsBox(e1: Point, e2: Point, corners: Array) { + const tl = corners[0]; + const br = corners[2]; + // the edge and box do not intersect in either the x or y dimensions + if (((e1.x < tl.x) && (e2.x < tl.x)) || + ((e1.x > br.x) && (e2.x > br.x)) || + ((e1.y < tl.y) && (e2.y < tl.y)) || + ((e1.y > br.y) && (e2.y > br.y))) return false; + + // check if all corners of the box are on the same side of the edge + const dir = isCounterClockwise(e1, e2, corners[0]); + return dir !== isCounterClockwise(e1, e2, corners[1]) || + dir !== isCounterClockwise(e1, e2, corners[2]) || + dir !== isCounterClockwise(e1, e2, corners[3]); +} diff --git a/node_modules/mapbox-gl/src/util/is_char_in_unicode_block.js b/node_modules/mapbox-gl/src/util/is_char_in_unicode_block.js new file mode 100644 index 0000000000000000000000000000000000000000..427f741d196e5e6842fee319eabfaf2400d56075 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/is_char_in_unicode_block.js @@ -0,0 +1,311 @@ +// @flow + +// The following table comes from . +// Keep it synchronized with . + +type UnicodeBlockLookup = {[key: string]: (char: number) => boolean}; + +const unicodeBlockLookup: UnicodeBlockLookup = { + // 'Basic Latin': (char) => char >= 0x0000 && char <= 0x007F, + 'Latin-1 Supplement': (char) => char >= 0x0080 && char <= 0x00FF, + // 'Latin Extended-A': (char) => char >= 0x0100 && char <= 0x017F, + // 'Latin Extended-B': (char) => char >= 0x0180 && char <= 0x024F, + // 'IPA Extensions': (char) => char >= 0x0250 && char <= 0x02AF, + // 'Spacing Modifier Letters': (char) => char >= 0x02B0 && char <= 0x02FF, + // 'Combining Diacritical Marks': (char) => char >= 0x0300 && char <= 0x036F, + // 'Greek and Coptic': (char) => char >= 0x0370 && char <= 0x03FF, + // 'Cyrillic': (char) => char >= 0x0400 && char <= 0x04FF, + // 'Cyrillic Supplement': (char) => char >= 0x0500 && char <= 0x052F, + // 'Armenian': (char) => char >= 0x0530 && char <= 0x058F, + //'Hebrew': (char) => char >= 0x0590 && char <= 0x05FF, + 'Arabic': (char) => char >= 0x0600 && char <= 0x06FF, + //'Syriac': (char) => char >= 0x0700 && char <= 0x074F, + 'Arabic Supplement': (char) => char >= 0x0750 && char <= 0x077F, + // 'Thaana': (char) => char >= 0x0780 && char <= 0x07BF, + // 'NKo': (char) => char >= 0x07C0 && char <= 0x07FF, + // 'Samaritan': (char) => char >= 0x0800 && char <= 0x083F, + // 'Mandaic': (char) => char >= 0x0840 && char <= 0x085F, + // 'Syriac Supplement': (char) => char >= 0x0860 && char <= 0x086F, + 'Arabic Extended-A': (char) => char >= 0x08A0 && char <= 0x08FF, + // 'Devanagari': (char) => char >= 0x0900 && char <= 0x097F, + // 'Bengali': (char) => char >= 0x0980 && char <= 0x09FF, + // 'Gurmukhi': (char) => char >= 0x0A00 && char <= 0x0A7F, + // 'Gujarati': (char) => char >= 0x0A80 && char <= 0x0AFF, + // 'Oriya': (char) => char >= 0x0B00 && char <= 0x0B7F, + // 'Tamil': (char) => char >= 0x0B80 && char <= 0x0BFF, + // 'Telugu': (char) => char >= 0x0C00 && char <= 0x0C7F, + // 'Kannada': (char) => char >= 0x0C80 && char <= 0x0CFF, + // 'Malayalam': (char) => char >= 0x0D00 && char <= 0x0D7F, + // 'Sinhala': (char) => char >= 0x0D80 && char <= 0x0DFF, + // 'Thai': (char) => char >= 0x0E00 && char <= 0x0E7F, + // 'Lao': (char) => char >= 0x0E80 && char <= 0x0EFF, + // 'Tibetan': (char) => char >= 0x0F00 && char <= 0x0FFF, + // 'Myanmar': (char) => char >= 0x1000 && char <= 0x109F, + // 'Georgian': (char) => char >= 0x10A0 && char <= 0x10FF, + 'Hangul Jamo': (char) => char >= 0x1100 && char <= 0x11FF, + // 'Ethiopic': (char) => char >= 0x1200 && char <= 0x137F, + // 'Ethiopic Supplement': (char) => char >= 0x1380 && char <= 0x139F, + // 'Cherokee': (char) => char >= 0x13A0 && char <= 0x13FF, + 'Unified Canadian Aboriginal Syllabics': (char) => char >= 0x1400 && char <= 0x167F, + // 'Ogham': (char) => char >= 0x1680 && char <= 0x169F, + // 'Runic': (char) => char >= 0x16A0 && char <= 0x16FF, + // 'Tagalog': (char) => char >= 0x1700 && char <= 0x171F, + // 'Hanunoo': (char) => char >= 0x1720 && char <= 0x173F, + // 'Buhid': (char) => char >= 0x1740 && char <= 0x175F, + // 'Tagbanwa': (char) => char >= 0x1760 && char <= 0x177F, + 'Khmer': (char) => char >= 0x1780 && char <= 0x17FF, + // 'Mongolian': (char) => char >= 0x1800 && char <= 0x18AF, + 'Unified Canadian Aboriginal Syllabics Extended': (char) => char >= 0x18B0 && char <= 0x18FF, + // 'Limbu': (char) => char >= 0x1900 && char <= 0x194F, + // 'Tai Le': (char) => char >= 0x1950 && char <= 0x197F, + // 'New Tai Lue': (char) => char >= 0x1980 && char <= 0x19DF, + // 'Khmer Symbols': (char) => char >= 0x19E0 && char <= 0x19FF, + // 'Buginese': (char) => char >= 0x1A00 && char <= 0x1A1F, + // 'Tai Tham': (char) => char >= 0x1A20 && char <= 0x1AAF, + // 'Combining Diacritical Marks Extended': (char) => char >= 0x1AB0 && char <= 0x1AFF, + // 'Balinese': (char) => char >= 0x1B00 && char <= 0x1B7F, + // 'Sundanese': (char) => char >= 0x1B80 && char <= 0x1BBF, + // 'Batak': (char) => char >= 0x1BC0 && char <= 0x1BFF, + // 'Lepcha': (char) => char >= 0x1C00 && char <= 0x1C4F, + // 'Ol Chiki': (char) => char >= 0x1C50 && char <= 0x1C7F, + // 'Cyrillic Extended-C': (char) => char >= 0x1C80 && char <= 0x1C8F, + // 'Georgian Extended': (char) => char >= 0x1C90 && char <= 0x1CBF, + // 'Sundanese Supplement': (char) => char >= 0x1CC0 && char <= 0x1CCF, + // 'Vedic Extensions': (char) => char >= 0x1CD0 && char <= 0x1CFF, + // 'Phonetic Extensions': (char) => char >= 0x1D00 && char <= 0x1D7F, + // 'Phonetic Extensions Supplement': (char) => char >= 0x1D80 && char <= 0x1DBF, + // 'Combining Diacritical Marks Supplement': (char) => char >= 0x1DC0 && char <= 0x1DFF, + // 'Latin Extended Additional': (char) => char >= 0x1E00 && char <= 0x1EFF, + // 'Greek Extended': (char) => char >= 0x1F00 && char <= 0x1FFF, + 'General Punctuation': (char) => char >= 0x2000 && char <= 0x206F, + // 'Superscripts and Subscripts': (char) => char >= 0x2070 && char <= 0x209F, + // 'Currency Symbols': (char) => char >= 0x20A0 && char <= 0x20CF, + // 'Combining Diacritical Marks for Symbols': (char) => char >= 0x20D0 && char <= 0x20FF, + 'Letterlike Symbols': (char) => char >= 0x2100 && char <= 0x214F, + 'Number Forms': (char) => char >= 0x2150 && char <= 0x218F, + // 'Arrows': (char) => char >= 0x2190 && char <= 0x21FF, + // 'Mathematical Operators': (char) => char >= 0x2200 && char <= 0x22FF, + 'Miscellaneous Technical': (char) => char >= 0x2300 && char <= 0x23FF, + 'Control Pictures': (char) => char >= 0x2400 && char <= 0x243F, + 'Optical Character Recognition': (char) => char >= 0x2440 && char <= 0x245F, + 'Enclosed Alphanumerics': (char) => char >= 0x2460 && char <= 0x24FF, + // 'Box Drawing': (char) => char >= 0x2500 && char <= 0x257F, + // 'Block Elements': (char) => char >= 0x2580 && char <= 0x259F, + 'Geometric Shapes': (char) => char >= 0x25A0 && char <= 0x25FF, + 'Miscellaneous Symbols': (char) => char >= 0x2600 && char <= 0x26FF, + // 'Dingbats': (char) => char >= 0x2700 && char <= 0x27BF, + // 'Miscellaneous Mathematical Symbols-A': (char) => char >= 0x27C0 && char <= 0x27EF, + // 'Supplemental Arrows-A': (char) => char >= 0x27F0 && char <= 0x27FF, + // 'Braille Patterns': (char) => char >= 0x2800 && char <= 0x28FF, + // 'Supplemental Arrows-B': (char) => char >= 0x2900 && char <= 0x297F, + // 'Miscellaneous Mathematical Symbols-B': (char) => char >= 0x2980 && char <= 0x29FF, + // 'Supplemental Mathematical Operators': (char) => char >= 0x2A00 && char <= 0x2AFF, + 'Miscellaneous Symbols and Arrows': (char) => char >= 0x2B00 && char <= 0x2BFF, + // 'Glagolitic': (char) => char >= 0x2C00 && char <= 0x2C5F, + // 'Latin Extended-C': (char) => char >= 0x2C60 && char <= 0x2C7F, + // 'Coptic': (char) => char >= 0x2C80 && char <= 0x2CFF, + // 'Georgian Supplement': (char) => char >= 0x2D00 && char <= 0x2D2F, + // 'Tifinagh': (char) => char >= 0x2D30 && char <= 0x2D7F, + // 'Ethiopic Extended': (char) => char >= 0x2D80 && char <= 0x2DDF, + // 'Cyrillic Extended-A': (char) => char >= 0x2DE0 && char <= 0x2DFF, + // 'Supplemental Punctuation': (char) => char >= 0x2E00 && char <= 0x2E7F, + 'CJK Radicals Supplement': (char) => char >= 0x2E80 && char <= 0x2EFF, + 'Kangxi Radicals': (char) => char >= 0x2F00 && char <= 0x2FDF, + 'Ideographic Description Characters': (char) => char >= 0x2FF0 && char <= 0x2FFF, + 'CJK Symbols and Punctuation': (char) => char >= 0x3000 && char <= 0x303F, + 'Hiragana': (char) => char >= 0x3040 && char <= 0x309F, + 'Katakana': (char) => char >= 0x30A0 && char <= 0x30FF, + 'Bopomofo': (char) => char >= 0x3100 && char <= 0x312F, + 'Hangul Compatibility Jamo': (char) => char >= 0x3130 && char <= 0x318F, + 'Kanbun': (char) => char >= 0x3190 && char <= 0x319F, + 'Bopomofo Extended': (char) => char >= 0x31A0 && char <= 0x31BF, + 'CJK Strokes': (char) => char >= 0x31C0 && char <= 0x31EF, + 'Katakana Phonetic Extensions': (char) => char >= 0x31F0 && char <= 0x31FF, + 'Enclosed CJK Letters and Months': (char) => char >= 0x3200 && char <= 0x32FF, + 'CJK Compatibility': (char) => char >= 0x3300 && char <= 0x33FF, + 'CJK Unified Ideographs Extension A': (char) => char >= 0x3400 && char <= 0x4DBF, + 'Yijing Hexagram Symbols': (char) => char >= 0x4DC0 && char <= 0x4DFF, + 'CJK Unified Ideographs': (char) => char >= 0x4E00 && char <= 0x9FFF, + 'Yi Syllables': (char) => char >= 0xA000 && char <= 0xA48F, + 'Yi Radicals': (char) => char >= 0xA490 && char <= 0xA4CF, + // 'Lisu': (char) => char >= 0xA4D0 && char <= 0xA4FF, + // 'Vai': (char) => char >= 0xA500 && char <= 0xA63F, + // 'Cyrillic Extended-B': (char) => char >= 0xA640 && char <= 0xA69F, + // 'Bamum': (char) => char >= 0xA6A0 && char <= 0xA6FF, + // 'Modifier Tone Letters': (char) => char >= 0xA700 && char <= 0xA71F, + // 'Latin Extended-D': (char) => char >= 0xA720 && char <= 0xA7FF, + // 'Syloti Nagri': (char) => char >= 0xA800 && char <= 0xA82F, + // 'Common Indic Number Forms': (char) => char >= 0xA830 && char <= 0xA83F, + // 'Phags-pa': (char) => char >= 0xA840 && char <= 0xA87F, + // 'Saurashtra': (char) => char >= 0xA880 && char <= 0xA8DF, + // 'Devanagari Extended': (char) => char >= 0xA8E0 && char <= 0xA8FF, + // 'Kayah Li': (char) => char >= 0xA900 && char <= 0xA92F, + // 'Rejang': (char) => char >= 0xA930 && char <= 0xA95F, + 'Hangul Jamo Extended-A': (char) => char >= 0xA960 && char <= 0xA97F, + // 'Javanese': (char) => char >= 0xA980 && char <= 0xA9DF, + // 'Myanmar Extended-B': (char) => char >= 0xA9E0 && char <= 0xA9FF, + // 'Cham': (char) => char >= 0xAA00 && char <= 0xAA5F, + // 'Myanmar Extended-A': (char) => char >= 0xAA60 && char <= 0xAA7F, + // 'Tai Viet': (char) => char >= 0xAA80 && char <= 0xAADF, + // 'Meetei Mayek Extensions': (char) => char >= 0xAAE0 && char <= 0xAAFF, + // 'Ethiopic Extended-A': (char) => char >= 0xAB00 && char <= 0xAB2F, + // 'Latin Extended-E': (char) => char >= 0xAB30 && char <= 0xAB6F, + // 'Cherokee Supplement': (char) => char >= 0xAB70 && char <= 0xABBF, + // 'Meetei Mayek': (char) => char >= 0xABC0 && char <= 0xABFF, + 'Hangul Syllables': (char) => char >= 0xAC00 && char <= 0xD7AF, + 'Hangul Jamo Extended-B': (char) => char >= 0xD7B0 && char <= 0xD7FF, + // 'High Surrogates': (char) => char >= 0xD800 && char <= 0xDB7F, + // 'High Private Use Surrogates': (char) => char >= 0xDB80 && char <= 0xDBFF, + // 'Low Surrogates': (char) => char >= 0xDC00 && char <= 0xDFFF, + 'Private Use Area': (char) => char >= 0xE000 && char <= 0xF8FF, + 'CJK Compatibility Ideographs': (char) => char >= 0xF900 && char <= 0xFAFF, + // 'Alphabetic Presentation Forms': (char) => char >= 0xFB00 && char <= 0xFB4F, + 'Arabic Presentation Forms-A': (char) => char >= 0xFB50 && char <= 0xFDFF, + // 'Variation Selectors': (char) => char >= 0xFE00 && char <= 0xFE0F, + 'Vertical Forms': (char) => char >= 0xFE10 && char <= 0xFE1F, + // 'Combining Half Marks': (char) => char >= 0xFE20 && char <= 0xFE2F, + 'CJK Compatibility Forms': (char) => char >= 0xFE30 && char <= 0xFE4F, + 'Small Form Variants': (char) => char >= 0xFE50 && char <= 0xFE6F, + 'Arabic Presentation Forms-B': (char) => char >= 0xFE70 && char <= 0xFEFF, + 'Halfwidth and Fullwidth Forms': (char) => char >= 0xFF00 && char <= 0xFFEF + // 'Specials': (char) => char >= 0xFFF0 && char <= 0xFFFF, + // 'Linear B Syllabary': (char) => char >= 0x10000 && char <= 0x1007F, + // 'Linear B Ideograms': (char) => char >= 0x10080 && char <= 0x100FF, + // 'Aegean Numbers': (char) => char >= 0x10100 && char <= 0x1013F, + // 'Ancient Greek Numbers': (char) => char >= 0x10140 && char <= 0x1018F, + // 'Ancient Symbols': (char) => char >= 0x10190 && char <= 0x101CF, + // 'Phaistos Disc': (char) => char >= 0x101D0 && char <= 0x101FF, + // 'Lycian': (char) => char >= 0x10280 && char <= 0x1029F, + // 'Carian': (char) => char >= 0x102A0 && char <= 0x102DF, + // 'Coptic Epact Numbers': (char) => char >= 0x102E0 && char <= 0x102FF, + // 'Old Italic': (char) => char >= 0x10300 && char <= 0x1032F, + // 'Gothic': (char) => char >= 0x10330 && char <= 0x1034F, + // 'Old Permic': (char) => char >= 0x10350 && char <= 0x1037F, + // 'Ugaritic': (char) => char >= 0x10380 && char <= 0x1039F, + // 'Old Persian': (char) => char >= 0x103A0 && char <= 0x103DF, + // 'Deseret': (char) => char >= 0x10400 && char <= 0x1044F, + // 'Shavian': (char) => char >= 0x10450 && char <= 0x1047F, + // 'Osmanya': (char) => char >= 0x10480 && char <= 0x104AF, + // 'Osage': (char) => char >= 0x104B0 && char <= 0x104FF, + // 'Elbasan': (char) => char >= 0x10500 && char <= 0x1052F, + // 'Caucasian Albanian': (char) => char >= 0x10530 && char <= 0x1056F, + // 'Linear A': (char) => char >= 0x10600 && char <= 0x1077F, + // 'Cypriot Syllabary': (char) => char >= 0x10800 && char <= 0x1083F, + // 'Imperial Aramaic': (char) => char >= 0x10840 && char <= 0x1085F, + // 'Palmyrene': (char) => char >= 0x10860 && char <= 0x1087F, + // 'Nabataean': (char) => char >= 0x10880 && char <= 0x108AF, + // 'Hatran': (char) => char >= 0x108E0 && char <= 0x108FF, + // 'Phoenician': (char) => char >= 0x10900 && char <= 0x1091F, + // 'Lydian': (char) => char >= 0x10920 && char <= 0x1093F, + // 'Meroitic Hieroglyphs': (char) => char >= 0x10980 && char <= 0x1099F, + // 'Meroitic Cursive': (char) => char >= 0x109A0 && char <= 0x109FF, + // 'Kharoshthi': (char) => char >= 0x10A00 && char <= 0x10A5F, + // 'Old South Arabian': (char) => char >= 0x10A60 && char <= 0x10A7F, + // 'Old North Arabian': (char) => char >= 0x10A80 && char <= 0x10A9F, + // 'Manichaean': (char) => char >= 0x10AC0 && char <= 0x10AFF, + // 'Avestan': (char) => char >= 0x10B00 && char <= 0x10B3F, + // 'Inscriptional Parthian': (char) => char >= 0x10B40 && char <= 0x10B5F, + // 'Inscriptional Pahlavi': (char) => char >= 0x10B60 && char <= 0x10B7F, + // 'Psalter Pahlavi': (char) => char >= 0x10B80 && char <= 0x10BAF, + // 'Old Turkic': (char) => char >= 0x10C00 && char <= 0x10C4F, + // 'Old Hungarian': (char) => char >= 0x10C80 && char <= 0x10CFF, + // 'Hanifi Rohingya': (char) => char >= 0x10D00 && char <= 0x10D3F, + // 'Rumi Numeral Symbols': (char) => char >= 0x10E60 && char <= 0x10E7F, + // 'Old Sogdian': (char) => char >= 0x10F00 && char <= 0x10F2F, + // 'Sogdian': (char) => char >= 0x10F30 && char <= 0x10F6F, + // 'Elymaic': (char) => char >= 0x10FE0 && char <= 0x10FFF, + // 'Brahmi': (char) => char >= 0x11000 && char <= 0x1107F, + // 'Kaithi': (char) => char >= 0x11080 && char <= 0x110CF, + // 'Sora Sompeng': (char) => char >= 0x110D0 && char <= 0x110FF, + // 'Chakma': (char) => char >= 0x11100 && char <= 0x1114F, + // 'Mahajani': (char) => char >= 0x11150 && char <= 0x1117F, + // 'Sharada': (char) => char >= 0x11180 && char <= 0x111DF, + // 'Sinhala Archaic Numbers': (char) => char >= 0x111E0 && char <= 0x111FF, + // 'Khojki': (char) => char >= 0x11200 && char <= 0x1124F, + // 'Multani': (char) => char >= 0x11280 && char <= 0x112AF, + // 'Khudawadi': (char) => char >= 0x112B0 && char <= 0x112FF, + // 'Grantha': (char) => char >= 0x11300 && char <= 0x1137F, + // 'Newa': (char) => char >= 0x11400 && char <= 0x1147F, + // 'Tirhuta': (char) => char >= 0x11480 && char <= 0x114DF, + // 'Siddham': (char) => char >= 0x11580 && char <= 0x115FF, + // 'Modi': (char) => char >= 0x11600 && char <= 0x1165F, + // 'Mongolian Supplement': (char) => char >= 0x11660 && char <= 0x1167F, + // 'Takri': (char) => char >= 0x11680 && char <= 0x116CF, + // 'Ahom': (char) => char >= 0x11700 && char <= 0x1173F, + // 'Dogra': (char) => char >= 0x11800 && char <= 0x1184F, + // 'Warang Citi': (char) => char >= 0x118A0 && char <= 0x118FF, + // 'Nandinagari': (char) => char >= 0x119A0 && char <= 0x119FF, + // 'Zanabazar Square': (char) => char >= 0x11A00 && char <= 0x11A4F, + // 'Soyombo': (char) => char >= 0x11A50 && char <= 0x11AAF, + // 'Pau Cin Hau': (char) => char >= 0x11AC0 && char <= 0x11AFF, + // 'Bhaiksuki': (char) => char >= 0x11C00 && char <= 0x11C6F, + // 'Marchen': (char) => char >= 0x11C70 && char <= 0x11CBF, + // 'Masaram Gondi': (char) => char >= 0x11D00 && char <= 0x11D5F, + // 'Gunjala Gondi': (char) => char >= 0x11D60 && char <= 0x11DAF, + // 'Makasar': (char) => char >= 0x11EE0 && char <= 0x11EFF, + // 'Tamil Supplement': (char) => char >= 0x11FC0 && char <= 0x11FFF, + // 'Cuneiform': (char) => char >= 0x12000 && char <= 0x123FF, + // 'Cuneiform Numbers and Punctuation': (char) => char >= 0x12400 && char <= 0x1247F, + // 'Early Dynastic Cuneiform': (char) => char >= 0x12480 && char <= 0x1254F, + // 'Egyptian Hieroglyphs': (char) => char >= 0x13000 && char <= 0x1342F, + // 'Egyptian Hieroglyph Format Controls': (char) => char >= 0x13430 && char <= 0x1343F, + // 'Anatolian Hieroglyphs': (char) => char >= 0x14400 && char <= 0x1467F, + // 'Bamum Supplement': (char) => char >= 0x16800 && char <= 0x16A3F, + // 'Mro': (char) => char >= 0x16A40 && char <= 0x16A6F, + // 'Bassa Vah': (char) => char >= 0x16AD0 && char <= 0x16AFF, + // 'Pahawh Hmong': (char) => char >= 0x16B00 && char <= 0x16B8F, + // 'Medefaidrin': (char) => char >= 0x16E40 && char <= 0x16E9F, + // 'Miao': (char) => char >= 0x16F00 && char <= 0x16F9F, + // 'Ideographic Symbols and Punctuation': (char) => char >= 0x16FE0 && char <= 0x16FFF, + // 'Tangut': (char) => char >= 0x17000 && char <= 0x187FF, + // 'Tangut Components': (char) => char >= 0x18800 && char <= 0x18AFF, + // 'Kana Supplement': (char) => char >= 0x1B000 && char <= 0x1B0FF, + // 'Kana Extended-A': (char) => char >= 0x1B100 && char <= 0x1B12F, + // 'Small Kana Extension': (char) => char >= 0x1B130 && char <= 0x1B16F, + // 'Nushu': (char) => char >= 0x1B170 && char <= 0x1B2FF, + // 'Duployan': (char) => char >= 0x1BC00 && char <= 0x1BC9F, + // 'Shorthand Format Controls': (char) => char >= 0x1BCA0 && char <= 0x1BCAF, + // 'Byzantine Musical Symbols': (char) => char >= 0x1D000 && char <= 0x1D0FF, + // 'Musical Symbols': (char) => char >= 0x1D100 && char <= 0x1D1FF, + // 'Ancient Greek Musical Notation': (char) => char >= 0x1D200 && char <= 0x1D24F, + // 'Mayan Numerals': (char) => char >= 0x1D2E0 && char <= 0x1D2FF, + // 'Tai Xuan Jing Symbols': (char) => char >= 0x1D300 && char <= 0x1D35F, + // 'Counting Rod Numerals': (char) => char >= 0x1D360 && char <= 0x1D37F, + // 'Mathematical Alphanumeric Symbols': (char) => char >= 0x1D400 && char <= 0x1D7FF, + // 'Sutton SignWriting': (char) => char >= 0x1D800 && char <= 0x1DAAF, + // 'Glagolitic Supplement': (char) => char >= 0x1E000 && char <= 0x1E02F, + // 'Nyiakeng Puachue Hmong': (char) => char >= 0x1E100 && char <= 0x1E14F, + // 'Wancho': (char) => char >= 0x1E2C0 && char <= 0x1E2FF, + // 'Mende Kikakui': (char) => char >= 0x1E800 && char <= 0x1E8DF, + // 'Adlam': (char) => char >= 0x1E900 && char <= 0x1E95F, + // 'Indic Siyaq Numbers': (char) => char >= 0x1EC70 && char <= 0x1ECBF, + // 'Ottoman Siyaq Numbers': (char) => char >= 0x1ED00 && char <= 0x1ED4F, + // 'Arabic Mathematical Alphabetic Symbols': (char) => char >= 0x1EE00 && char <= 0x1EEFF, + // 'Mahjong Tiles': (char) => char >= 0x1F000 && char <= 0x1F02F, + // 'Domino Tiles': (char) => char >= 0x1F030 && char <= 0x1F09F, + // 'Playing Cards': (char) => char >= 0x1F0A0 && char <= 0x1F0FF, + // 'Enclosed Alphanumeric Supplement': (char) => char >= 0x1F100 && char <= 0x1F1FF, + // 'Enclosed Ideographic Supplement': (char) => char >= 0x1F200 && char <= 0x1F2FF, + // 'Miscellaneous Symbols and Pictographs': (char) => char >= 0x1F300 && char <= 0x1F5FF, + // 'Emoticons': (char) => char >= 0x1F600 && char <= 0x1F64F, + // 'Ornamental Dingbats': (char) => char >= 0x1F650 && char <= 0x1F67F, + // 'Transport and Map Symbols': (char) => char >= 0x1F680 && char <= 0x1F6FF, + // 'Alchemical Symbols': (char) => char >= 0x1F700 && char <= 0x1F77F, + // 'Geometric Shapes Extended': (char) => char >= 0x1F780 && char <= 0x1F7FF, + // 'Supplemental Arrows-C': (char) => char >= 0x1F800 && char <= 0x1F8FF, + // 'Supplemental Symbols and Pictographs': (char) => char >= 0x1F900 && char <= 0x1F9FF, + // 'Chess Symbols': (char) => char >= 0x1FA00 && char <= 0x1FA6F, + // 'Symbols and Pictographs Extended-A': (char) => char >= 0x1FA70 && char <= 0x1FAFF, + // 'CJK Unified Ideographs Extension B': (char) => char >= 0x20000 && char <= 0x2A6DF, + // 'CJK Unified Ideographs Extension C': (char) => char >= 0x2A700 && char <= 0x2B73F, + // 'CJK Unified Ideographs Extension D': (char) => char >= 0x2B740 && char <= 0x2B81F, + // 'CJK Unified Ideographs Extension E': (char) => char >= 0x2B820 && char <= 0x2CEAF, + // 'CJK Unified Ideographs Extension F': (char) => char >= 0x2CEB0 && char <= 0x2EBEF, + // 'CJK Compatibility Ideographs Supplement': (char) => char >= 0x2F800 && char <= 0x2FA1F, + // 'Tags': (char) => char >= 0xE0000 && char <= 0xE007F, + // 'Variation Selectors Supplement': (char) => char >= 0xE0100 && char <= 0xE01EF, + // 'Supplementary Private Use Area-A': (char) => char >= 0xF0000 && char <= 0xFFFFF, + // 'Supplementary Private Use Area-B': (char) => char >= 0x100000 && char <= 0x10FFFF, +}; + +export default unicodeBlockLookup; diff --git a/node_modules/mapbox-gl/src/util/mapbox.js b/node_modules/mapbox-gl/src/util/mapbox.js new file mode 100644 index 0000000000000000000000000000000000000000..665ac7b9690b5971e82eddf566b041dccc33c483 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/mapbox.js @@ -0,0 +1,490 @@ +// @flow + +/***** START WARNING - IF YOU USE THIS CODE WITH MAPBOX MAPPING APIS, REMOVAL OR +* MODIFICATION OF THE FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ****** +* The following code is used to access Mapbox's Mapping APIs. Removal or modification +* of this code when used with Mapbox's Mapping APIs can result in higher fees and/or +* termination of your account with Mapbox. +* +* Under the Mapbox Terms of Service, you may not use this code to access Mapbox +* Mapping APIs other than through Mapbox SDKs. +* +* The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps +* and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/ +******************************************************************************/ + +import config from './config'; + +import browser from './browser'; +import window from './window'; +import webpSupported from './webp_supported'; +import {createSkuToken, SKU_ID} from './sku_token'; +import {version as sdkVersion} from '../../package.json'; +import {uuid, validateUuid, storageAvailable, b64DecodeUnicode, b64EncodeUnicode, warnOnce, extend} from './util'; +import {postData, ResourceType} from './ajax'; + +import type {RequestParameters} from './ajax'; +import type {Cancelable} from '../types/cancelable'; +import type {TileJSON} from '../types/tilejson'; + +type ResourceTypeEnum = $Keys; +export type RequestTransformFunction = (url: string, resourceType?: ResourceTypeEnum) => RequestParameters; + +type UrlObject = {| + protocol: string, + authority: string, + path: string, + params: Array +|}; + +export class RequestManager { + _skuToken: string; + _skuTokenExpiresAt: number; + _transformRequestFn: ?RequestTransformFunction; + _customAccessToken: ?string; + + constructor(transformRequestFn?: RequestTransformFunction, customAccessToken?: string) { + this._transformRequestFn = transformRequestFn; + this._customAccessToken = customAccessToken; + this._createSkuToken(); + } + + _createSkuToken() { + const skuToken = createSkuToken(); + this._skuToken = skuToken.token; + this._skuTokenExpiresAt = skuToken.tokenExpiresAt; + } + + _isSkuTokenExpired(): boolean { + return Date.now() > this._skuTokenExpiresAt; + } + + transformRequest(url: string, type: ResourceTypeEnum) { + if (this._transformRequestFn) { + return this._transformRequestFn(url, type) || {url}; + } + + return {url}; + } + + normalizeStyleURL(url: string, accessToken?: string): string { + if (!isMapboxURL(url)) return url; + const urlObject = parseUrl(url); + urlObject.path = `/styles/v1${urlObject.path}`; + return this._makeAPIURL(urlObject, this._customAccessToken || accessToken); + } + + normalizeGlyphsURL(url: string, accessToken?: string): string { + if (!isMapboxURL(url)) return url; + const urlObject = parseUrl(url); + urlObject.path = `/fonts/v1${urlObject.path}`; + return this._makeAPIURL(urlObject, this._customAccessToken || accessToken); + } + + normalizeSourceURL(url: string, accessToken?: string): string { + if (!isMapboxURL(url)) return url; + const urlObject = parseUrl(url); + urlObject.path = `/v4/${urlObject.authority}.json`; + // TileJSON requests need a secure flag appended to their URLs so + // that the server knows to send SSL-ified resource references. + urlObject.params.push('secure'); + return this._makeAPIURL(urlObject, this._customAccessToken || accessToken); + } + + normalizeSpriteURL(url: string, format: string, extension: string, accessToken?: string): string { + const urlObject = parseUrl(url); + if (!isMapboxURL(url)) { + urlObject.path += `${format}${extension}`; + return formatUrl(urlObject); + } + urlObject.path = `/styles/v1${urlObject.path}/sprite${format}${extension}`; + return this._makeAPIURL(urlObject, this._customAccessToken || accessToken); + } + + normalizeTileURL(tileURL: string, tileSize?: ?number): string { + if (this._isSkuTokenExpired()) { + this._createSkuToken(); + } + + if (tileURL && !isMapboxURL(tileURL)) return tileURL; + + const urlObject = parseUrl(tileURL); + const imageExtensionRe = /(\.(png|jpg)\d*)(?=$)/; + const tileURLAPIPrefixRe = /^.+\/v4\//; + + // The v4 mapbox tile API supports 512x512 image tiles only when @2x + // is appended to the tile URL. If `tileSize: 512` is specified for + // a Mapbox raster source force the @2x suffix even if a non hidpi device. + const suffix = browser.devicePixelRatio >= 2 || tileSize === 512 ? '@2x' : ''; + const extension = webpSupported.supported ? '.webp' : '$1'; + urlObject.path = urlObject.path.replace(imageExtensionRe, `${suffix}${extension}`); + urlObject.path = urlObject.path.replace(tileURLAPIPrefixRe, '/'); + urlObject.path = `/v4${urlObject.path}`; + + const accessToken = this._customAccessToken || getAccessToken(urlObject.params) || config.ACCESS_TOKEN; + if (config.REQUIRE_ACCESS_TOKEN && accessToken && this._skuToken) { + urlObject.params.push(`sku=${this._skuToken}`); + } + + return this._makeAPIURL(urlObject, accessToken); + } + + canonicalizeTileURL(url: string, removeAccessToken: boolean) { + const version = "/v4/"; + // matches any file extension specified by a dot and one or more alphanumeric characters + const extensionRe = /\.[\w]+$/; + + const urlObject = parseUrl(url); + // Make sure that we are dealing with a valid Mapbox tile URL. + // Has to begin with /v4/, with a valid filename + extension + if (!urlObject.path.match(/(^\/v4\/)/) || !urlObject.path.match(extensionRe)) { + // Not a proper Mapbox tile URL. + return url; + } + // Reassemble the canonical URL from the parts we've parsed before. + let result = "mapbox://tiles/"; + result += urlObject.path.replace(version, ''); + + // Append the query string, minus the access token parameter. + let params = urlObject.params; + if (removeAccessToken) { + params = params.filter(p => !p.match(/^access_token=/)); + } + if (params.length) result += `?${params.join('&')}`; + return result; + } + + canonicalizeTileset(tileJSON: TileJSON, sourceURL?: string) { + const removeAccessToken = sourceURL ? isMapboxURL(sourceURL) : false; + const canonical = []; + for (const url of tileJSON.tiles || []) { + if (isMapboxHTTPURL(url)) { + canonical.push(this.canonicalizeTileURL(url, removeAccessToken)); + } else { + canonical.push(url); + } + } + return canonical; + } + + _makeAPIURL(urlObject: UrlObject, accessToken: string | null | void): string { + const help = 'See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes'; + const apiUrlObject = parseUrl(config.API_URL); + urlObject.protocol = apiUrlObject.protocol; + urlObject.authority = apiUrlObject.authority; + + if (urlObject.protocol === 'http') { + const i = urlObject.params.indexOf('secure'); + if (i >= 0) urlObject.params.splice(i, 1); + } + + if (apiUrlObject.path !== '/') { + urlObject.path = `${apiUrlObject.path}${urlObject.path}`; + } + + if (!config.REQUIRE_ACCESS_TOKEN) return formatUrl(urlObject); + + accessToken = accessToken || config.ACCESS_TOKEN; + if (!accessToken) + throw new Error(`An API access token is required to use Mapbox GL. ${help}`); + if (accessToken[0] === 's') + throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${help}`); + + urlObject.params = urlObject.params.filter((d) => d.indexOf('access_token') === -1); + urlObject.params.push(`access_token=${accessToken}`); + return formatUrl(urlObject); + } +} + +function isMapboxURL(url: string) { + return url.indexOf('mapbox:') === 0; +} + +const mapboxHTTPURLRe = /^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/|\?|$)/i; +function isMapboxHTTPURL(url: string): boolean { + return mapboxHTTPURLRe.test(url); +} + +function hasCacheDefeatingSku(url: string) { + return url.indexOf('sku=') > 0 && isMapboxHTTPURL(url); +} + +function getAccessToken(params: Array): string | null { + for (const param of params) { + const match = param.match(/^access_token=(.*)$/); + if (match) { + return match[1]; + } + } + return null; +} + +const urlRe = /^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/; + +function parseUrl(url: string): UrlObject { + const parts = url.match(urlRe); + if (!parts) { + throw new Error('Unable to parse URL object'); + } + return { + protocol: parts[1], + authority: parts[2], + path: parts[3] || '/', + params: parts[4] ? parts[4].split('&') : [] + }; +} + +function formatUrl(obj: UrlObject): string { + const params = obj.params.length ? `?${obj.params.join('&')}` : ''; + return `${obj.protocol}://${obj.authority}${obj.path}${params}`; +} + +export {isMapboxURL, isMapboxHTTPURL, hasCacheDefeatingSku}; + +const telemEventKey = 'mapbox.eventData'; + +function parseAccessToken(accessToken: ?string) { + if (!accessToken) { + return null; + } + + const parts = accessToken.split('.'); + if (!parts || parts.length !== 3) { + return null; + } + + try { + const jsonData = JSON.parse(b64DecodeUnicode(parts[1])); + return jsonData; + } catch (e) { + return null; + } +} + +type TelemetryEventType = 'appUserTurnstile' | 'map.load'; + +class TelemetryEvent { + eventData: any; + anonId: ?string; + queue: Array; + type: TelemetryEventType; + pendingRequest: ?Cancelable; + _customAccessToken: ?string; + + constructor(type: TelemetryEventType) { + this.type = type; + this.anonId = null; + this.eventData = {}; + this.queue = []; + this.pendingRequest = null; + } + + getStorageKey(domain: ?string) { + const tokenData = parseAccessToken(config.ACCESS_TOKEN); + let u = ''; + if (tokenData && tokenData['u']) { + u = b64EncodeUnicode(tokenData['u']); + } else { + u = config.ACCESS_TOKEN || ''; + } + return domain ? + `${telemEventKey}.${domain}:${u}` : + `${telemEventKey}:${u}`; + } + + fetchEventData() { + const isLocalStorageAvailable = storageAvailable('localStorage'); + const storageKey = this.getStorageKey(); + const uuidKey = this.getStorageKey('uuid'); + + if (isLocalStorageAvailable) { + //Retrieve cached data + try { + const data = window.localStorage.getItem(storageKey); + if (data) { + this.eventData = JSON.parse(data); + } + + const uuid = window.localStorage.getItem(uuidKey); + if (uuid) this.anonId = uuid; + } catch (e) { + warnOnce('Unable to read from LocalStorage'); + } + } + } + + saveEventData() { + const isLocalStorageAvailable = storageAvailable('localStorage'); + const storageKey = this.getStorageKey(); + const uuidKey = this.getStorageKey('uuid'); + if (isLocalStorageAvailable) { + try { + window.localStorage.setItem(uuidKey, this.anonId); + if (Object.keys(this.eventData).length >= 1) { + window.localStorage.setItem(storageKey, JSON.stringify(this.eventData)); + } + } catch (e) { + warnOnce('Unable to write to LocalStorage'); + } + } + + } + + processRequests(_: ?string) {} + + /* + * If any event data should be persisted after the POST request, the callback should modify eventData` + * to the values that should be saved. For this reason, the callback should be invoked prior to the call + * to TelemetryEvent#saveData + */ + postEvent(timestamp: number, additionalPayload: {[_: string]: any}, callback: (err: ?Error) => void, customAccessToken?: ?string) { + if (!config.EVENTS_URL) return; + const eventsUrlObject: UrlObject = parseUrl(config.EVENTS_URL); + eventsUrlObject.params.push(`access_token=${customAccessToken || config.ACCESS_TOKEN || ''}`); + + const payload: Object = { + event: this.type, + created: new Date(timestamp).toISOString(), + sdkIdentifier: 'mapbox-gl-js', + sdkVersion, + skuId: SKU_ID, + userId: this.anonId + }; + + const finalPayload = additionalPayload ? extend(payload, additionalPayload) : payload; + const request: RequestParameters = { + url: formatUrl(eventsUrlObject), + headers: { + 'Content-Type': 'text/plain' //Skip the pre-flight OPTIONS request + }, + body: JSON.stringify([finalPayload]) + }; + + this.pendingRequest = postData(request, (error) => { + this.pendingRequest = null; + callback(error); + this.saveEventData(); + this.processRequests(customAccessToken); + }); + } + + queueRequest(event: number | {id: number, timestamp: number}, customAccessToken?: ?string) { + this.queue.push(event); + this.processRequests(customAccessToken); + } +} + +export class MapLoadEvent extends TelemetryEvent { + +success: {[_: number]: boolean}; + skuToken: string; + + constructor() { + super('map.load'); + this.success = {}; + this.skuToken = ''; + } + + postMapLoadEvent(tileUrls: Array, mapId: number, skuToken: string, customAccessToken: string) { + this.skuToken = skuToken; + + const accessTokenIsSet = !!(customAccessToken || config.ACCESS_TOKEN); + const usesMapboxTiles = Array.isArray(tileUrls) && tileUrls.some(url => isMapboxURL(url) || isMapboxHTTPURL(url)); + + // Enabled only when Mapbox Access Token is set and a source uses mapbox tiles. + if (config.EVENTS_URL && accessTokenIsSet && usesMapboxTiles) { + this.queueRequest({id: mapId, timestamp: Date.now()}, customAccessToken); + } + } + + processRequests(customAccessToken?: ?string) { + if (this.pendingRequest || this.queue.length === 0) return; + const {id, timestamp} = this.queue.shift(); + + // Only one load event should fire per map + if (id && this.success[id]) return; + + if (!this.anonId) { + this.fetchEventData(); + } + + if (!validateUuid(this.anonId)) { + this.anonId = uuid(); + } + + this.postEvent(timestamp, {skuToken: this.skuToken}, (err) => { + if (!err) { + if (id) this.success[id] = true; + } + }, customAccessToken); + } +} + +export class TurnstileEvent extends TelemetryEvent { + constructor(customAccessToken?: ?string) { + super('appUserTurnstile'); + this._customAccessToken = customAccessToken; + } + + postTurnstileEvent(tileUrls: Array, customAccessToken?: ?string) { + //Enabled only when Mapbox Access Token is set and a source uses + // mapbox tiles. + if (config.EVENTS_URL && + config.ACCESS_TOKEN && + Array.isArray(tileUrls) && + tileUrls.some(url => isMapboxURL(url) || isMapboxHTTPURL(url))) { + this.queueRequest(Date.now(), customAccessToken); + } + } + + processRequests(customAccessToken?: ?string) { + if (this.pendingRequest || this.queue.length === 0) { + return; + } + + if (!this.anonId || !this.eventData.lastSuccess || !this.eventData.tokenU) { + //Retrieve cached data + this.fetchEventData(); + } + + const tokenData = parseAccessToken(config.ACCESS_TOKEN); + const tokenU = tokenData ? tokenData['u'] : config.ACCESS_TOKEN; + //Reset event data cache if the access token owner changed. + let dueForEvent = tokenU !== this.eventData.tokenU; + + if (!validateUuid(this.anonId)) { + this.anonId = uuid(); + dueForEvent = true; + } + + const nextUpdate = this.queue.shift(); + // Record turnstile event once per calendar day. + if (this.eventData.lastSuccess) { + const lastUpdate = new Date(this.eventData.lastSuccess); + const nextDate = new Date(nextUpdate); + const daysElapsed = (nextUpdate - this.eventData.lastSuccess) / (24 * 60 * 60 * 1000); + dueForEvent = dueForEvent || daysElapsed >= 1 || daysElapsed < -1 || lastUpdate.getDate() !== nextDate.getDate(); + } else { + dueForEvent = true; + } + + if (!dueForEvent) { + return this.processRequests(); + } + + this.postEvent(nextUpdate, {"enabled.telemetry": false}, (err) => { + if (!err) { + this.eventData.lastSuccess = nextUpdate; + this.eventData.tokenU = tokenU; + } + }, customAccessToken); + } +} + +const turnstileEvent_ = new TurnstileEvent(); +export const postTurnstileEvent = turnstileEvent_.postTurnstileEvent.bind(turnstileEvent_); + +const mapLoadEvent_ = new MapLoadEvent(); +export const postMapLoadEvent = mapLoadEvent_.postMapLoadEvent.bind(mapLoadEvent_); + +/***** END WARNING - REMOVAL OR MODIFICATION OF THE +PRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******/ diff --git a/node_modules/mapbox-gl/src/util/offscreen_canvas_supported.js b/node_modules/mapbox-gl/src/util/offscreen_canvas_supported.js new file mode 100644 index 0000000000000000000000000000000000000000..4ec6b188d05a679e471197753df59ebe0217c7ef --- /dev/null +++ b/node_modules/mapbox-gl/src/util/offscreen_canvas_supported.js @@ -0,0 +1,14 @@ +// @flow +import window from './window'; + +let supportsOffscreenCanvas: ?boolean; + +export default function offscreenCanvasSupported(): boolean { + if (supportsOffscreenCanvas == null) { + supportsOffscreenCanvas = window.OffscreenCanvas && + new window.OffscreenCanvas(1, 1).getContext('2d') && + typeof window.createImageBitmap === 'function'; + } + + return supportsOffscreenCanvas; +} diff --git a/node_modules/mapbox-gl/src/util/performance.js b/node_modules/mapbox-gl/src/util/performance.js new file mode 100644 index 0000000000000000000000000000000000000000..0b6a26c377b1bbceef7909a1f9af0792f5657403 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/performance.js @@ -0,0 +1,112 @@ +// @flow + +import window from '../util/window'; +import type {RequestParameters} from '../util/ajax'; + +const performance = window.performance; + +export type PerformanceMetrics = { + loadTime: number, + fullLoadTime: number, + fps: number, + percentDroppedFrames: number +} + +export const PerformanceMarkers = { + create: 'create', + load: 'load', + fullLoad: 'fullLoad' +}; + +let lastFrameTime = null; +let frameTimes = []; + +const minFramerateTarget = 30; +const frameTimeTarget = 1000 / minFramerateTarget; + +export const PerformanceUtils = { + mark(marker: $Keys) { + performance.mark(marker); + }, + frame(timestamp: number) { + const currTimestamp = timestamp; + if (lastFrameTime != null) { + const frameTime = currTimestamp - lastFrameTime; + frameTimes.push(frameTime); + } + lastFrameTime = currTimestamp; + }, + clearMetrics() { + lastFrameTime = null; + frameTimes = []; + performance.clearMeasures('loadTime'); + performance.clearMeasures('fullLoadTime'); + + for (const marker in PerformanceMarkers) { + performance.clearMarks(PerformanceMarkers[marker]); + } + }, + getPerformanceMetrics(): PerformanceMetrics { + const loadTime = performance.measure('loadTime', PerformanceMarkers.create, PerformanceMarkers.load).duration; + const fullLoadTime = performance.measure('fullLoadTime', PerformanceMarkers.create, PerformanceMarkers.fullLoad).duration; + const totalFrames = frameTimes.length; + + const avgFrameTime = frameTimes.reduce((prev, curr) => prev + curr, 0) / totalFrames / 1000; + const fps = 1 / avgFrameTime; + + // count frames that missed our framerate target + const droppedFrames = frameTimes + .filter((frameTime) => frameTime > frameTimeTarget) + .reduce((acc, curr) => { + return acc + (curr - frameTimeTarget) / frameTimeTarget; + }, 0); + const percentDroppedFrames = (droppedFrames / (totalFrames + droppedFrames)) * 100; + + return { + loadTime, + fullLoadTime, + fps, + percentDroppedFrames + }; + } +}; + +/** + * Safe wrapper for the performance resource timing API in web workers with graceful degradation + * + * @param {RequestParameters} request + * @private + */ +export class RequestPerformance { + _marks: {start: string, end: string, measure: string}; + + constructor (request: RequestParameters) { + this._marks = { + start: [request.url, 'start'].join('#'), + end: [request.url, 'end'].join('#'), + measure: request.url.toString() + }; + + performance.mark(this._marks.start); + } + + finish() { + performance.mark(this._marks.end); + let resourceTimingData = performance.getEntriesByName(this._marks.measure); + + // fallback if web worker implementation of perf.getEntriesByName returns empty + if (resourceTimingData.length === 0) { + performance.measure(this._marks.measure, this._marks.start, this._marks.end); + resourceTimingData = performance.getEntriesByName(this._marks.measure); + + // cleanup + performance.clearMarks(this._marks.start); + performance.clearMarks(this._marks.end); + performance.clearMeasures(this._marks.measure); + } + + return resourceTimingData; + } +} + +export default performance; diff --git a/node_modules/mapbox-gl/src/util/primitives.js b/node_modules/mapbox-gl/src/util/primitives.js new file mode 100644 index 0000000000000000000000000000000000000000..b1cd69e6fe345e3df5154be3e6cb21784ffa28ce --- /dev/null +++ b/node_modules/mapbox-gl/src/util/primitives.js @@ -0,0 +1,145 @@ +// @flow + +import {vec3, vec4} from 'gl-matrix'; +import assert from 'assert'; + +class Frustum { + points: Array>; + planes: Array>; + + constructor(points_: Array>, planes_: Array>) { + this.points = points_; + this.planes = planes_; + } + + static fromInvProjectionMatrix(invProj: Float64Array, worldSize: number, zoom: number): Frustum { + const clipSpaceCorners = [ + [-1, 1, -1, 1], + [ 1, 1, -1, 1], + [ 1, -1, -1, 1], + [-1, -1, -1, 1], + [-1, 1, 1, 1], + [ 1, 1, 1, 1], + [ 1, -1, 1, 1], + [-1, -1, 1, 1] + ]; + + const scale = Math.pow(2, zoom); + + // Transform frustum corner points from clip space to tile space + const frustumCoords = clipSpaceCorners + .map(v => vec4.transformMat4([], v, invProj)) + .map(v => vec4.scale([], v, 1.0 / v[3] / worldSize * scale)); + + const frustumPlanePointIndices = [ + [0, 1, 2], // near + [6, 5, 4], // far + [0, 3, 7], // left + [2, 1, 5], // right + [3, 2, 6], // bottom + [0, 4, 5] // top + ]; + + const frustumPlanes = frustumPlanePointIndices.map((p: Array) => { + const a = vec3.sub([], frustumCoords[p[0]], frustumCoords[p[1]]); + const b = vec3.sub([], frustumCoords[p[2]], frustumCoords[p[1]]); + const n = vec3.normalize([], vec3.cross([], a, b)); + const d = -vec3.dot(n, frustumCoords[p[1]]); + return n.concat(d); + }); + + return new Frustum(frustumCoords, frustumPlanes); + } +} + +class Aabb { + min: vec3; + max: vec3; + center: vec3; + + constructor(min_: vec3, max_: vec3) { + this.min = min_; + this.max = max_; + this.center = vec3.scale([], vec3.add([], this.min, this.max), 0.5); + } + + quadrant(index: number): Aabb { + const split = [(index % 2) === 0, index < 2]; + const qMin = vec3.clone(this.min); + const qMax = vec3.clone(this.max); + for (let axis = 0; axis < split.length; axis++) { + qMin[axis] = split[axis] ? this.min[axis] : this.center[axis]; + qMax[axis] = split[axis] ? this.center[axis] : this.max[axis]; + } + // Elevation is always constant, hence quadrant.max.z = this.max.z + qMax[2] = this.max[2]; + return new Aabb(qMin, qMax); + } + + distanceX(point: Array): number { + const pointOnAabb = Math.max(Math.min(this.max[0], point[0]), this.min[0]); + return pointOnAabb - point[0]; + } + + distanceY(point: Array): number { + const pointOnAabb = Math.max(Math.min(this.max[1], point[1]), this.min[1]); + return pointOnAabb - point[1]; + } + + // Performs a frustum-aabb intersection test. Returns 0 if there's no intersection, + // 1 if shapes are intersecting and 2 if the aabb if fully inside the frustum. + intersects(frustum: Frustum): number { + // Execute separating axis test between two convex objects to find intersections + // Each frustum plane together with 3 major axes define the separating axes + // Note: test only 4 points as both min and max points have equal elevation + assert(this.min[2] === 0 && this.max[2] === 0); + + const aabbPoints = [ + [this.min[0], this.min[1], 0.0, 1], + [this.max[0], this.min[1], 0.0, 1], + [this.max[0], this.max[1], 0.0, 1], + [this.min[0], this.max[1], 0.0, 1] + ]; + + let fullyInside = true; + + for (let p = 0; p < frustum.planes.length; p++) { + const plane = frustum.planes[p]; + let pointsInside = 0; + + for (let i = 0; i < aabbPoints.length; i++) { + pointsInside += vec4.dot(plane, aabbPoints[i]) >= 0; + } + + if (pointsInside === 0) + return 0; + + if (pointsInside !== aabbPoints.length) + fullyInside = false; + } + + if (fullyInside) + return 2; + + for (let axis = 0; axis < 3; axis++) { + let projMin = Number.MAX_VALUE; + let projMax = -Number.MAX_VALUE; + + for (let p = 0; p < frustum.points.length; p++) { + const projectedPoint = frustum.points[p][axis] - this.min[axis]; + + projMin = Math.min(projMin, projectedPoint); + projMax = Math.max(projMax, projectedPoint); + } + + if (projMax < 0 || projMin > this.max[axis] - this.min[axis]) + return 0; + } + + return 1; + } +} +export { + Aabb, + Frustum +}; diff --git a/node_modules/mapbox-gl/src/util/resolve_tokens.js b/node_modules/mapbox-gl/src/util/resolve_tokens.js new file mode 100644 index 0000000000000000000000000000000000000000..3ca7c86055b779361a242b53f87dbaa43b60065a --- /dev/null +++ b/node_modules/mapbox-gl/src/util/resolve_tokens.js @@ -0,0 +1,16 @@ +// @flow +export default resolveTokens; + +/** + * Replace tokens in a string template with values in an object + * + * @param properties a key/value relationship between tokens and replacements + * @param text the template string + * @returns the template with tokens replaced + * @private + */ +function resolveTokens(properties: {+[string]: mixed}, text: string): string { + return text.replace(/{([^{}]+)}/g, (match, key: string) => { + return key in properties ? String(properties[key]) : ''; + }); +} diff --git a/node_modules/mapbox-gl/src/util/script_detection.js b/node_modules/mapbox-gl/src/util/script_detection.js new file mode 100644 index 0000000000000000000000000000000000000000..985ae4830012bf15b01f54e2a1974a207042bfc5 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/script_detection.js @@ -0,0 +1,328 @@ +// @flow + +/* eslint-disable new-cap */ + +import isChar from './is_char_in_unicode_block'; + +export function allowsIdeographicBreaking(chars: string) { + for (const char of chars) { + if (!charAllowsIdeographicBreaking(char.charCodeAt(0))) return false; + } + return true; +} + +export function allowsVerticalWritingMode(chars: string) { + for (const char of chars) { + if (charHasUprightVerticalOrientation(char.charCodeAt(0))) return true; + } + return false; +} + +export function allowsLetterSpacing(chars: string) { + for (const char of chars) { + if (!charAllowsLetterSpacing(char.charCodeAt(0))) return false; + } + return true; +} + +export function charAllowsLetterSpacing(char: number) { + if (isChar['Arabic'](char)) return false; + if (isChar['Arabic Supplement'](char)) return false; + if (isChar['Arabic Extended-A'](char)) return false; + if (isChar['Arabic Presentation Forms-A'](char)) return false; + if (isChar['Arabic Presentation Forms-B'](char)) return false; + + return true; +} + +export function charAllowsIdeographicBreaking(char: number) { + // Return early for characters outside all ideographic ranges. + if (char < 0x2E80) return false; + + if (isChar['Bopomofo Extended'](char)) return true; + if (isChar['Bopomofo'](char)) return true; + if (isChar['CJK Compatibility Forms'](char)) return true; + if (isChar['CJK Compatibility Ideographs'](char)) return true; + if (isChar['CJK Compatibility'](char)) return true; + if (isChar['CJK Radicals Supplement'](char)) return true; + if (isChar['CJK Strokes'](char)) return true; + if (isChar['CJK Symbols and Punctuation'](char)) return true; + if (isChar['CJK Unified Ideographs Extension A'](char)) return true; + if (isChar['CJK Unified Ideographs'](char)) return true; + if (isChar['Enclosed CJK Letters and Months'](char)) return true; + if (isChar['Halfwidth and Fullwidth Forms'](char)) return true; + if (isChar['Hiragana'](char)) return true; + if (isChar['Ideographic Description Characters'](char)) return true; + if (isChar['Kangxi Radicals'](char)) return true; + if (isChar['Katakana Phonetic Extensions'](char)) return true; + if (isChar['Katakana'](char)) return true; + if (isChar['Vertical Forms'](char)) return true; + if (isChar['Yi Radicals'](char)) return true; + if (isChar['Yi Syllables'](char)) return true; + + return false; +} + +// The following logic comes from +// . +// Keep it synchronized with +// . +// The data file denotes with “U” or “Tu” any codepoint that may be drawn +// upright in vertical text but does not distinguish between upright and +// “neutral” characters. + +// Blocks in the Unicode supplementary planes are excluded from this module due +// to . + +/** + * Returns true if the given Unicode codepoint identifies a character with + * upright orientation. + * + * A character has upright orientation if it is drawn upright (unrotated) + * whether the line is oriented horizontally or vertically, even if both + * adjacent characters can be rotated. For example, a Chinese character is + * always drawn upright. An uprightly oriented character causes an adjacent + * “neutral” character to be drawn upright as well. + * @private + */ +export function charHasUprightVerticalOrientation(char: number) { + if (char === 0x02EA /* modifier letter yin departing tone mark */ || + char === 0x02EB /* modifier letter yang departing tone mark */) { + return true; + } + + // Return early for characters outside all ranges whose characters remain + // upright in vertical writing mode. + if (char < 0x1100) return false; + + if (isChar['Bopomofo Extended'](char)) return true; + if (isChar['Bopomofo'](char)) return true; + if (isChar['CJK Compatibility Forms'](char)) { + if (!((char >= 0xFE49 /* dashed overline */ && char <= 0xFE4F) /* wavy low line */)) { + return true; + } + } + if (isChar['CJK Compatibility Ideographs'](char)) return true; + if (isChar['CJK Compatibility'](char)) return true; + if (isChar['CJK Radicals Supplement'](char)) return true; + if (isChar['CJK Strokes'](char)) return true; + if (isChar['CJK Symbols and Punctuation'](char)) { + if (!((char >= 0x3008 /* left angle bracket */ && char <= 0x3011) /* right black lenticular bracket */) && + !((char >= 0x3014 /* left tortoise shell bracket */ && char <= 0x301F) /* low double prime quotation mark */) && + char !== 0x3030 /* wavy dash */) { + return true; + } + } + if (isChar['CJK Unified Ideographs Extension A'](char)) return true; + if (isChar['CJK Unified Ideographs'](char)) return true; + if (isChar['Enclosed CJK Letters and Months'](char)) return true; + if (isChar['Hangul Compatibility Jamo'](char)) return true; + if (isChar['Hangul Jamo Extended-A'](char)) return true; + if (isChar['Hangul Jamo Extended-B'](char)) return true; + if (isChar['Hangul Jamo'](char)) return true; + if (isChar['Hangul Syllables'](char)) return true; + if (isChar['Hiragana'](char)) return true; + if (isChar['Ideographic Description Characters'](char)) return true; + if (isChar['Kanbun'](char)) return true; + if (isChar['Kangxi Radicals'](char)) return true; + if (isChar['Katakana Phonetic Extensions'](char)) return true; + if (isChar['Katakana'](char)) { + if (char !== 0x30FC /* katakana-hiragana prolonged sound mark */) { + return true; + } + } + if (isChar['Halfwidth and Fullwidth Forms'](char)) { + if (char !== 0xFF08 /* fullwidth left parenthesis */ && + char !== 0xFF09 /* fullwidth right parenthesis */ && + char !== 0xFF0D /* fullwidth hyphen-minus */ && + !((char >= 0xFF1A /* fullwidth colon */ && char <= 0xFF1E) /* fullwidth greater-than sign */) && + char !== 0xFF3B /* fullwidth left square bracket */ && + char !== 0xFF3D /* fullwidth right square bracket */ && + char !== 0xFF3F /* fullwidth low line */ && + !(char >= 0xFF5B /* fullwidth left curly bracket */ && char <= 0xFFDF) && + char !== 0xFFE3 /* fullwidth macron */ && + !(char >= 0xFFE8 /* halfwidth forms light vertical */ && char <= 0xFFEF)) { + return true; + } + } + if (isChar['Small Form Variants'](char)) { + if (!((char >= 0xFE58 /* small em dash */ && char <= 0xFE5E) /* small right tortoise shell bracket */) && + !((char >= 0xFE63 /* small hyphen-minus */ && char <= 0xFE66) /* small equals sign */)) { + return true; + } + } + if (isChar['Unified Canadian Aboriginal Syllabics'](char)) return true; + if (isChar['Unified Canadian Aboriginal Syllabics Extended'](char)) return true; + if (isChar['Vertical Forms'](char)) return true; + if (isChar['Yijing Hexagram Symbols'](char)) return true; + if (isChar['Yi Syllables'](char)) return true; + if (isChar['Yi Radicals'](char)) return true; + + return false; +} + +/** + * Returns true if the given Unicode codepoint identifies a character with + * neutral orientation. + * + * A character has neutral orientation if it may be drawn rotated or unrotated + * when the line is oriented vertically, depending on the orientation of the + * adjacent characters. For example, along a verticlly oriented line, the vulgar + * fraction ½ is drawn upright among Chinese characters but rotated among Latin + * letters. A neutrally oriented character does not influence whether an + * adjacent character is drawn upright or rotated. + * @private + */ +export function charHasNeutralVerticalOrientation(char: number) { + if (isChar['Latin-1 Supplement'](char)) { + if (char === 0x00A7 /* section sign */ || + char === 0x00A9 /* copyright sign */ || + char === 0x00AE /* registered sign */ || + char === 0x00B1 /* plus-minus sign */ || + char === 0x00BC /* vulgar fraction one quarter */ || + char === 0x00BD /* vulgar fraction one half */ || + char === 0x00BE /* vulgar fraction three quarters */ || + char === 0x00D7 /* multiplication sign */ || + char === 0x00F7 /* division sign */) { + return true; + } + } + if (isChar['General Punctuation'](char)) { + if (char === 0x2016 /* double vertical line */ || + char === 0x2020 /* dagger */ || + char === 0x2021 /* double dagger */ || + char === 0x2030 /* per mille sign */ || + char === 0x2031 /* per ten thousand sign */ || + char === 0x203B /* reference mark */ || + char === 0x203C /* double exclamation mark */ || + char === 0x2042 /* asterism */ || + char === 0x2047 /* double question mark */ || + char === 0x2048 /* question exclamation mark */ || + char === 0x2049 /* exclamation question mark */ || + char === 0x2051 /* two asterisks aligned vertically */) { + return true; + } + } + if (isChar['Letterlike Symbols'](char)) return true; + if (isChar['Number Forms'](char)) return true; + if (isChar['Miscellaneous Technical'](char)) { + if ((char >= 0x2300 /* diameter sign */ && char <= 0x2307 /* wavy line */) || + (char >= 0x230C /* bottom right crop */ && char <= 0x231F /* bottom right corner */) || + (char >= 0x2324 /* up arrowhead between two horizontal bars */ && char <= 0x2328 /* keyboard */) || + char === 0x232B /* erase to the left */ || + (char >= 0x237D /* shouldered open box */ && char <= 0x239A /* clear screen symbol */) || + (char >= 0x23BE /* dentistry symbol light vertical and top right */ && char <= 0x23CD /* square foot */) || + char === 0x23CF /* eject symbol */ || + (char >= 0x23D1 /* metrical breve */ && char <= 0x23DB /* fuse */) || + (char >= 0x23E2 /* white trapezium */ && char <= 0x23FF)) { + return true; + } + } + if (isChar['Control Pictures'](char) && char !== 0x2423 /* open box */) return true; + if (isChar['Optical Character Recognition'](char)) return true; + if (isChar['Enclosed Alphanumerics'](char)) return true; + if (isChar['Geometric Shapes'](char)) return true; + if (isChar['Miscellaneous Symbols'](char)) { + if (!((char >= 0x261A /* black left pointing index */ && char <= 0x261F) /* white down pointing index */)) { + return true; + } + } + if (isChar['Miscellaneous Symbols and Arrows'](char)) { + if ((char >= 0x2B12 /* square with top half black */ && char <= 0x2B2F /* white vertical ellipse */) || + (char >= 0x2B50 /* white medium star */ && char <= 0x2B59 /* heavy circled saltire */) || + (char >= 0x2BB8 /* upwards white arrow from bar with horizontal bar */ && char <= 0x2BEB)) { + return true; + } + } + if (isChar['CJK Symbols and Punctuation'](char)) return true; + if (isChar['Katakana'](char)) return true; + if (isChar['Private Use Area'](char)) return true; + if (isChar['CJK Compatibility Forms'](char)) return true; + if (isChar['Small Form Variants'](char)) return true; + if (isChar['Halfwidth and Fullwidth Forms'](char)) return true; + + if (char === 0x221E /* infinity */ || + char === 0x2234 /* therefore */ || + char === 0x2235 /* because */ || + (char >= 0x2700 /* black safety scissors */ && char <= 0x2767 /* rotated floral heart bullet */) || + (char >= 0x2776 /* dingbat negative circled digit one */ && char <= 0x2793 /* dingbat negative circled sans-serif number ten */) || + char === 0xFFFC /* object replacement character */ || + char === 0xFFFD /* replacement character */) { + return true; + } + + return false; +} + +/** + * Returns true if the given Unicode codepoint identifies a character with + * rotated orientation. + * + * A character has rotated orientation if it is drawn rotated when the line is + * oriented vertically, even if both adjacent characters are upright. For + * example, a Latin letter is drawn rotated along a vertical line. A rotated + * character causes an adjacent “neutral” character to be drawn rotated as well. + * @private + */ +export function charHasRotatedVerticalOrientation(char: number) { + return !(charHasUprightVerticalOrientation(char) || + charHasNeutralVerticalOrientation(char)); +} + +export function charInComplexShapingScript(char: number) { + return isChar['Arabic'](char) || + isChar['Arabic Supplement'](char) || + isChar['Arabic Extended-A'](char) || + isChar['Arabic Presentation Forms-A'](char) || + isChar['Arabic Presentation Forms-B'](char); +} + +export function charInRTLScript(char: number) { + // Main blocks for Hebrew, Arabic, Thaana and other RTL scripts + return (char >= 0x0590 && char <= 0x08FF) || + isChar['Arabic Presentation Forms-A'](char) || + isChar['Arabic Presentation Forms-B'](char); +} + +export function charInSupportedScript(char: number, canRenderRTL: boolean) { + // This is a rough heuristic: whether we "can render" a script + // actually depends on the properties of the font being used + // and whether differences from the ideal rendering are considered + // semantically significant. + + // Even in Latin script, we "can't render" combinations such as the fi + // ligature, but we don't consider that semantically significant. + if (!canRenderRTL && charInRTLScript(char)) { + return false; + } + if ((char >= 0x0900 && char <= 0x0DFF) || + // Main blocks for Indic scripts and Sinhala + (char >= 0x0F00 && char <= 0x109F) || + // Main blocks for Tibetan and Myanmar + isChar['Khmer'](char)) { + // These blocks cover common scripts that require + // complex text shaping, based on unicode script metadata: + // http://www.unicode.org/repos/cldr/trunk/common/properties/scriptMetadata.txt + // where "Web Rank <= 32" "Shaping Required = YES" + return false; + } + return true; +} + +export function stringContainsRTLText(chars: string): boolean { + for (const char of chars) { + if (charInRTLScript(char.charCodeAt(0))) { + return true; + } + } + return false; +} + +export function isStringInSupportedScript(chars: string, canRenderRTL: boolean) { + for (const char of chars) { + if (!charInSupportedScript(char.charCodeAt(0), canRenderRTL)) { + return false; + } + } + return true; +} diff --git a/node_modules/mapbox-gl/src/util/sku_token.js b/node_modules/mapbox-gl/src/util/sku_token.js new file mode 100644 index 0000000000000000000000000000000000000000..990a1c60c1e4a3a4308735baf90335819f3fb7c2 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/sku_token.js @@ -0,0 +1,42 @@ +// @flow + +/***** START WARNING - IF YOU USE THIS CODE WITH MAPBOX MAPPING APIS, REMOVAL OR +* MODIFICATION OF THE FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ****** +* The following code is used to access Mapbox's Mapping APIs. Removal or modification +* of this code when used with Mapbox's Mapping APIs can result in higher fees and/or +* termination of your account with Mapbox. +* +* Under the Mapbox Terms of Service, you may not use this code to access Mapbox +* Mapping APIs other than through Mapbox SDKs. +* +* The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps +* and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/ +******************************************************************************/ + +type SkuTokenObject = {| + token: string, + tokenExpiresAt: number +|}; + +const SKU_ID = '01'; + +function createSkuToken(): SkuTokenObject { + // SKU_ID and TOKEN_VERSION are specified by an internal schema and should not change + const TOKEN_VERSION = '1'; + const base62chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + // sessionRandomizer is a randomized 10-digit base-62 number + let sessionRandomizer = ''; + for (let i = 0; i < 10; i++) { + sessionRandomizer += base62chars[Math.floor(Math.random() * 62)]; + } + const expiration = 12 * 60 * 60 * 1000; // 12 hours + const token = [TOKEN_VERSION, SKU_ID, sessionRandomizer].join(''); + const tokenExpiresAt = Date.now() + expiration; + + return {token, tokenExpiresAt}; +} + +export {createSkuToken, SKU_ID}; + +/***** END WARNING - REMOVAL OR MODIFICATION OF THE +PRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******/ diff --git a/node_modules/mapbox-gl/src/util/smart_wrap.js b/node_modules/mapbox-gl/src/util/smart_wrap.js new file mode 100644 index 0000000000000000000000000000000000000000..a713d1e2b9dc3536777eed4340ef7220aba47777 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/smart_wrap.js @@ -0,0 +1,55 @@ +// @flow + +import LngLat from '../geo/lng_lat'; + +import type Point from '@mapbox/point-geometry'; +import type Transform from '../geo/transform'; + +/** + * Given a LngLat, prior projected position, and a transform, return a new LngLat shifted + * n × 360° east or west for some n ≥ 0 such that: + * + * * the projected location of the result is on screen, if possible, and secondarily: + * * the difference between the projected location of the result and the prior position + * is minimized. + * + * The object is to preserve perceived object constancy for Popups and Markers as much as + * possible; they should avoid shifting large distances across the screen, even when the + * map center changes by ±360° due to automatic wrapping, and when about to go off screen, + * should wrap just enough to avoid doing so. + * + * @private + */ +export default function(lngLat: LngLat, priorPos: ?Point, transform: Transform): LngLat { + lngLat = new LngLat(lngLat.lng, lngLat.lat); + + // First, try shifting one world in either direction, and see if either is closer to the + // prior position. This preserves object constancy when the map center is auto-wrapped + // during animations. + if (priorPos) { + const left = new LngLat(lngLat.lng - 360, lngLat.lat); + const right = new LngLat(lngLat.lng + 360, lngLat.lat); + const delta = transform.locationPoint(lngLat).distSqr(priorPos); + if (transform.locationPoint(left).distSqr(priorPos) < delta) { + lngLat = left; + } else if (transform.locationPoint(right).distSqr(priorPos) < delta) { + lngLat = right; + } + } + + // Second, wrap toward the center until the new position is on screen, or we can't get + // any closer. + while (Math.abs(lngLat.lng - transform.center.lng) > 180) { + const pos = transform.locationPoint(lngLat); + if (pos.x >= 0 && pos.y >= 0 && pos.x <= transform.width && pos.y <= transform.height) { + break; + } + if (lngLat.lng > transform.center.lng) { + lngLat.lng -= 360; + } else { + lngLat.lng += 360; + } + } + + return lngLat; +} diff --git a/node_modules/mapbox-gl/src/util/struct_array.js b/node_modules/mapbox-gl/src/util/struct_array.js new file mode 100644 index 0000000000000000000000000000000000000000..f033270be4374bd06923d7f8f25885a172e45334 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/struct_array.js @@ -0,0 +1,243 @@ +// @flow + +// Note: all "sizes" are measured in bytes + +import assert from 'assert'; + +import type {Transferable} from '../types/transferable'; + +const viewTypes = { + 'Int8': Int8Array, + 'Uint8': Uint8Array, + 'Int16': Int16Array, + 'Uint16': Uint16Array, + 'Int32': Int32Array, + 'Uint32': Uint32Array, + 'Float32': Float32Array +}; + +export type ViewType = $Keys; + +/** + * @private + */ +class Struct { + _pos1: number; + _pos2: number; + _pos4: number; + _pos8: number; + +_structArray: StructArray; + + // The following properties are defined on the prototype of sub classes. + size: number; + + /** + * @param {StructArray} structArray The StructArray the struct is stored in + * @param {number} index The index of the struct in the StructArray. + * @private + */ + constructor(structArray: StructArray, index: number) { + (this: any)._structArray = structArray; + this._pos1 = index * this.size; + this._pos2 = this._pos1 / 2; + this._pos4 = this._pos1 / 4; + this._pos8 = this._pos1 / 8; + } +} + +const DEFAULT_CAPACITY = 128; +const RESIZE_MULTIPLIER = 5; + +export type StructArrayMember = { + name: string, + type: ViewType, + components: number, + offset: number +}; + +export type StructArrayLayout = { + members: Array, + size: number, + alignment: ?number +} + +export type SerializedStructArray = { + length: number, + arrayBuffer: ArrayBuffer +}; + +/** + * `StructArray` provides an abstraction over `ArrayBuffer` and `TypedArray` + * making it behave like an array of typed structs. + * + * Conceptually, a StructArray is comprised of elements, i.e., instances of its + * associated struct type. Each particular struct type, together with an + * alignment size, determines the memory layout of a StructArray whose elements + * are of that type. Thus, for each such layout that we need, we have + * a corrseponding StructArrayLayout class, inheriting from StructArray and + * implementing `emplaceBack()` and `_refreshViews()`. + * + * In some cases, where we need to access particular elements of a StructArray, + * we implement a more specific subclass that inherits from one of the + * StructArrayLayouts and adds a `get(i): T` accessor that returns a structured + * object whose properties are proxies into the underlying memory space for the + * i-th element. This affords the convience of working with (seemingly) plain + * Javascript objects without the overhead of serializing/deserializing them + * into ArrayBuffers for efficient web worker transfer. + * + * @private + */ +class StructArray { + capacity: number; + length: number; + isTransferred: boolean; + arrayBuffer: ArrayBuffer; + uint8: Uint8Array; + + // The following properties are defined on the prototype. + members: Array; + bytesPerElement: number; + +emplaceBack: Function; + +emplace: Function; + + constructor() { + this.isTransferred = false; + this.capacity = -1; + this.resize(0); + } + + /** + * Serialize a StructArray instance. Serializes both the raw data and the + * metadata needed to reconstruct the StructArray base class during + * deserialization. + * @private + */ + static serialize(array: StructArray, transferables?: Array): SerializedStructArray { + assert(!array.isTransferred); + + array._trim(); + + if (transferables) { + array.isTransferred = true; + transferables.push(array.arrayBuffer); + } + + return { + length: array.length, + arrayBuffer: array.arrayBuffer, + }; + } + + static deserialize(input: SerializedStructArray) { + const structArray = Object.create(this.prototype); + structArray.arrayBuffer = input.arrayBuffer; + structArray.length = input.length; + structArray.capacity = input.arrayBuffer.byteLength / structArray.bytesPerElement; + structArray._refreshViews(); + return structArray; + } + + /** + * Resize the array to discard unused capacity. + */ + _trim() { + if (this.length !== this.capacity) { + this.capacity = this.length; + this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement); + this._refreshViews(); + } + } + + /** + * Resets the the length of the array to 0 without de-allocating capcacity. + */ + clear() { + this.length = 0; + } + + /** + * Resize the array. + * If `n` is greater than the current length then additional elements with undefined values are added. + * If `n` is less than the current length then the array will be reduced to the first `n` elements. + * @param {number} n The new size of the array. + */ + resize(n: number) { + assert(!this.isTransferred); + this.reserve(n); + this.length = n; + } + + /** + * Indicate a planned increase in size, so that any necessary allocation may + * be done once, ahead of time. + * @param {number} n The expected size of the array. + */ + reserve(n: number) { + if (n > this.capacity) { + this.capacity = Math.max(n, Math.floor(this.capacity * RESIZE_MULTIPLIER), DEFAULT_CAPACITY); + this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement); + + const oldUint8Array = this.uint8; + this._refreshViews(); + if (oldUint8Array) this.uint8.set(oldUint8Array); + } + } + + /** + * Create TypedArray views for the current ArrayBuffer. + */ + _refreshViews() { + throw new Error('_refreshViews() must be implemented by each concrete StructArray layout'); + } +} + +/** + * Given a list of member fields, create a full StructArrayLayout, in + * particular calculating the correct byte offset for each field. This data + * is used at build time to generate StructArrayLayout_*#emplaceBack() and + * other accessors, and at runtime for binding vertex buffer attributes. + * + * @private + */ +function createLayout( + members: Array<{ name: string, type: ViewType, +components?: number, }>, + alignment: number = 1 +): StructArrayLayout { + + let offset = 0; + let maxSize = 0; + const layoutMembers = members.map((member) => { + assert(member.name.length); + const typeSize = sizeOf(member.type); + const memberOffset = offset = align(offset, Math.max(alignment, typeSize)); + const components = member.components || 1; + + maxSize = Math.max(maxSize, typeSize); + offset += typeSize * components; + + return { + name: member.name, + type: member.type, + components, + offset: memberOffset, + }; + }); + + const size = align(offset, Math.max(maxSize, alignment)); + + return { + members: layoutMembers, + size, + alignment + }; +} + +function sizeOf(type: ViewType): number { + return viewTypes[type].BYTES_PER_ELEMENT; +} + +function align(offset: number, size: number): number { + return Math.ceil(offset / size) * size; +} + +export {StructArray, Struct, viewTypes, createLayout}; diff --git a/node_modules/mapbox-gl/src/util/struct_array.js.ejs b/node_modules/mapbox-gl/src/util/struct_array.js.ejs new file mode 100644 index 0000000000000000000000000000000000000000..e9d062ad65ffbb5ec60b3527ff8f24c56df3bc2c --- /dev/null +++ b/node_modules/mapbox-gl/src/util/struct_array.js.ejs @@ -0,0 +1,112 @@ +<% +const { + arrayClass, + members, + size, + usedTypes, + hasAnchorPoint, + layoutClass, + includeStructAccessors +} = locals + +const StructTypeClass = arrayClass.replace('Array', 'Struct'); +const StructArrayClass = arrayClass; +const StructArrayLayoutClass = layoutClass; +-%> +<% +// collect components +const components = []; +for (const member of members) { + for (let c = 0; c < member.components; c++) { + let name = member.name; + if (member.components > 1) { + name += c; + } + components.push({name, member, component: c}); + } +} + +// exceptions for which we generate accessors on the array rather than a separate struct for performance +const useComponentGetters = StructArrayClass === 'GlyphOffsetArray' || StructArrayClass === 'SymbolLineVertexArray'; + +if (includeStructAccessors && !useComponentGetters) { +-%> +class <%=StructTypeClass%> extends Struct { + _structArray: <%=StructArrayClass%>; +<% + // property declarations + for (const {name} of components) {-%> + <%=name%>: number; +<% } + if (hasAnchorPoint) { -%> + anchorPoint: Point; +<% } -%> +<% +for (const {name, member, component} of components) { + const elementOffset = `this._pos${member.size.toFixed(0)}`; + const componentOffset = (member.offset / member.size + component).toFixed(0); + const index = `${elementOffset} + ${componentOffset}`; + const componentAccess = `this._structArray.${member.view}[${index}]`; +-%> + get <%=name%>() { return <%=componentAccess%>; } +<% +// generate setters for properties that are updated during runtime symbol placement; others are read-only +if (name === 'crossTileID' || name === 'placedOrientation' || name === 'hidden') { +-%> + set <%=name%>(x: number) { <%=componentAccess%> = x; } +<% +} +} +// Special case used for the CollisionBoxArray type +if (hasAnchorPoint) { +-%> + get anchorPoint() { return new Point(this.anchorPointX, this.anchorPointY); } +<% +} +-%> +} + +<%=StructTypeClass%>.prototype.size = <%=size%>; + +export type <%=StructTypeClass.replace('Struct', '')%> = <%=StructTypeClass%>; + +<% +} // end 'if (includeStructAccessors)' +-%> +/** + * @private + */ +export class <%=StructArrayClass%> extends <%=StructArrayLayoutClass%> { +<% +if (useComponentGetters) { + for (const member of members) { + for (let c = 0; c < member.components; c++) { + if (!includeStructAccessors) continue; + let name = `get${member.name}`; + if (member.components > 1) { + name += c; + } + const componentOffset = (member.offset / member.size + c).toFixed(0); + const componentStride = size / member.size; +-%> + <%=name%>(index: number) { return this.<%=member.view%>[index * <%=componentStride%> + <%=componentOffset%>]; } +<% + } + } +} else if (includeStructAccessors) { // get(i) +-%> + /** + * Return the <%=StructTypeClass%> at the given location in the array. + * @param {number} index The index of the element. + * @private + */ + get(index: number): <%=StructTypeClass%> { + assert(!this.isTransferred); + return new <%=StructTypeClass%>(this, index); + } +<% +} +-%> +} + +register('<%=StructArrayClass%>', <%=StructArrayClass%>); diff --git a/node_modules/mapbox-gl/src/util/struct_array_layout.js.ejs b/node_modules/mapbox-gl/src/util/struct_array_layout.js.ejs new file mode 100644 index 0000000000000000000000000000000000000000..3be26217d0caa1c7b86ea0c3a3d72335bd2bf5cd --- /dev/null +++ b/node_modules/mapbox-gl/src/util/struct_array_layout.js.ejs @@ -0,0 +1,98 @@ +<% +const { + className, + members, + size, + usedTypes +} = locals + +const StructArrayLayoutClass = className; +-%> +/** + * Implementation of the StructArray layout: +<% +for (const member of members) { +-%> + * [<%=member.offset%>]: <%=member.type%>[<%=member.components%>] +<% +} +-%> + * + * @private + */ +class <%=StructArrayLayoutClass%> extends StructArray { +<% +for (const type of usedTypes) { +-%> + <%=type.toLowerCase()%>: <%=type%>Array; +<% +} +-%> + + _refreshViews() { +<% +for (const type of usedTypes) { +-%> + this.<%=type.toLowerCase()%> = new <%=type%>Array(this.arrayBuffer); +<% +} +-%> + } + +<% +// prep for emplaceBack: collect type sizes and count the number of arguments +// we'll need +const bytesPerElement = size; +const usedTypeSizes = []; +const argNames = []; +const argNamesTyped = []; +for (const member of members) { + if (usedTypeSizes.indexOf(member.size) < 0) { + usedTypeSizes.push(member.size); + } + for (let c = 0; c < member.components; c++) { + // arguments v0, v1, v2, ... are, in order, the components of + // member 0, then the components of member 1, etc. + const name = `v${argNames.length}`; + argNames.push(name); + argNamesTyped.push(`${name}: number`); + } +} +-%> + emplaceBack(<%=argNamesTyped.join(', ')%>) { + const i = this.length; + this.resize(i + 1); + return this.emplace(i, <%=argNames.join(', ')%>); + } + + emplace(i: number, <%=argNamesTyped.join(', ')%>) { +<% +{ +for (const size of usedTypeSizes) { +-%> + const o<%=size.toFixed(0)%> = i * <%=(bytesPerElement / size).toFixed(0)%>; +<% +} + +let argIndex = 0; +for (const member of members) { + for (let c = 0; c < member.components; c++) { + // The index for `member` component `c` into the appropriate type array is: + // this.{TYPE}[o{SIZE} + MEMBER_OFFSET + {c}] = v{X} + // where MEMBER_OFFSET = ROUND(member.offset / size) is the per-element + // offset of this member into the array + const index = `o${member.size.toFixed(0)} + ${(member.offset / member.size + c).toFixed(0)}`; +-%> + this.<%=member.view%>[<%=index%>] = v<%=argIndex++%>; +<% + } +} +} +-%> + return i; + } +-%> +} + +<%=StructArrayLayoutClass%>.prototype.bytesPerElement = <%= size %>; +register('<%=StructArrayLayoutClass%>', <%=StructArrayLayoutClass%>); diff --git a/node_modules/mapbox-gl/src/util/task_queue.js b/node_modules/mapbox-gl/src/util/task_queue.js new file mode 100644 index 0000000000000000000000000000000000000000..25b28d250f991d4e74a7e80227bf2d78296b3210 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/task_queue.js @@ -0,0 +1,68 @@ +// @flow strict +import assert from 'assert'; + +export type TaskID = number; // can't mark opaque due to https://github.com/flowtype/flow-remove-types/pull/61 +type Task = { + callback: (timeStamp: number) => void; + id: TaskID; + cancelled: boolean; +}; + +class TaskQueue { + _queue: Array; + _id: TaskID; + _cleared: boolean; + _currentlyRunning: Array | false; + + constructor() { + this._queue = []; + this._id = 0; + this._cleared = false; + this._currentlyRunning = false; + } + + add(callback: (timeStamp: number) => void): TaskID { + const id = ++this._id; + const queue = this._queue; + queue.push({callback, id, cancelled: false}); + return id; + } + + remove(id: TaskID) { + const running = this._currentlyRunning; + const queue = running ? this._queue.concat(running) : this._queue; + for (const task of queue) { + if (task.id === id) { + task.cancelled = true; + return; + } + } + } + + run(timeStamp: number = 0) { + assert(!this._currentlyRunning); + const queue = this._currentlyRunning = this._queue; + + // Tasks queued by callbacks in the current queue should be executed + // on the next run, not the current run. + this._queue = []; + + for (const task of queue) { + if (task.cancelled) continue; + task.callback(timeStamp); + if (this._cleared) break; + } + + this._cleared = false; + this._currentlyRunning = false; + } + + clear() { + if (this._currentlyRunning) { + this._cleared = true; + } + this._queue = []; + } +} + +export default TaskQueue; diff --git a/node_modules/mapbox-gl/src/util/throttle.js b/node_modules/mapbox-gl/src/util/throttle.js new file mode 100644 index 0000000000000000000000000000000000000000..79c7b6e70916b21cac6d0397998c865a723df335 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/throttle.js @@ -0,0 +1,27 @@ +// @flow strict + +/** + * Throttle the given function to run at most every `period` milliseconds. + * @private + */ +export default function throttle(fn: () => void, time: number): () => ?TimeoutID { + let pending = false; + let timerId: ?TimeoutID = null; + + const later = () => { + timerId = null; + if (pending) { + fn(); + timerId = setTimeout(later, time); + pending = false; + } + }; + + return () => { + pending = true; + if (!timerId) { + later(); + } + return timerId; + }; +} diff --git a/node_modules/mapbox-gl/src/util/throttled_invoker.js b/node_modules/mapbox-gl/src/util/throttled_invoker.js new file mode 100644 index 0000000000000000000000000000000000000000..ca1b97bfce1175cd64d4963e242e0a5fad3172cb --- /dev/null +++ b/node_modules/mapbox-gl/src/util/throttled_invoker.js @@ -0,0 +1,46 @@ +// @flow + +/** + * Invokes the wrapped function in a non-blocking way when trigger() is called. Invocation requests + * are ignored until the function was actually invoked. + * + * @private + */ +class ThrottledInvoker { + _channel: MessageChannel; + _triggered: boolean; + _callback: Function + + constructor(callback: Function) { + this._callback = callback; + this._triggered = false; + if (typeof MessageChannel !== 'undefined') { + this._channel = new MessageChannel(); + this._channel.port2.onmessage = () => { + this._triggered = false; + this._callback(); + }; + } + } + + trigger() { + if (!this._triggered) { + this._triggered = true; + if (this._channel) { + this._channel.port1.postMessage(true); + } else { + setTimeout(() => { + this._triggered = false; + this._callback(); + }, 0); + } + } + } + + remove() { + delete this._channel; + this._callback = () => {}; + } +} + +export default ThrottledInvoker; diff --git a/node_modules/mapbox-gl/src/util/tile_request_cache.js b/node_modules/mapbox-gl/src/util/tile_request_cache.js new file mode 100644 index 0000000000000000000000000000000000000000..22b01780379e8c1410bab7ea0633d4cd329ea089 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/tile_request_cache.js @@ -0,0 +1,172 @@ +// @flow + +import {warnOnce, parseCacheControl} from './util'; +import window from './window'; + +import type Dispatcher from './dispatcher'; + +const CACHE_NAME = 'mapbox-tiles'; +let cacheLimit = 500; // 50MB / (100KB/tile) ~= 500 tiles +let cacheCheckThreshold = 50; + +const MIN_TIME_UNTIL_EXPIRY = 1000 * 60 * 7; // 7 minutes. Skip caching tiles with a short enough max age. + +export type ResponseOptions = { + status: number, + statusText: string, + headers: window.Headers +}; + +// We're using a global shared cache object. Normally, requesting ad-hoc Cache objects is fine, but +// Safari has a memory leak in which it fails to release memory when requesting keys() from a Cache +// object. See https://bugs.webkit.org/show_bug.cgi?id=203991 for more information. +let sharedCache: ?Promise; + +function cacheOpen() { + if (window.caches && !sharedCache) { + sharedCache = window.caches.open(CACHE_NAME); + } +} + +// We're never closing the cache, but our unit tests rely on changing out the global window.caches +// object, so we have a function specifically for unit tests that allows resetting the shared cache. +export function cacheClose() { + sharedCache = undefined; +} + +let responseConstructorSupportsReadableStream; +function prepareBody(response: Response, callback) { + if (responseConstructorSupportsReadableStream === undefined) { + try { + new Response(new ReadableStream()); // eslint-disable-line no-undef + responseConstructorSupportsReadableStream = true; + } catch (e) { + // Edge + responseConstructorSupportsReadableStream = false; + } + } + + if (responseConstructorSupportsReadableStream) { + callback(response.body); + } else { + response.blob().then(callback); + } +} + +export function cachePut(request: Request, response: Response, requestTime: number) { + cacheOpen(); + if (!sharedCache) return; + + const options: ResponseOptions = { + status: response.status, + statusText: response.statusText, + headers: new window.Headers() + }; + response.headers.forEach((v, k) => options.headers.set(k, v)); + + const cacheControl = parseCacheControl(response.headers.get('Cache-Control') || ''); + if (cacheControl['no-store']) { + return; + } + if (cacheControl['max-age']) { + options.headers.set('Expires', new Date(requestTime + cacheControl['max-age'] * 1000).toUTCString()); + } + + const timeUntilExpiry = new Date(options.headers.get('Expires')).getTime() - requestTime; + if (timeUntilExpiry < MIN_TIME_UNTIL_EXPIRY) return; + + prepareBody(response, body => { + const clonedResponse = new window.Response(body, options); + + cacheOpen(); + if (!sharedCache) return; + sharedCache + .then(cache => cache.put(stripQueryParameters(request.url), clonedResponse)) + .catch(e => warnOnce(e.message)); + }); +} + +function stripQueryParameters(url: string) { + const start = url.indexOf('?'); + return start < 0 ? url : url.slice(0, start); +} + +export function cacheGet(request: Request, callback: (error: ?any, response: ?Response, fresh: ?boolean) => void) { + cacheOpen(); + if (!sharedCache) return callback(null); + + const strippedURL = stripQueryParameters(request.url); + + sharedCache + .then(cache => { + // manually strip URL instead of `ignoreSearch: true` because of a known + // performance issue in Chrome https://github.com/mapbox/mapbox-gl-js/issues/8431 + cache.match(strippedURL) + .then(response => { + const fresh = isFresh(response); + + // Reinsert into cache so that order of keys in the cache is the order of access. + // This line makes the cache a LRU instead of a FIFO cache. + cache.delete(strippedURL); + if (fresh) { + cache.put(strippedURL, response.clone()); + } + + callback(null, response, fresh); + }) + .catch(callback); + }) + .catch(callback); + +} + +function isFresh(response) { + if (!response) return false; + const expires = new Date(response.headers.get('Expires') || 0); + const cacheControl = parseCacheControl(response.headers.get('Cache-Control') || ''); + return expires > Date.now() && !cacheControl['no-cache']; +} + +// `Infinity` triggers a cache check after the first tile is loaded +// so that a check is run at least once on each page load. +let globalEntryCounter = Infinity; + +// The cache check gets run on a worker. The reason for this is that +// profiling sometimes shows this as taking up significant time on the +// thread it gets called from. And sometimes it doesn't. It *may* be +// fine to run this on the main thread but out of caution this is being +// dispatched on a worker. This can be investigated further in the future. +export function cacheEntryPossiblyAdded(dispatcher: Dispatcher) { + globalEntryCounter++; + if (globalEntryCounter > cacheCheckThreshold) { + dispatcher.getActor().send('enforceCacheSizeLimit', cacheLimit); + globalEntryCounter = 0; + } +} + +// runs on worker, see above comment +export function enforceCacheSizeLimit(limit: number) { + cacheOpen(); + if (!sharedCache) return; + + sharedCache + .then(cache => { + cache.keys().then(keys => { + for (let i = 0; i < keys.length - limit; i++) { + cache.delete(keys[i]); + } + }); + }); +} + +export function clearTileCache(callback?: (err: ?Error) => void) { + const promise = window.caches.delete(CACHE_NAME); + if (callback) { + promise.catch(callback).then(() => callback()); + } +} + +export function setCacheLimits(limit: number, checkThreshold: number) { + cacheLimit = limit; + cacheCheckThreshold = checkThreshold; +} diff --git a/node_modules/mapbox-gl/src/util/util.js b/node_modules/mapbox-gl/src/util/util.js new file mode 100644 index 0000000000000000000000000000000000000000..f5e3d55c58a15a254524b4f27a2b84d00b87fde4 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/util.js @@ -0,0 +1,524 @@ +// @flow + +import UnitBezier from '@mapbox/unitbezier'; + +import Point from '@mapbox/point-geometry'; +import window from './window'; + +import type {Callback} from '../types/callback'; + +// Number.MAX_SAFE_INTEGER not available in IE +export const MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; + +/** + * @module util + * @private + */ + +/** + * Given a value `t` that varies between 0 and 1, return + * an interpolation function that eases between 0 and 1 in a pleasing + * cubic in-out fashion. + * + * @private + */ +export function easeCubicInOut(t: number): number { + if (t <= 0) return 0; + if (t >= 1) return 1; + const t2 = t * t, + t3 = t2 * t; + return 4 * (t < 0.5 ? t3 : 3 * (t - t2) + t3 - 0.75); +} + +/** + * Given given (x, y), (x1, y1) control points for a bezier curve, + * return a function that interpolates along that curve. + * + * @param p1x control point 1 x coordinate + * @param p1y control point 1 y coordinate + * @param p2x control point 2 x coordinate + * @param p2y control point 2 y coordinate + * @private + */ +export function bezier(p1x: number, p1y: number, p2x: number, p2y: number): (t: number) => number { + const bezier = new UnitBezier(p1x, p1y, p2x, p2y); + return function(t: number) { + return bezier.solve(t); + }; +} + +/** + * A default bezier-curve powered easing function with + * control points (0.25, 0.1) and (0.25, 1) + * + * @private + */ +export const ease = bezier(0.25, 0.1, 0.25, 1); + +/** + * constrain n to the given range via min + max + * + * @param n value + * @param min the minimum value to be returned + * @param max the maximum value to be returned + * @returns the clamped value + * @private + */ +export function clamp(n: number, min: number, max: number): number { + return Math.min(max, Math.max(min, n)); +} + +/** + * constrain n to the given range, excluding the minimum, via modular arithmetic + * + * @param n value + * @param min the minimum value to be returned, exclusive + * @param max the maximum value to be returned, inclusive + * @returns constrained number + * @private + */ +export function wrap(n: number, min: number, max: number): number { + const d = max - min; + const w = ((n - min) % d + d) % d + min; + return (w === min) ? max : w; +} + +/* + * Call an asynchronous function on an array of arguments, + * calling `callback` with the completed results of all calls. + * + * @param array input to each call of the async function. + * @param fn an async function with signature (data, callback) + * @param callback a callback run after all async work is done. + * called with an array, containing the results of each async call. + * @private + */ +export function asyncAll( + array: Array, + fn: (item: Item, fnCallback: Callback) => void, + callback: Callback> +) { + if (!array.length) { return callback(null, []); } + let remaining = array.length; + const results = new Array(array.length); + let error = null; + array.forEach((item, i) => { + fn(item, (err, result) => { + if (err) error = err; + results[i] = ((result: any): Result); // https://github.com/facebook/flow/issues/2123 + if (--remaining === 0) callback(error, results); + }); + }); +} + +/* + * Polyfill for Object.values. Not fully spec compliant, but we don't + * need it to be. + * + * @private + */ +export function values(obj: {[key: string]: T}): Array { + const result = []; + for (const k in obj) { + result.push(obj[k]); + } + return result; +} + +/* + * Compute the difference between the keys in one object and the keys + * in another object. + * + * @returns keys difference + * @private + */ +export function keysDifference(obj: {[key: string]: S}, other: {[key: string]: T}): Array { + const difference = []; + for (const i in obj) { + if (!(i in other)) { + difference.push(i); + } + } + return difference; +} + +/** + * Given a destination object and optionally many source objects, + * copy all properties from the source objects into the destination. + * The last source object given overrides properties from previous + * source objects. + * + * @param dest destination object + * @param sources sources from which properties are pulled + * @private + */ +export function extend(dest: Object, ...sources: Array): Object { + for (const src of sources) { + for (const k in src) { + dest[k] = src[k]; + } + } + return dest; +} + +/** + * Given an object and a number of properties as strings, return version + * of that object with only those properties. + * + * @param src the object + * @param properties an array of property names chosen + * to appear on the resulting object. + * @returns object with limited properties. + * @example + * var foo = { name: 'Charlie', age: 10 }; + * var justName = pick(foo, ['name']); + * // justName = { name: 'Charlie' } + * @private + */ +export function pick(src: Object, properties: Array): Object { + const result = {}; + for (let i = 0; i < properties.length; i++) { + const k = properties[i]; + if (k in src) { + result[k] = src[k]; + } + } + return result; +} + +let id = 1; + +/** + * Return a unique numeric id, starting at 1 and incrementing with + * each call. + * + * @returns unique numeric id. + * @private + */ +export function uniqueId(): number { + return id++; +} + +/** + * Return a random UUID (v4). Taken from: https://gist.github.com/jed/982883 + * @private + */ +export function uuid(): string { + function b(a) { + return a ? (a ^ Math.random() * 16 >> a / 4).toString(16) : + //$FlowFixMe: Flow doesn't like the implied array literal conversion here + ([1e7] + -[1e3] + -4e3 + -8e3 + -1e11).replace(/[018]/g, b); + } + return b(); +} + +/** + * Return whether a given value is a power of two + * @private + */ +export function isPowerOfTwo(value: number): boolean { + return (Math.log(value) / Math.LN2) % 1 === 0; +} + +/** + * Return the next power of two, or the input value if already a power of two + * @private + */ +export function nextPowerOfTwo(value: number): number { + if (value <= 1) return 1; + return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2)); +} + +/** + * Validate a string to match UUID(v4) of the + * form: xxxxxxxx-xxxx-4xxx-[89ab]xxx-xxxxxxxxxxxx + * @param str string to validate. + * @private + */ +export function validateUuid(str: ?string): boolean { + return str ? /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(str) : false; +} + +/** + * Given an array of member function names as strings, replace all of them + * with bound versions that will always refer to `context` as `this`. This + * is useful for classes where otherwise event bindings would reassign + * `this` to the evented object or some other value: this lets you ensure + * the `this` value always. + * + * @param fns list of member function names + * @param context the context value + * @example + * function MyClass() { + * bindAll(['ontimer'], this); + * this.name = 'Tom'; + * } + * MyClass.prototype.ontimer = function() { + * alert(this.name); + * }; + * var myClass = new MyClass(); + * setTimeout(myClass.ontimer, 100); + * @private + */ +export function bindAll(fns: Array, context: Object): void { + fns.forEach((fn) => { + if (!context[fn]) { return; } + context[fn] = context[fn].bind(context); + }); +} + +/** + * Determine if a string ends with a particular substring + * + * @private + */ +export function endsWith(string: string, suffix: string): boolean { + return string.indexOf(suffix, string.length - suffix.length) !== -1; +} + +/** + * Create an object by mapping all the values of an existing object while + * preserving their keys. + * + * @private + */ +export function mapObject(input: Object, iterator: Function, context?: Object): Object { + const output = {}; + for (const key in input) { + output[key] = iterator.call(context || this, input[key], key, input); + } + return output; +} + +/** + * Create an object by filtering out values of an existing object. + * + * @private + */ +export function filterObject(input: Object, iterator: Function, context?: Object): Object { + const output = {}; + for (const key in input) { + if (iterator.call(context || this, input[key], key, input)) { + output[key] = input[key]; + } + } + return output; +} + +import deepEqual from '../style-spec/util/deep_equal'; +export {deepEqual}; + +/** + * Deeply clones two objects. + * + * @private + */ +export function clone(input: T): T { + if (Array.isArray(input)) { + return input.map(clone); + } else if (typeof input === 'object' && input) { + return ((mapObject(input, clone): any): T); + } else { + return input; + } +} + +/** + * Check if two arrays have at least one common element. + * + * @private + */ +export function arraysIntersect(a: Array, b: Array): boolean { + for (let l = 0; l < a.length; l++) { + if (b.indexOf(a[l]) >= 0) return true; + } + return false; +} + +/** + * Print a warning message to the console and ensure duplicate warning messages + * are not printed. + * + * @private + */ +const warnOnceHistory: {[key: string]: boolean} = {}; + +export function warnOnce(message: string): void { + if (!warnOnceHistory[message]) { + // console isn't defined in some WebWorkers, see #2558 + if (typeof console !== "undefined") console.warn(message); + warnOnceHistory[message] = true; + } +} + +/** + * Indicates if the provided Points are in a counter clockwise (true) or clockwise (false) order + * + * @private + * @returns true for a counter clockwise set of points + */ +// http://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/ +export function isCounterClockwise(a: Point, b: Point, c: Point): boolean { + return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x); +} + +/** + * Returns the signed area for the polygon ring. Postive areas are exterior rings and + * have a clockwise winding. Negative areas are interior rings and have a counter clockwise + * ordering. + * + * @private + * @param ring Exterior or interior ring + */ +export function calculateSignedArea(ring: Array): number { + let sum = 0; + for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + sum += (p2.x - p1.x) * (p1.y + p2.y); + } + return sum; +} + +/** + * Detects closed polygons, first + last point are equal + * + * @private + * @param points array of points + * @return true if the points are a closed polygon + */ +export function isClosedPolygon(points: Array): boolean { + // If it is 2 points that are the same then it is a point + // If it is 3 points with start and end the same then it is a line + if (points.length < 4) + return false; + + const p1 = points[0]; + const p2 = points[points.length - 1]; + + if (Math.abs(p1.x - p2.x) > 0 || + Math.abs(p1.y - p2.y) > 0) { + return false; + } + + // polygon simplification can produce polygons with zero area and more than 3 points + return Math.abs(calculateSignedArea(points)) > 0.01; +} + +/** + * Converts spherical coordinates to cartesian coordinates. + * + * @private + * @param spherical Spherical coordinates, in [radial, azimuthal, polar] + * @return cartesian coordinates in [x, y, z] + */ + +export function sphericalToCartesian([r, azimuthal, polar]: [number, number, number]): {x: number, y: number, z: number} { + // We abstract "north"/"up" (compass-wise) to be 0° when really this is 90° (π/2): + // correct for that here + azimuthal += 90; + + // Convert azimuthal and polar angles to radians + azimuthal *= Math.PI / 180; + polar *= Math.PI / 180; + + return { + x: r * Math.cos(azimuthal) * Math.sin(polar), + y: r * Math.sin(azimuthal) * Math.sin(polar), + z: r * Math.cos(polar) + }; +} + +/* global self, WorkerGlobalScope */ +/** + * Retuns true if the when run in the web-worker context. + * + * @private + * @returns {boolean} + */ +export function isWorker(): boolean { + return typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && + self instanceof WorkerGlobalScope; +} + +/** + * Parses data from 'Cache-Control' headers. + * + * @private + * @param cacheControl Value of 'Cache-Control' header + * @return object containing parsed header info. + */ + +export function parseCacheControl(cacheControl: string): Object { + // Taken from [Wreck](https://github.com/hapijs/wreck) + const re = /(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g; + + const header = {}; + cacheControl.replace(re, ($0, $1, $2, $3) => { + const value = $2 || $3; + header[$1] = value ? value.toLowerCase() : true; + return ''; + }); + + if (header['max-age']) { + const maxAge = parseInt(header['max-age'], 10); + if (isNaN(maxAge)) delete header['max-age']; + else header['max-age'] = maxAge; + } + + return header; +} + +let _isSafari = null; + +/** + * Returns true when run in WebKit derived browsers. + * This is used as a workaround for a memory leak in Safari caused by using Transferable objects to + * transfer data between WebWorkers and the main thread. + * https://github.com/mapbox/mapbox-gl-js/issues/8771 + * + * This should be removed once the underlying Safari issue is fixed. + * + * @private + * @param scope {WindowOrWorkerGlobalScope} Since this function is used both on the main thread and WebWorker context, + * let the calling scope pass in the global scope object. + * @returns {boolean} + */ +export function isSafari(scope: any): boolean { + if (_isSafari == null) { + const userAgent = scope.navigator ? scope.navigator.userAgent : null; + _isSafari = !!scope.safari || + !!(userAgent && (/\b(iPad|iPhone|iPod)\b/.test(userAgent) || (!!userAgent.match('Safari') && !userAgent.match('Chrome')))); + } + return _isSafari; +} + +export function storageAvailable(type: string): boolean { + try { + const storage = window[type]; + storage.setItem('_mapbox_test_', 1); + storage.removeItem('_mapbox_test_'); + return true; + } catch (e) { + return false; + } +} + +// The following methods are from https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem +//Unicode compliant base64 encoder for strings +export function b64EncodeUnicode(str: string) { + return window.btoa( + encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, + (match, p1) => { + return String.fromCharCode(Number('0x' + p1)); //eslint-disable-line + } + ) + ); +} + +// Unicode compliant decoder for base64-encoded strings +export function b64DecodeUnicode(str: string) { + return decodeURIComponent(window.atob(str).split('').map((c) => { + return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); //eslint-disable-line + }).join('')); +} diff --git a/node_modules/mapbox-gl/src/util/vectortile_to_geojson.js b/node_modules/mapbox-gl/src/util/vectortile_to_geojson.js new file mode 100644 index 0000000000000000000000000000000000000000..87df3344a4f403d1a19d83c008675418f553a26b --- /dev/null +++ b/node_modules/mapbox-gl/src/util/vectortile_to_geojson.js @@ -0,0 +1,50 @@ +// @flow +import type {GeoJSONGeometry} from '@mapbox/geojson-types'; + +class Feature { + type: 'Feature'; + _geometry: ?GeoJSONGeometry; + properties: {}; + id: number | string | void; + + _vectorTileFeature: VectorTileFeature; + + constructor(vectorTileFeature: VectorTileFeature, z: number, x: number, y: number, id: string | number | void) { + this.type = 'Feature'; + + this._vectorTileFeature = vectorTileFeature; + (vectorTileFeature: any)._z = z; + (vectorTileFeature: any)._x = x; + (vectorTileFeature: any)._y = y; + + this.properties = vectorTileFeature.properties; + this.id = id; + } + + get geometry(): ?GeoJSONGeometry { + if (this._geometry === undefined) { + this._geometry = this._vectorTileFeature.toGeoJSON( + (this._vectorTileFeature: any)._x, + (this._vectorTileFeature: any)._y, + (this._vectorTileFeature: any)._z).geometry; + } + return this._geometry; + } + + set geometry(g: ?GeoJSONGeometry) { + this._geometry = g; + } + + toJSON() { + const json = { + geometry: this.geometry + }; + for (const i in this) { + if (i === '_geometry' || i === '_vectorTileFeature') continue; + json[i] = (this: any)[i]; + } + return json; + } +} + +export default Feature; diff --git a/node_modules/mapbox-gl/src/util/verticalize_punctuation.js b/node_modules/mapbox-gl/src/util/verticalize_punctuation.js new file mode 100644 index 0000000000000000000000000000000000000000..658ffdf6316d58e96f44c4e12e7494117b4ffe80 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/verticalize_punctuation.js @@ -0,0 +1,114 @@ +// @flow + +import { + charHasRotatedVerticalOrientation, +} from './script_detection'; + +export const verticalizedCharacterMap = { + '!': '︕', + '#': '#', + '$': '$', + '%': '%', + '&': '&', + '(': '︵', + ')': '︶', + '*': '*', + '+': '+', + ',': '︐', + '-': '︲', + '.': '・', + '/': '/', + ':': '︓', + ';': '︔', + '<': '︿', + '=': '=', + '>': '﹀', + '?': '︖', + '@': '@', + '[': '﹇', + '\\': '\', + ']': '﹈', + '^': '^', + '_': '︳', + '`': '`', + '{': '︷', + '|': '―', + '}': '︸', + '~': '~', + '¢': '¢', + '£': '£', + '¥': '¥', + '¦': '¦', + '¬': '¬', + '¯': ' ̄', + '–': '︲', + '—': '︱', + '‘': '﹃', + '’': '﹄', + '“': '﹁', + '”': '﹂', + '…': '︙', + '‧': '・', + '₩': '₩', + '、': '︑', + '。': '︒', + '〈': '︿', + '〉': '﹀', + '《': '︽', + '》': '︾', + '「': '﹁', + '」': '﹂', + '『': '﹃', + '』': '﹄', + '【': '︻', + '】': '︼', + '〔': '︹', + '〕': '︺', + '〖': '︗', + '〗': '︘', + '!': '︕', + '(': '︵', + ')': '︶', + ',': '︐', + '-': '︲', + '.': '・', + ':': '︓', + ';': '︔', + '<': '︿', + '>': '﹀', + '?': '︖', + '[': '﹇', + ']': '﹈', + '_': '︳', + '{': '︷', + '|': '―', + '}': '︸', + '⦅': '︵', + '⦆': '︶', + '。': '︒', + '「': '﹁', + '」': '﹂' +}; + +export default function verticalizePunctuation(input: string) { + let output = ''; + + for (let i = 0; i < input.length; i++) { + const nextCharCode = input.charCodeAt(i + 1) || null; + const prevCharCode = input.charCodeAt(i - 1) || null; + + const canReplacePunctuation = ( + (!nextCharCode || !charHasRotatedVerticalOrientation(nextCharCode) || verticalizedCharacterMap[input[i + 1]]) && + (!prevCharCode || !charHasRotatedVerticalOrientation(prevCharCode) || verticalizedCharacterMap[input[i - 1]]) + ); + + if (canReplacePunctuation && verticalizedCharacterMap[input[i]]) { + output += verticalizedCharacterMap[input[i]]; + } else { + output += input[i]; + } + } + + return output; +} + diff --git a/node_modules/mapbox-gl/src/util/web_worker.js b/node_modules/mapbox-gl/src/util/web_worker.js new file mode 100644 index 0000000000000000000000000000000000000000..b08477c97b3130312bf0dcd1eef3fc44c66528ae --- /dev/null +++ b/node_modules/mapbox-gl/src/util/web_worker.js @@ -0,0 +1,91 @@ +// @flow + +// This file is intended for use in the GL-JS test suite +// It implements a MessageBus main thread interface for use in Node environments +// In a browser environment, this file is replaced with ./src/util/browser/web_worker.js +// when Rollup builds the main bundle. +// See package.json#browser + +import Worker from '../source/worker'; + +import type {WorkerSource} from '../source/worker_source'; + +type MessageListener = ({data: Object}) => mixed; + +// The main thread interface. Provided by Worker in a browser environment, +// and MessageBus below in a node environment. +export interface WorkerInterface { + addEventListener(type: 'message', listener: MessageListener): void; + removeEventListener(type: 'message', listener: MessageListener): void; + postMessage(message: any): void; + terminate(): void; +} + +export interface WorkerGlobalScopeInterface { + importScripts(...urls: Array): void; + + registerWorkerSource: (string, Class) => void, + registerRTLTextPlugin: (_: any) => void +} + +class MessageBus implements WorkerInterface, WorkerGlobalScopeInterface { + addListeners: Array; + postListeners: Array; + target: MessageBus; + registerWorkerSource: *; + registerRTLTextPlugin: *; + + constructor(addListeners: Array, postListeners: Array) { + this.addListeners = addListeners; + this.postListeners = postListeners; + } + + addEventListener(event: 'message', callback: MessageListener) { + if (event === 'message') { + this.addListeners.push(callback); + } + } + + removeEventListener(event: 'message', callback: MessageListener) { + const i = this.addListeners.indexOf(callback); + if (i >= 0) { + this.addListeners.splice(i, 1); + } + } + + postMessage(data: Object) { + setImmediate(() => { + try { + for (const listener of this.postListeners) { + listener({data, target: this.target}); + } + } catch (e) { + console.error(e); + } + }); + } + + terminate() { + this.addListeners.splice(0, this.addListeners.length); + this.postListeners.splice(0, this.postListeners.length); + } + + importScripts() {} +} + +export default function WebWorker(): WorkerInterface { + const parentListeners = [], + workerListeners = [], + parentBus = new MessageBus(workerListeners, parentListeners), + workerBus = new MessageBus(parentListeners, workerListeners); + + parentBus.target = workerBus; + workerBus.target = parentBus; + + new WebWorker.Worker(workerBus); + + return parentBus; +} + +// expose to allow stubbing in unit tests +WebWorker.Worker = Worker; diff --git a/node_modules/mapbox-gl/src/util/web_worker_transfer.js b/node_modules/mapbox-gl/src/util/web_worker_transfer.js new file mode 100644 index 0000000000000000000000000000000000000000..a3625eccc42c3796e49fb7d0fe24a06f360c7842 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/web_worker_transfer.js @@ -0,0 +1,266 @@ +// @flow + +import assert from 'assert'; + +import Grid from 'grid-index'; +import Color from '../style-spec/util/color'; +import {StylePropertyFunction, StyleExpression, ZoomDependentExpression, ZoomConstantExpression} from '../style-spec/expression'; +import CompoundExpression from '../style-spec/expression/compound_expression'; +import expressions from '../style-spec/expression/definitions'; +import ResolvedImage from '../style-spec/expression/types/resolved_image'; +import window from './window'; +const {ImageData, ImageBitmap} = window; + +import type {Transferable} from '../types/transferable'; + +type SerializedObject = {[_: string]: Serialized }; // eslint-disable-line +export type Serialized = + | null + | void + | boolean + | number + | string + | Boolean + | Number + | String + | Date + | RegExp + | ArrayBuffer + | $ArrayBufferView + | ImageData + | Array + | SerializedObject; + +type Registry = { + [_: string]: { + klass: Class, + omit: $ReadOnlyArray, + shallow: $ReadOnlyArray + } +}; + +type RegisterOptions = { + omit?: $ReadOnlyArray<$Keys>, + shallow?: $ReadOnlyArray<$Keys> +} + +const registry: Registry = {}; + +/** + * Register the given class as serializable. + * + * @param options + * @param options.omit List of properties to omit from serialization (e.g., cached/computed properties) + * @param options.shallow List of properties that should be serialized by a simple shallow copy, rather than by a recursive call to serialize(). + * + * @private + */ +export function register(name: string, klass: Class, options: RegisterOptions = {}) { + assert(!registry[name], `${name} is already registered.`); + (Object.defineProperty: any)(klass, '_classRegistryKey', { + value: name, + writeable: false + }); + registry[name] = { + klass, + omit: options.omit || [], + shallow: options.shallow || [] + }; +} + +register('Object', Object); + +type SerializedGrid = { buffer: ArrayBuffer }; + +Grid.serialize = function serialize(grid: Grid, transferables?: Array): SerializedGrid { + const buffer = grid.toArrayBuffer(); + if (transferables) { + transferables.push(buffer); + } + return {buffer}; +}; + +Grid.deserialize = function deserialize(serialized: SerializedGrid): Grid { + return new Grid(serialized.buffer); +}; +register('Grid', Grid); + +register('Color', Color); +register('Error', Error); +register('ResolvedImage', ResolvedImage); + +register('StylePropertyFunction', StylePropertyFunction); +register('StyleExpression', StyleExpression, {omit: ['_evaluator']}); + +register('ZoomDependentExpression', ZoomDependentExpression); +register('ZoomConstantExpression', ZoomConstantExpression); +register('CompoundExpression', CompoundExpression, {omit: ['_evaluate']}); +for (const name in expressions) { + if ((expressions[name]: any)._classRegistryKey) continue; + register(`Expression_${name}`, expressions[name]); +} + +function isArrayBuffer(val: any): boolean { + return val && typeof ArrayBuffer !== 'undefined' && + (val instanceof ArrayBuffer || (val.constructor && val.constructor.name === 'ArrayBuffer')); +} + +function isImageBitmap(val: any): boolean { + return ImageBitmap && + val instanceof ImageBitmap; +} + +/** + * Serialize the given object for transfer to or from a web worker. + * + * For non-builtin types, recursively serialize each property (possibly + * omitting certain properties - see register()), and package the result along + * with the constructor's `name` so that the appropriate constructor can be + * looked up in `deserialize()`. + * + * If a `transferables` array is provided, add any transferable objects (i.e., + * any ArrayBuffers or ArrayBuffer views) to the list. (If a copy is needed, + * this should happen in the client code, before using serialize().) + * + * @private + */ +export function serialize(input: mixed, transferables: ?Array): Serialized { + if (input === null || + input === undefined || + typeof input === 'boolean' || + typeof input === 'number' || + typeof input === 'string' || + input instanceof Boolean || + input instanceof Number || + input instanceof String || + input instanceof Date || + input instanceof RegExp) { + return input; + } + + if (isArrayBuffer(input) || isImageBitmap(input)) { + if (transferables) { + transferables.push(((input: any): ArrayBuffer)); + } + return input; + } + + if (ArrayBuffer.isView(input)) { + const view: $ArrayBufferView = (input: any); + if (transferables) { + transferables.push(view.buffer); + } + return view; + } + + if (input instanceof ImageData) { + if (transferables) { + transferables.push(input.data.buffer); + } + return input; + } + + if (Array.isArray(input)) { + const serialized: Array = []; + for (const item of input) { + serialized.push(serialize(item, transferables)); + } + return serialized; + } + + if (typeof input === 'object') { + const klass = (input.constructor: any); + const name = klass._classRegistryKey; + if (!name) { + throw new Error(`can't serialize object of unregistered class`); + } + assert(registry[name]); + + const properties: SerializedObject = klass.serialize ? + // (Temporary workaround) allow a class to provide static + // `serialize()` and `deserialize()` methods to bypass the generic + // approach. + // This temporary workaround lets us use the generic serialization + // approach for objects whose members include instances of dynamic + // StructArray types. Once we refactor StructArray to be static, + // we can remove this complexity. + (klass.serialize(input, transferables): SerializedObject) : {}; + + if (!klass.serialize) { + for (const key in input) { + // any cast due to https://github.com/facebook/flow/issues/5393 + if (!(input: any).hasOwnProperty(key)) continue; + if (registry[name].omit.indexOf(key) >= 0) continue; + const property = (input: any)[key]; + properties[key] = registry[name].shallow.indexOf(key) >= 0 ? + property : + serialize(property, transferables); + } + if (input instanceof Error) { + properties.message = input.message; + } + } else { + // make sure statically serialized object survives transfer of $name property + assert(!transferables || properties !== transferables[transferables.length - 1]); + } + + if (properties.$name) { + throw new Error('$name property is reserved for worker serialization logic.'); + } + if (name !== 'Object') { + properties.$name = name; + } + + return properties; + } + + throw new Error(`can't serialize object of type ${typeof input}`); +} + +export function deserialize(input: Serialized): mixed { + if (input === null || + input === undefined || + typeof input === 'boolean' || + typeof input === 'number' || + typeof input === 'string' || + input instanceof Boolean || + input instanceof Number || + input instanceof String || + input instanceof Date || + input instanceof RegExp || + isArrayBuffer(input) || + isImageBitmap(input) || + ArrayBuffer.isView(input) || + input instanceof ImageData) { + return input; + } + + if (Array.isArray(input)) { + return input.map(deserialize); + } + + if (typeof input === 'object') { + const name = (input: any).$name || 'Object'; + + const {klass} = registry[name]; + if (!klass) { + throw new Error(`can't deserialize unregistered class ${name}`); + } + + if (klass.deserialize) { + return (klass.deserialize: typeof deserialize)(input); + } + + const result = Object.create(klass.prototype); + + for (const key of Object.keys(input)) { + if (key === '$name') continue; + const value = (input: SerializedObject)[key]; + result[key] = registry[name].shallow.indexOf(key) >= 0 ? value : deserialize(value); + } + + return result; + } + + throw new Error(`can't deserialize object of type ${typeof input}`); +} diff --git a/node_modules/mapbox-gl/src/util/webp_supported.js b/node_modules/mapbox-gl/src/util/webp_supported.js new file mode 100644 index 0000000000000000000000000000000000000000..7c40c7c97b531c6f93a7b7f55844687beb9d027c --- /dev/null +++ b/node_modules/mapbox-gl/src/util/webp_supported.js @@ -0,0 +1,69 @@ +// @flow strict + +import window from './window'; + +const exported = { + supported: false, + testSupport +}; + +export default exported; + +let glForTesting; +let webpCheckComplete = false; +let webpImgTest; +let webpImgTestOnloadComplete = false; + +if (window.document) { + webpImgTest = window.document.createElement('img'); + webpImgTest.onload = function() { + if (glForTesting) testWebpTextureUpload(glForTesting); + glForTesting = null; + webpImgTestOnloadComplete = true; + }; + webpImgTest.onerror = function() { + webpCheckComplete = true; + glForTesting = null; + }; + webpImgTest.src = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA='; +} + +function testSupport(gl: WebGLRenderingContext) { + if (webpCheckComplete || !webpImgTest) return; + + // HTMLImageElement.complete is set when an image is done loading it's source + // regardless of whether the load was successful or not. + // It's possible for an error to set HTMLImageElement.complete to true which would trigger + // testWebpTextureUpload and mistakenly set exported.supported to true in browsers which don't support webp + // To avoid this, we set a flag in the image's onload handler and only call testWebpTextureUpload + // after a successful image load event. + if (webpImgTestOnloadComplete) { + testWebpTextureUpload(gl); + } else { + glForTesting = gl; + + } +} + +function testWebpTextureUpload(gl: WebGLRenderingContext) { + // Edge 18 supports WebP but not uploading a WebP image to a gl texture + // Test support for this before allowing WebP images. + // https://github.com/mapbox/mapbox-gl-js/issues/7671 + const texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + + try { + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, webpImgTest); + + // The error does not get triggered in Edge if the context is lost + if (gl.isContextLost()) return; + + exported.supported = true; + } catch (e) { + // Catch "Unspecified Error." in Edge 18. + } + + gl.deleteTexture(texture); + + webpCheckComplete = true; +} diff --git a/node_modules/mapbox-gl/src/util/window.js b/node_modules/mapbox-gl/src/util/window.js new file mode 100644 index 0000000000000000000000000000000000000000..0d465f163f9e16e73805eefda9a678b6dcaadae8 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/window.js @@ -0,0 +1,102 @@ +// @flow strict + +// This file is intended for use in the GL-JS test suite +// It implements a JSDOM window object for use in Node environments +// In a browser environment, this file is replaced with ./src/util/browser/window.js +// when Rollup builds the main bundle +// See package.json#browser + +import jsdom from 'jsdom'; + +import gl from 'gl'; +import sinon from 'sinon'; + +import type {Window} from '../types/window'; + +const {window: _window} = new jsdom.JSDOM('', { + virtualConsole: new jsdom.VirtualConsole().sendTo(console) +}); + +restore(); + +export default _window; + +function restore(): Window { + // Remove previous window from exported object + const previousWindow = _window; + if (previousWindow.close) previousWindow.close(); + for (const key in previousWindow) { + if (previousWindow.hasOwnProperty(key)) { + delete previousWindow[key]; + } + } + + // Create new window and inject into exported object + const {window} = new jsdom.JSDOM('', { + // Send jsdom console output to the node console object. + virtualConsole: new jsdom.VirtualConsole().sendTo(console) + }); + + // Delete local and session storage from JSDOM and stub them out with a warning log + // Accessing these properties during extend() produces an error in Node environments + // See https://github.com/mapbox/mapbox-gl-js/pull/7455 for discussion + delete window.localStorage; + delete window.sessionStorage; + window.localStorage = window.sessionStorage = () => console.log('Local and session storage not available in Node. Use a stub implementation if needed for testing.'); + + window.devicePixelRatio = 1; + + window.requestAnimationFrame = function(callback) { + return setImmediate(callback, 0); + }; + window.cancelAnimationFrame = clearImmediate; + + // Add webgl context with the supplied GL + const originalGetContext = window.HTMLCanvasElement.prototype.getContext; + window.HTMLCanvasElement.prototype.getContext = function (type, attributes) { + if (type === 'webgl') { + if (!this._webGLContext) { + this._webGLContext = gl(this.width, this.height, attributes); + } + return this._webGLContext; + } + // Fallback to existing HTMLCanvasElement getContext behaviour + return originalGetContext.call(this, type, attributes); + }; + + window.useFakeHTMLCanvasGetContext = function() { + this.HTMLCanvasElement.prototype.getContext = function() { return '2d'; }; + }; + + window.useFakeXMLHttpRequest = function() { + sinon.xhr.supportsCORS = true; + this.server = sinon.fakeServer.create(); + this.XMLHttpRequest = this.server.xhr; + }; + + window.URL.revokeObjectURL = function () {}; + + window.fakeWorkerPresence = function() { + global.WorkerGlobalScope = function() {}; + global.self = new global.WorkerGlobalScope(); + }; + window.clearFakeWorkerPresence = function() { + global.WorkerGlobalScope = undefined; + global.self = undefined; + }; + + window.restore = restore; + + window.performance.getEntriesByName = function() {}; + window.performance.mark = function() {}; + window.performance.measure = function() {}; + window.performance.clearMarks = function() {}; + window.performance.clearMeasures = function() {}; + + window.ImageData = window.ImageData || function() { return false; }; + window.ImageBitmap = window.ImageBitmap || function() { return false; }; + window.WebGLFramebuffer = window.WebGLFramebuffer || Object; + Object.assign(_window, window); // eslint-disable-line no-restricted-properties + + return window; +} diff --git a/node_modules/mapbox-gl/src/util/worker_pool.js b/node_modules/mapbox-gl/src/util/worker_pool.js new file mode 100644 index 0000000000000000000000000000000000000000..f9a899dfcca8216df24445ec0c5281c930a33c23 --- /dev/null +++ b/node_modules/mapbox-gl/src/util/worker_pool.js @@ -0,0 +1,57 @@ +// @flow + +import WebWorker from './web_worker'; +import type {WorkerInterface} from './web_worker'; +import browser from './browser'; + +export const PRELOAD_POOL_ID = 'mapboxgl_preloaded_worker_pool'; + +/** + * Constructs a worker pool. + * @private + */ +export default class WorkerPool { + static workerCount: number; + + active: {[_: number | string]: boolean}; + workers: Array; + + constructor() { + this.active = {}; + } + + acquire(mapId: number | string): Array { + if (!this.workers) { + // Lazily look up the value of mapboxgl.workerCount so that + // client code has had a chance to set it. + this.workers = []; + while (this.workers.length < WorkerPool.workerCount) { + this.workers.push(new WebWorker()); + } + } + + this.active[mapId] = true; + return this.workers.slice(); + } + + release(mapId: number | string) { + delete this.active[mapId]; + if (this.numActive() === 0) { + this.workers.forEach((w) => { + w.terminate(); + }); + this.workers = (null: any); + } + } + + isPreloaded(): boolean { + return !!this.active[PRELOAD_POOL_ID]; + } + + numActive(): number { + return Object.keys(this.active).length; + } +} + +const availableLogicalProcessors = Math.floor(browser.hardwareConcurrency / 2); +WorkerPool.workerCount = Math.max(Math.min(availableLogicalProcessors, 6), 1); diff --git a/node_modules/math-intrinsics/.eslintrc b/node_modules/math-intrinsics/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..d90a1bc657a8c3b85c939c7b20e4ed4e4aba4ab0 --- /dev/null +++ b/node_modules/math-intrinsics/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "eqeqeq": ["error", "allow-null"], + "id-length": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "RequireObjectCoercible", + "ToObject", + ], + }], + }, +} diff --git a/node_modules/math-intrinsics/.github/FUNDING.yml b/node_modules/math-intrinsics/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..868f4ff4876eb4b02fd44c608e135cf6462895e2 --- /dev/null +++ b/node_modules/math-intrinsics/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/math-intrinsics +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/math-intrinsics/CHANGELOG.md b/node_modules/math-intrinsics/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..9cf48f5a1421c943f38a21bbf05efc249fb53a41 --- /dev/null +++ b/node_modules/math-intrinsics/CHANGELOG.md @@ -0,0 +1,24 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.0](https://github.com/es-shims/math-intrinsics/compare/v1.0.0...v1.1.0) - 2024-12-18 + +### Commits + +- [New] add `round` [`7cfb044`](https://github.com/es-shims/math-intrinsics/commit/7cfb04460c0fbdf1ca101eecbac3f59d11994130) +- [Tests] add attw [`e96be8f`](https://github.com/es-shims/math-intrinsics/commit/e96be8fbf58449eafe976446a0470e6ea561ad8d) +- [Dev Deps] update `@types/tape` [`30d0023`](https://github.com/es-shims/math-intrinsics/commit/30d00234ce8a3fa0094a61cd55d6686eb91e36ec) + +## v1.0.0 - 2024-12-11 + +### Commits + +- Initial implementation, tests, readme, types [`b898caa`](https://github.com/es-shims/math-intrinsics/commit/b898caae94e9994a94a42b8740f7bbcfd0a868fe) +- Initial commit [`02745b0`](https://github.com/es-shims/math-intrinsics/commit/02745b03a62255af8a332771987b55d127538d9c) +- [New] add `constants/maxArrayLength`, `mod` [`b978178`](https://github.com/es-shims/math-intrinsics/commit/b978178a57685bd23ed1c7efe2137f3784f5fcc5) +- npm init [`a39fc57`](https://github.com/es-shims/math-intrinsics/commit/a39fc57e5639a645d0bd52a0dc56202480223be2) +- Only apps should have lockfiles [`9451580`](https://github.com/es-shims/math-intrinsics/commit/94515800fb34db4f3cc7e99290042d45609ac7bd) diff --git a/node_modules/math-intrinsics/LICENSE b/node_modules/math-intrinsics/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..34995e79d1528aaceca7d38f323df52514ba7d0f --- /dev/null +++ b/node_modules/math-intrinsics/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 ECMAScript Shims + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/math-intrinsics/README.md b/node_modules/math-intrinsics/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4a66dcf24e0b17dce66d4742994e726e5c45439a --- /dev/null +++ b/node_modules/math-intrinsics/README.md @@ -0,0 +1,50 @@ +# math-intrinsics [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +ES Math-related intrinsics and helpers, robustly cached. + + - `abs` + - `floor` + - `isFinite` + - `isInteger` + - `isNaN` + - `isNegativeZero` + - `max` + - `min` + - `mod` + - `pow` + - `round` + - `sign` + - `constants/maxArrayLength` + - `constants/maxSafeInteger` + - `constants/maxValue` + + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/math-intrinsics +[npm-version-svg]: https://versionbadg.es/es-shims/math-intrinsics.svg +[deps-svg]: https://david-dm.org/es-shims/math-intrinsics.svg +[deps-url]: https://david-dm.org/es-shims/math-intrinsics +[dev-deps-svg]: https://david-dm.org/es-shims/math-intrinsics/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/math-intrinsics#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/math-intrinsics.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/math-intrinsics.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-object.svg +[downloads-url]: https://npm-stat.com/charts.html?package=math-intrinsics +[codecov-image]: https://codecov.io/gh/es-shims/math-intrinsics/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/es-shims/math-intrinsics/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/es-shims/math-intrinsics +[actions-url]: https://github.com/es-shims/math-intrinsics/actions diff --git a/node_modules/math-intrinsics/abs.d.ts b/node_modules/math-intrinsics/abs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..14ad9c699397bcc9818453c0b1b07996c1f6ee41 --- /dev/null +++ b/node_modules/math-intrinsics/abs.d.ts @@ -0,0 +1 @@ +export = Math.abs; \ No newline at end of file diff --git a/node_modules/math-intrinsics/abs.js b/node_modules/math-intrinsics/abs.js new file mode 100644 index 0000000000000000000000000000000000000000..a751424cdcdd37aab366b9ed966e1ed9651308f5 --- /dev/null +++ b/node_modules/math-intrinsics/abs.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./abs')} */ +module.exports = Math.abs; diff --git a/node_modules/math-intrinsics/constants/maxArrayLength.d.ts b/node_modules/math-intrinsics/constants/maxArrayLength.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b92d46be2cd3dc21c004f16a9196d2bccbba16cc --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxArrayLength.d.ts @@ -0,0 +1,3 @@ +declare const MAX_ARRAY_LENGTH: 4294967295; + +export = MAX_ARRAY_LENGTH; \ No newline at end of file diff --git a/node_modules/math-intrinsics/constants/maxArrayLength.js b/node_modules/math-intrinsics/constants/maxArrayLength.js new file mode 100644 index 0000000000000000000000000000000000000000..cfc6affd0ab67ba717dfd79219fdf32716d07d0e --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxArrayLength.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./maxArrayLength')} */ +module.exports = 4294967295; // Math.pow(2, 32) - 1; diff --git a/node_modules/math-intrinsics/constants/maxSafeInteger.d.ts b/node_modules/math-intrinsics/constants/maxSafeInteger.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fee3f621ed517b821371decc956f3fa83bd3a45c --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxSafeInteger.d.ts @@ -0,0 +1,3 @@ +declare const MAX_SAFE_INTEGER: 9007199254740991; + +export = MAX_SAFE_INTEGER; \ No newline at end of file diff --git a/node_modules/math-intrinsics/constants/maxSafeInteger.js b/node_modules/math-intrinsics/constants/maxSafeInteger.js new file mode 100644 index 0000000000000000000000000000000000000000..b568ad393bd22da735d31af78462946a86d720f8 --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxSafeInteger.js @@ -0,0 +1,5 @@ +'use strict'; + +/** @type {import('./maxSafeInteger')} */ +// eslint-disable-next-line no-extra-parens +module.exports = /** @type {import('./maxSafeInteger')} */ (Number.MAX_SAFE_INTEGER) || 9007199254740991; // Math.pow(2, 53) - 1; diff --git a/node_modules/math-intrinsics/constants/maxValue.d.ts b/node_modules/math-intrinsics/constants/maxValue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..292cb827153b6dd5483406bf937d78db8130fa0b --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxValue.d.ts @@ -0,0 +1,3 @@ +declare const MAX_VALUE: 1.7976931348623157e+308; + +export = MAX_VALUE; diff --git a/node_modules/math-intrinsics/constants/maxValue.js b/node_modules/math-intrinsics/constants/maxValue.js new file mode 100644 index 0000000000000000000000000000000000000000..a2202dc39767adad11f1df67b2ffabba8aaf9cbd --- /dev/null +++ b/node_modules/math-intrinsics/constants/maxValue.js @@ -0,0 +1,5 @@ +'use strict'; + +/** @type {import('./maxValue')} */ +// eslint-disable-next-line no-extra-parens +module.exports = /** @type {import('./maxValue')} */ (Number.MAX_VALUE) || 1.7976931348623157e+308; diff --git a/node_modules/math-intrinsics/floor.d.ts b/node_modules/math-intrinsics/floor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9265236f288b7da2345b73a3bc290a6385d2b356 --- /dev/null +++ b/node_modules/math-intrinsics/floor.d.ts @@ -0,0 +1 @@ +export = Math.floor; \ No newline at end of file diff --git a/node_modules/math-intrinsics/floor.js b/node_modules/math-intrinsics/floor.js new file mode 100644 index 0000000000000000000000000000000000000000..ab0e5d7dcd43056d5d5288de0d08ca4177efb2db --- /dev/null +++ b/node_modules/math-intrinsics/floor.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./floor')} */ +module.exports = Math.floor; diff --git a/node_modules/math-intrinsics/isFinite.d.ts b/node_modules/math-intrinsics/isFinite.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6daae331f18e427d1057c96c8ca75d6c6c3fd211 --- /dev/null +++ b/node_modules/math-intrinsics/isFinite.d.ts @@ -0,0 +1,3 @@ +declare function isFinite(x: unknown): x is number | bigint; + +export = isFinite; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isFinite.js b/node_modules/math-intrinsics/isFinite.js new file mode 100644 index 0000000000000000000000000000000000000000..b201a5a523ed18bde69edd3b3deff3b63c463120 --- /dev/null +++ b/node_modules/math-intrinsics/isFinite.js @@ -0,0 +1,12 @@ +'use strict'; + +var $isNaN = require('./isNaN'); + +/** @type {import('./isFinite')} */ +module.exports = function isFinite(x) { + return (typeof x === 'number' || typeof x === 'bigint') + && !$isNaN(x) + && x !== Infinity + && x !== -Infinity; +}; + diff --git a/node_modules/math-intrinsics/isInteger.d.ts b/node_modules/math-intrinsics/isInteger.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..13935a8ccf78a105bc508e4c8f88b9888f57f1b1 --- /dev/null +++ b/node_modules/math-intrinsics/isInteger.d.ts @@ -0,0 +1,3 @@ +declare function isInteger(argument: unknown): argument is number; + +export = isInteger; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isInteger.js b/node_modules/math-intrinsics/isInteger.js new file mode 100644 index 0000000000000000000000000000000000000000..4b1b9a56d1bba183cc75a616ece707489901d4a8 --- /dev/null +++ b/node_modules/math-intrinsics/isInteger.js @@ -0,0 +1,16 @@ +'use strict'; + +var $abs = require('./abs'); +var $floor = require('./floor'); + +var $isNaN = require('./isNaN'); +var $isFinite = require('./isFinite'); + +/** @type {import('./isInteger')} */ +module.exports = function isInteger(argument) { + if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) { + return false; + } + var absValue = $abs(argument); + return $floor(absValue) === absValue; +}; diff --git a/node_modules/math-intrinsics/isNaN.d.ts b/node_modules/math-intrinsics/isNaN.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c1d4c552456bde706a914f901e9ccd523ac44e7d --- /dev/null +++ b/node_modules/math-intrinsics/isNaN.d.ts @@ -0,0 +1 @@ +export = Number.isNaN; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isNaN.js b/node_modules/math-intrinsics/isNaN.js new file mode 100644 index 0000000000000000000000000000000000000000..e36475cf878ca6beda4dfd1cd3881759b72270c6 --- /dev/null +++ b/node_modules/math-intrinsics/isNaN.js @@ -0,0 +1,6 @@ +'use strict'; + +/** @type {import('./isNaN')} */ +module.exports = Number.isNaN || function isNaN(a) { + return a !== a; +}; diff --git a/node_modules/math-intrinsics/isNegativeZero.d.ts b/node_modules/math-intrinsics/isNegativeZero.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ad88193e1f3599ebce7e63ed97854895fe87f33 --- /dev/null +++ b/node_modules/math-intrinsics/isNegativeZero.d.ts @@ -0,0 +1,3 @@ +declare function isNegativeZero(x: unknown): boolean; + +export = isNegativeZero; \ No newline at end of file diff --git a/node_modules/math-intrinsics/isNegativeZero.js b/node_modules/math-intrinsics/isNegativeZero.js new file mode 100644 index 0000000000000000000000000000000000000000..b69adcc5a7f190f38c6907584432368e77d097d0 --- /dev/null +++ b/node_modules/math-intrinsics/isNegativeZero.js @@ -0,0 +1,6 @@ +'use strict'; + +/** @type {import('./isNegativeZero')} */ +module.exports = function isNegativeZero(x) { + return x === 0 && 1 / x === 1 / -0; +}; diff --git a/node_modules/math-intrinsics/max.d.ts b/node_modules/math-intrinsics/max.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad6f43e35f4a342bcac73ec92226b342f282097e --- /dev/null +++ b/node_modules/math-intrinsics/max.d.ts @@ -0,0 +1 @@ +export = Math.max; \ No newline at end of file diff --git a/node_modules/math-intrinsics/max.js b/node_modules/math-intrinsics/max.js new file mode 100644 index 0000000000000000000000000000000000000000..edb55dfbca86a881da139244122c4f734d6a5844 --- /dev/null +++ b/node_modules/math-intrinsics/max.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./max')} */ +module.exports = Math.max; diff --git a/node_modules/math-intrinsics/min.d.ts b/node_modules/math-intrinsics/min.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fd90f2d504422b14fbe14393fabdc0fc0a8db6a0 --- /dev/null +++ b/node_modules/math-intrinsics/min.d.ts @@ -0,0 +1 @@ +export = Math.min; \ No newline at end of file diff --git a/node_modules/math-intrinsics/min.js b/node_modules/math-intrinsics/min.js new file mode 100644 index 0000000000000000000000000000000000000000..5a4a7c7149a79f113c536e08888acc70213674e8 --- /dev/null +++ b/node_modules/math-intrinsics/min.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./min')} */ +module.exports = Math.min; diff --git a/node_modules/math-intrinsics/mod.d.ts b/node_modules/math-intrinsics/mod.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..549dbd46e5a4c1df5f6d75e11e690d6dc8758421 --- /dev/null +++ b/node_modules/math-intrinsics/mod.d.ts @@ -0,0 +1,3 @@ +declare function mod(number: number, modulo: number): number; + +export = mod; \ No newline at end of file diff --git a/node_modules/math-intrinsics/mod.js b/node_modules/math-intrinsics/mod.js new file mode 100644 index 0000000000000000000000000000000000000000..4a98362baf165d9190ab6bc7b627daeaad6fac8c --- /dev/null +++ b/node_modules/math-intrinsics/mod.js @@ -0,0 +1,9 @@ +'use strict'; + +var $floor = require('./floor'); + +/** @type {import('./mod')} */ +module.exports = function mod(number, modulo) { + var remain = number % modulo; + return $floor(remain >= 0 ? remain : remain + modulo); +}; diff --git a/node_modules/math-intrinsics/package.json b/node_modules/math-intrinsics/package.json new file mode 100644 index 0000000000000000000000000000000000000000..067627354b768e180e286f8c2efdb0c35a188e52 --- /dev/null +++ b/node_modules/math-intrinsics/package.json @@ -0,0 +1,86 @@ +{ + "name": "math-intrinsics", + "version": "1.1.0", + "description": "ES Math-related intrinsics and helpers, robustly cached.", + "main": false, + "exports": { + "./abs": "./abs.js", + "./floor": "./floor.js", + "./isFinite": "./isFinite.js", + "./isInteger": "./isInteger.js", + "./isNaN": "./isNaN.js", + "./isNegativeZero": "./isNegativeZero.js", + "./max": "./max.js", + "./min": "./min.js", + "./mod": "./mod.js", + "./pow": "./pow.js", + "./sign": "./sign.js", + "./round": "./round.js", + "./constants/maxArrayLength": "./constants/maxArrayLength.js", + "./constants/maxSafeInteger": "./constants/maxSafeInteger.js", + "./constants/maxValue": "./constants/maxValue.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "npx npm@'>= 10.2' audit --production", + "prelint": "evalmd README.md && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc && attw -P", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/es-shims/math-intrinsics.git" + }, + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/es-shims/math-intrinsics/issues" + }, + "homepage": "https://github.com/es-shims/math-intrinsics#readme", + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/for-each": "^0.3.3", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.8.0", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "es-value-fixtures": "^1.5.0", + "eslint": "^8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.3", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/math-intrinsics/pow.d.ts b/node_modules/math-intrinsics/pow.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5873c441e62a88335b478b30de3c2a319b945520 --- /dev/null +++ b/node_modules/math-intrinsics/pow.d.ts @@ -0,0 +1 @@ +export = Math.pow; \ No newline at end of file diff --git a/node_modules/math-intrinsics/pow.js b/node_modules/math-intrinsics/pow.js new file mode 100644 index 0000000000000000000000000000000000000000..c0a4103811f69cdfefb43e1fd0a5a866da3c0cd9 --- /dev/null +++ b/node_modules/math-intrinsics/pow.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./pow')} */ +module.exports = Math.pow; diff --git a/node_modules/math-intrinsics/round.d.ts b/node_modules/math-intrinsics/round.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..da1fde3f638b9a9a3db026668427ae9cde5bbcb7 --- /dev/null +++ b/node_modules/math-intrinsics/round.d.ts @@ -0,0 +1 @@ +export = Math.round; \ No newline at end of file diff --git a/node_modules/math-intrinsics/round.js b/node_modules/math-intrinsics/round.js new file mode 100644 index 0000000000000000000000000000000000000000..b79215663a657631fd01aef3d95dbffac635b707 --- /dev/null +++ b/node_modules/math-intrinsics/round.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./round')} */ +module.exports = Math.round; diff --git a/node_modules/math-intrinsics/sign.d.ts b/node_modules/math-intrinsics/sign.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c49cecaa240c415345f455f2e4fbed99015c1713 --- /dev/null +++ b/node_modules/math-intrinsics/sign.d.ts @@ -0,0 +1,3 @@ +declare function sign(x: number): number; + +export = sign; \ No newline at end of file diff --git a/node_modules/math-intrinsics/sign.js b/node_modules/math-intrinsics/sign.js new file mode 100644 index 0000000000000000000000000000000000000000..9e5173c80da67de620a9b3a769936d77bf68ba73 --- /dev/null +++ b/node_modules/math-intrinsics/sign.js @@ -0,0 +1,11 @@ +'use strict'; + +var $isNaN = require('./isNaN'); + +/** @type {import('./sign')} */ +module.exports = function sign(number) { + if ($isNaN(number) || number === 0) { + return number; + } + return number < 0 ? -1 : +1; +}; diff --git a/node_modules/math-intrinsics/test/index.js b/node_modules/math-intrinsics/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0f90a5dc0f5f107d65a4b8d3f79711b8b1d5a6f7 --- /dev/null +++ b/node_modules/math-intrinsics/test/index.js @@ -0,0 +1,192 @@ +'use strict'; + +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); +var inspect = require('object-inspect'); + +var abs = require('../abs'); +var floor = require('../floor'); +var isFinite = require('../isFinite'); +var isInteger = require('../isInteger'); +var isNaN = require('../isNaN'); +var isNegativeZero = require('../isNegativeZero'); +var max = require('../max'); +var min = require('../min'); +var mod = require('../mod'); +var pow = require('../pow'); +var round = require('../round'); +var sign = require('../sign'); + +var maxArrayLength = require('../constants/maxArrayLength'); +var maxSafeInteger = require('../constants/maxSafeInteger'); +var maxValue = require('../constants/maxValue'); + +test('abs', function (t) { + t.equal(abs(-1), 1, 'abs(-1) === 1'); + t.equal(abs(+1), 1, 'abs(+1) === 1'); + t.equal(abs(+0), +0, 'abs(+0) === +0'); + t.equal(abs(-0), +0, 'abs(-0) === +0'); + + t.end(); +}); + +test('floor', function (t) { + t.equal(floor(-1.1), -2, 'floor(-1.1) === -2'); + t.equal(floor(+1.1), 1, 'floor(+1.1) === 1'); + t.equal(floor(+0), +0, 'floor(+0) === +0'); + t.equal(floor(-0), -0, 'floor(-0) === -0'); + t.equal(floor(-Infinity), -Infinity, 'floor(-Infinity) === -Infinity'); + t.equal(floor(Number(Infinity)), Number(Infinity), 'floor(+Infinity) === +Infinity'); + t.equal(floor(NaN), NaN, 'floor(NaN) === NaN'); + t.equal(floor(0), +0, 'floor(0) === +0'); + t.equal(floor(-0), -0, 'floor(-0) === -0'); + t.equal(floor(1), 1, 'floor(1) === 1'); + t.equal(floor(-1), -1, 'floor(-1) === -1'); + t.equal(floor(1.1), 1, 'floor(1.1) === 1'); + t.equal(floor(-1.1), -2, 'floor(-1.1) === -2'); + t.equal(floor(maxValue), maxValue, 'floor(maxValue) === maxValue'); + t.equal(floor(maxSafeInteger), maxSafeInteger, 'floor(maxSafeInteger) === maxSafeInteger'); + + t.end(); +}); + +test('isFinite', function (t) { + t.equal(isFinite(0), true, 'isFinite(+0) === true'); + t.equal(isFinite(-0), true, 'isFinite(-0) === true'); + t.equal(isFinite(1), true, 'isFinite(1) === true'); + t.equal(isFinite(Infinity), false, 'isFinite(Infinity) === false'); + t.equal(isFinite(-Infinity), false, 'isFinite(-Infinity) === false'); + t.equal(isFinite(NaN), false, 'isFinite(NaN) === false'); + + forEach(v.nonNumbers, function (nonNumber) { + t.equal(isFinite(nonNumber), false, 'isFinite(' + inspect(nonNumber) + ') === false'); + }); + + t.end(); +}); + +test('isInteger', function (t) { + forEach([].concat( + // @ts-expect-error TS sucks with concat + v.nonNumbers, + v.nonIntegerNumbers + ), function (nonInteger) { + t.equal(isInteger(nonInteger), false, 'isInteger(' + inspect(nonInteger) + ') === false'); + }); + + t.end(); +}); + +test('isNaN', function (t) { + forEach([].concat( + // @ts-expect-error TS sucks with concat + v.nonNumbers, + v.infinities, + v.zeroes, + v.integerNumbers + ), function (nonNaN) { + t.equal(isNaN(nonNaN), false, 'isNaN(' + inspect(nonNaN) + ') === false'); + }); + + t.equal(isNaN(NaN), true, 'isNaN(NaN) === true'); + + t.end(); +}); + +test('isNegativeZero', function (t) { + t.equal(isNegativeZero(-0), true, 'isNegativeZero(-0) === true'); + t.equal(isNegativeZero(+0), false, 'isNegativeZero(+0) === false'); + t.equal(isNegativeZero(1), false, 'isNegativeZero(1) === false'); + t.equal(isNegativeZero(-1), false, 'isNegativeZero(-1) === false'); + t.equal(isNegativeZero(NaN), false, 'isNegativeZero(NaN) === false'); + t.equal(isNegativeZero(Infinity), false, 'isNegativeZero(Infinity) === false'); + t.equal(isNegativeZero(-Infinity), false, 'isNegativeZero(-Infinity) === false'); + + forEach(v.nonNumbers, function (nonNumber) { + t.equal(isNegativeZero(nonNumber), false, 'isNegativeZero(' + inspect(nonNumber) + ') === false'); + }); + + t.end(); +}); + +test('max', function (t) { + t.equal(max(1, 2), 2, 'max(1, 2) === 2'); + t.equal(max(1, 2, 3), 3, 'max(1, 2, 3) === 3'); + t.equal(max(1, 2, 3, 4), 4, 'max(1, 2, 3, 4) === 4'); + t.equal(max(1, 2, 3, 4, 5), 5, 'max(1, 2, 3, 4, 5) === 5'); + t.equal(max(1, 2, 3, 4, 5, 6), 6, 'max(1, 2, 3, 4, 5, 6) === 6'); + t.equal(max(1, 2, 3, 4, 5, 6, 7), 7, 'max(1, 2, 3, 4, 5, 6, 7) === 7'); + + t.end(); +}); + +test('min', function (t) { + t.equal(min(1, 2), 1, 'min(1, 2) === 1'); + t.equal(min(1, 2, 3), 1, 'min(1, 2, 3) === 1'); + t.equal(min(1, 2, 3, 4), 1, 'min(1, 2, 3, 4) === 1'); + t.equal(min(1, 2, 3, 4, 5), 1, 'min(1, 2, 3, 4, 5) === 1'); + t.equal(min(1, 2, 3, 4, 5, 6), 1, 'min(1, 2, 3, 4, 5, 6) === 1'); + + t.end(); +}); + +test('mod', function (t) { + t.equal(mod(1, 2), 1, 'mod(1, 2) === 1'); + t.equal(mod(2, 2), 0, 'mod(2, 2) === 0'); + t.equal(mod(3, 2), 1, 'mod(3, 2) === 1'); + t.equal(mod(4, 2), 0, 'mod(4, 2) === 0'); + t.equal(mod(5, 2), 1, 'mod(5, 2) === 1'); + t.equal(mod(6, 2), 0, 'mod(6, 2) === 0'); + t.equal(mod(7, 2), 1, 'mod(7, 2) === 1'); + t.equal(mod(8, 2), 0, 'mod(8, 2) === 0'); + t.equal(mod(9, 2), 1, 'mod(9, 2) === 1'); + t.equal(mod(10, 2), 0, 'mod(10, 2) === 0'); + t.equal(mod(11, 2), 1, 'mod(11, 2) === 1'); + + t.end(); +}); + +test('pow', function (t) { + t.equal(pow(2, 2), 4, 'pow(2, 2) === 4'); + t.equal(pow(2, 3), 8, 'pow(2, 3) === 8'); + t.equal(pow(2, 4), 16, 'pow(2, 4) === 16'); + t.equal(pow(2, 5), 32, 'pow(2, 5) === 32'); + t.equal(pow(2, 6), 64, 'pow(2, 6) === 64'); + t.equal(pow(2, 7), 128, 'pow(2, 7) === 128'); + t.equal(pow(2, 8), 256, 'pow(2, 8) === 256'); + t.equal(pow(2, 9), 512, 'pow(2, 9) === 512'); + t.equal(pow(2, 10), 1024, 'pow(2, 10) === 1024'); + + t.end(); +}); + +test('round', function (t) { + t.equal(round(1.1), 1, 'round(1.1) === 1'); + t.equal(round(1.5), 2, 'round(1.5) === 2'); + t.equal(round(1.9), 2, 'round(1.9) === 2'); + + t.end(); +}); + +test('sign', function (t) { + t.equal(sign(-1), -1, 'sign(-1) === -1'); + t.equal(sign(+1), +1, 'sign(+1) === +1'); + t.equal(sign(+0), +0, 'sign(+0) === +0'); + t.equal(sign(-0), -0, 'sign(-0) === -0'); + t.equal(sign(NaN), NaN, 'sign(NaN) === NaN'); + t.equal(sign(Infinity), +1, 'sign(Infinity) === +1'); + t.equal(sign(-Infinity), -1, 'sign(-Infinity) === -1'); + t.equal(sign(maxValue), +1, 'sign(maxValue) === +1'); + t.equal(sign(maxSafeInteger), +1, 'sign(maxSafeInteger) === +1'); + + t.end(); +}); + +test('constants', function (t) { + t.equal(typeof maxArrayLength, 'number', 'typeof maxArrayLength === "number"'); + t.equal(typeof maxSafeInteger, 'number', 'typeof maxSafeInteger === "number"'); + t.equal(typeof maxValue, 'number', 'typeof maxValue === "number"'); + + t.end(); +}); diff --git a/node_modules/math-intrinsics/tsconfig.json b/node_modules/math-intrinsics/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..b131000796f0cb804c38b121021940cd962cc1a7 --- /dev/null +++ b/node_modules/math-intrinsics/tsconfig.json @@ -0,0 +1,3 @@ +{ + "extends": "@ljharb/tsconfig", +} diff --git a/node_modules/math-log2/index.js b/node_modules/math-log2/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3b9541c90b7aa736a2ef359489daecf249c5c78a --- /dev/null +++ b/node_modules/math-log2/index.js @@ -0,0 +1,4 @@ +'use strict'; +module.exports = Math.log2 || function (x) { + return Math.log(x) * Math.LOG2E; +}; diff --git a/node_modules/math-log2/license b/node_modules/math-log2/license new file mode 100644 index 0000000000000000000000000000000000000000..654d0bfe943437d43242325b1fbcff5f400d84ee --- /dev/null +++ b/node_modules/math-log2/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/math-log2/package.json b/node_modules/math-log2/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8d0bff764d5ef43fa99322ff6e856c794073a659 --- /dev/null +++ b/node_modules/math-log2/package.json @@ -0,0 +1,38 @@ +{ + "name": "math-log2", + "version": "1.0.1", + "description": "ES2015 Math.log2() ponyfill", + "license": "MIT", + "repository": "sindresorhus/math-log2", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "es2015", + "ponyfill", + "polyfill", + "shim", + "number", + "math", + "log2", + "log", + "logarithm" + ], + "devDependencies": { + "ava": "*", + "float-equal": "^1.0.0", + "number-is-nan": "^1.0.0", + "positive-zero": "^1.0.0" + } +} diff --git a/node_modules/math-log2/readme.md b/node_modules/math-log2/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..1de7c3cdaec4d2cc13ada80945c73963a09d94c2 --- /dev/null +++ b/node_modules/math-log2/readme.md @@ -0,0 +1,25 @@ +# math-log2 [![Build Status](https://travis-ci.org/sindresorhus/math-log2.svg?branch=master)](https://travis-ci.org/sindresorhus/math-log2) + +> ES2015 [`Math.log2()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log2) [ponyfill](https://ponyfill.com) + + +## Install + +``` +$ npm install --save math-log2 +``` + + +## Usage + +```js +var mathLog2 = require('math-log2'); + +mathLog2(5); +//=> 2.321928094887362 +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/md5.js/LICENSE b/node_modules/md5.js/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6f02ae800b5bf0b5bf394f717a6f56d6f6ecd186 --- /dev/null +++ b/node_modules/md5.js/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Kirill Fomichev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/md5.js/README.md b/node_modules/md5.js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..36316e1b39672790312ab0ece6605114750c5551 --- /dev/null +++ b/node_modules/md5.js/README.md @@ -0,0 +1,29 @@ +# md5.js + +[![NPM Package](https://img.shields.io/npm/v/md5.js.svg?style=flat-square)](https://www.npmjs.org/package/md5.js) +[![Build Status](https://img.shields.io/travis/crypto-browserify/md5.js.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/md5.js) +[![Dependency status](https://img.shields.io/david/crypto-browserify/md5.js.svg?style=flat-square)](https://david-dm.org/crypto-browserify/md5.js#info=dependencies) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +Node style `md5` on pure JavaScript. + +From [NIST SP 800-131A][1]: *md5 is no longer acceptable where collision resistance is required such as digital signatures.* + +## Example + +```js +var MD5 = require('md5.js') + +console.log(new MD5().update('42').digest('hex')) +// => a1d0c6e83f027327d8461063f4ac58a6 + +var md5stream = new MD5() +md5stream.end('42') +console.log(md5stream.read().toString('hex')) +// => a1d0c6e83f027327d8461063f4ac58a6 +``` + +## LICENSE [MIT](LICENSE) + +[1]: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf diff --git a/node_modules/md5.js/index.js b/node_modules/md5.js/index.js new file mode 100644 index 0000000000000000000000000000000000000000..cbfa2e3786fb1d3eeab468527346483485be8185 --- /dev/null +++ b/node_modules/md5.js/index.js @@ -0,0 +1,146 @@ +'use strict' +var inherits = require('inherits') +var HashBase = require('hash-base') +var Buffer = require('safe-buffer').Buffer + +var ARRAY16 = new Array(16) + +function MD5 () { + HashBase.call(this, 64) + + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 +} + +inherits(MD5, HashBase) + +MD5.prototype._update = function () { + var M = ARRAY16 + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4) + + var a = this._a + var b = this._b + var c = this._c + var d = this._d + + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7) + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12) + c = fnF(c, d, a, b, M[2], 0x242070db, 17) + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) + c = fnF(c, d, a, b, M[6], 0xa8304613, 17) + b = fnF(b, c, d, a, M[7], 0xfd469501, 22) + a = fnF(a, b, c, d, M[8], 0x698098d8, 7) + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) + a = fnF(a, b, c, d, M[12], 0x6b901122, 7) + d = fnF(d, a, b, c, M[13], 0xfd987193, 12) + c = fnF(c, d, a, b, M[14], 0xa679438e, 17) + b = fnF(b, c, d, a, M[15], 0x49b40821, 22) + + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) + d = fnG(d, a, b, c, M[6], 0xc040b340, 9) + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) + d = fnG(d, a, b, c, M[10], 0x02441453, 9) + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) + + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) + d = fnH(d, a, b, c, M[8], 0x8771f681, 11) + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) + b = fnH(b, c, d, a, M[6], 0x04881d05, 23) + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) + + a = fnI(a, b, c, d, M[0], 0xf4292244, 6) + d = fnI(d, a, b, c, M[7], 0x432aff97, 10) + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) + c = fnI(c, d, a, b, M[6], 0xa3014314, 15) + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) + + this._a = (this._a + a) | 0 + this._b = (this._b + b) | 0 + this._c = (this._c + c) | 0 + this._d = (this._d + d) | 0 +} + +MD5.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = Buffer.allocUnsafe(16) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + return buffer +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function fnF (a, b, c, d, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 +} + +function fnG (a, b, c, d, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 +} + +function fnH (a, b, c, d, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 +} + +function fnI (a, b, c, d, m, k, s) { + return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 +} + +module.exports = MD5 diff --git a/node_modules/md5.js/package.json b/node_modules/md5.js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e12e3c72b8bbd6c0506d692575ea226570858e6a --- /dev/null +++ b/node_modules/md5.js/package.json @@ -0,0 +1,38 @@ +{ + "name": "md5.js", + "version": "1.3.5", + "description": "node style md5 on pure JavaScript", + "keywords": [ + "crypto", + "md5" + ], + "homepage": "https://github.com/crypto-browserify/md5.js", + "bugs": { + "url": "https://github.com/crypto-browserify/md5.js/issues" + }, + "license": "MIT", + "author": "Kirill Fomichev (https://github.com/fanatid)", + "files": [ + "index.js" + ], + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/crypto-browserify/md5.js.git" + }, + "scripts": { + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "node test/*.js" + }, + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + }, + "devDependencies": { + "hash-test-vectors": "^1.3.2", + "standard": "^7.0.0", + "tape": "^4.2.0" + } +} diff --git a/node_modules/media-typer/HISTORY.md b/node_modules/media-typer/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..538ade14fa848dcce1b5b839ced17f5817fcd5ff --- /dev/null +++ b/node_modules/media-typer/HISTORY.md @@ -0,0 +1,50 @@ +1.1.0 / 2019-04-24 +================== + + * Add `test(string)` function + +1.0.2 / 2019-04-19 +================== + + * Fix JSDoc comment for `parse` function + +1.0.1 / 2018-10-20 +================== + + * Remove left over `parameters` property from class + +1.0.0 / 2018-10-20 +================== + +This major release brings the module back to it's RFC 6838 roots. If you want +a module to parse the `Content-Type` or similar HTTP headers, use the +`content-type` module instead. + + * Drop support for Node.js below 0.8 + * Remove parameter handling, which is outside RFC 6838 scope + * Remove `parse(req)` and `parse(res)` signatures + * perf: enable strict mode + * perf: use a class for object creation + +0.3.0 / 2014-09-07 +================== + + * Support Node.js 0.6 + * Throw error when parameter format invalid on parse + +0.2.0 / 2014-06-18 +================== + + * Add `typer.format()` to format media types + +0.1.0 / 2014-06-17 +================== + + * Accept `req` as argument to `parse` + * Accept `res` as argument to `parse` + * Parse media type with extra LWS between type and first parameter + +0.0.0 / 2014-06-13 +================== + + * Initial implementation diff --git a/node_modules/media-typer/LICENSE b/node_modules/media-typer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..84441fbb5709262c2bfc9b5ff0166ad4f024a1b8 --- /dev/null +++ b/node_modules/media-typer/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/media-typer/README.md b/node_modules/media-typer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..37edad16f5aca0263d8350f3654cf1f04a5c32cf --- /dev/null +++ b/node_modules/media-typer/README.md @@ -0,0 +1,93 @@ +# media-typer + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Simple RFC 6838 media type parser. + +This module will parse a given media type into it's component parts, like type, +subtype, and suffix. A formatter is also provided to put them back together and +the two can be combined to normalize media types into a canonical form. + +If you are looking to parse the string that represents a media type and it's +parameters in HTTP (for example, the `Content-Type` header), use the +[content-type module](https://www.npmjs.com/package/content-type). + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install media-typer +``` + +## API + + + +```js +var typer = require('media-typer') +``` + +### typer.parse(string) + + + +```js +var obj = typer.parse('image/svg+xml') +``` + +Parse a media type string. This will return an object with the following +properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The type of the media type (always lower case). Example: `'image'` + + - `subtype`: The subtype of the media type (always lower case). Example: `'svg'` + + - `suffix`: The suffix of the media type (always lower case). Example: `'xml'` + +If the given type string is invalid, then a `TypeError` is thrown. + +### typer.format(obj) + + + +```js +var obj = typer.format({ type: 'image', subtype: 'svg', suffix: 'xml' }) +``` + +Format an object into a media type string. This will return a string of the +mime type for the given object. For the properties of the object, see the +documentation for `typer.parse(string)`. + +If any of the given object values are invalid, then a `TypeError` is thrown. + +### typer.test(string) + + + +```js +var valid = typer.test('image/svg+xml') +``` + +Validate a media type string. This will return `true` is the string is a well- +formatted media type, or `false` otherwise. + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/media-typer/master +[coveralls-url]: https://coveralls.io/r/jshttp/media-typer?branch=master +[node-version-image]: https://badgen.net/npm/node/media-typer +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/media-typer +[npm-url]: https://npmjs.org/package/media-typer +[npm-version-image]: https://badgen.net/npm/v/media-typer +[travis-image]: https://badgen.net/travis/jshttp/media-typer/master +[travis-url]: https://travis-ci.org/jshttp/media-typer diff --git a/node_modules/media-typer/index.js b/node_modules/media-typer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..897cae1570efe9b622229f15e07fe45fe8284350 --- /dev/null +++ b/node_modules/media-typer/index.js @@ -0,0 +1,143 @@ +/*! + * media-typer + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to match type in RFC 6838 + * + * type-name = restricted-name + * subtype-name = restricted-name + * restricted-name = restricted-name-first *126restricted-name-chars + * restricted-name-first = ALPHA / DIGIT + * restricted-name-chars = ALPHA / DIGIT / "!" / "#" / + * "$" / "&" / "-" / "^" / "_" + * restricted-name-chars =/ "." ; Characters before first dot always + * ; specify a facet name + * restricted-name-chars =/ "+" ; Characters after last plus always + * ; specify a structured syntax suffix + * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z + * DIGIT = %x30-39 ; 0-9 + */ +var SUBTYPE_NAME_REGEXP = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/ +var TYPE_NAME_REGEXP = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/ +var TYPE_REGEXP = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/ + +/** + * Module exports. + */ + +exports.format = format +exports.parse = parse +exports.test = test + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var subtype = obj.subtype + var suffix = obj.suffix + var type = obj.type + + if (!type || !TYPE_NAME_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + if (!subtype || !SUBTYPE_NAME_REGEXP.test(subtype)) { + throw new TypeError('invalid subtype') + } + + // format as type/subtype + var string = type + '/' + subtype + + // append +suffix + if (suffix) { + if (!TYPE_NAME_REGEXP.test(suffix)) { + throw new TypeError('invalid suffix') + } + + string += '+' + suffix + } + + return string +} + +/** + * Test media type. + * + * @param {string} string + * @return {object} + * @public + */ + +function test (string) { + if (!string) { + throw new TypeError('argument string is required') + } + + if (typeof string !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + return TYPE_REGEXP.test(string.toLowerCase()) +} + +/** + * Parse media type to object. + * + * @param {string} string + * @return {object} + * @public + */ + +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } + + if (typeof string !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var match = TYPE_REGEXP.exec(string.toLowerCase()) + + if (!match) { + throw new TypeError('invalid media type') + } + + var type = match[1] + var subtype = match[2] + var suffix + + // suffix after last + + var index = subtype.lastIndexOf('+') + if (index !== -1) { + suffix = subtype.substr(index + 1) + subtype = subtype.substr(0, index) + } + + return new MediaType(type, subtype, suffix) +} + +/** + * Class for MediaType object. + * @public + */ + +function MediaType (type, subtype, suffix) { + this.type = type + this.subtype = subtype + this.suffix = suffix +} diff --git a/node_modules/media-typer/package.json b/node_modules/media-typer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1dca712ee162c2ae9cb7ee3011948018c845ca39 --- /dev/null +++ b/node_modules/media-typer/package.json @@ -0,0 +1,33 @@ +{ + "name": "media-typer", + "description": "Simple RFC 6838 media type parser and formatter", + "version": "1.1.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "jshttp/media-typer", + "devDependencies": { + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "mocha": "6.1.4", + "nyc": "14.0.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-travis": "nyc --reporter=text npm test" + } +} diff --git a/node_modules/merge-descriptors/index.d.ts b/node_modules/merge-descriptors/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..df8f91f445b1ef0be11552801e36bf5eedea8910 --- /dev/null +++ b/node_modules/merge-descriptors/index.d.ts @@ -0,0 +1,11 @@ +/** +Merges "own" properties from a source to a destination object, including non-enumerable and accessor-defined properties. It retains original values and descriptors, ensuring the destination receives a complete and accurate copy of the source's properties. + +@param destination - The object to receive properties. +@param source - The object providing properties. +@param overwrite - Optional boolean to control overwriting of existing properties. Defaults to true. +@returns The modified destination object. +*/ +declare function mergeDescriptors(destination: T, source: U, overwrite?: boolean): T & U; + +export = mergeDescriptors; diff --git a/node_modules/merge-descriptors/index.js b/node_modules/merge-descriptors/index.js new file mode 100644 index 0000000000000000000000000000000000000000..51228e5cecc2929c27b40f855a6f4eb4fb9baf7b --- /dev/null +++ b/node_modules/merge-descriptors/index.js @@ -0,0 +1,26 @@ +'use strict'; + +function mergeDescriptors(destination, source, overwrite = true) { + if (!destination) { + throw new TypeError('The `destination` argument is required.'); + } + + if (!source) { + throw new TypeError('The `source` argument is required.'); + } + + for (const name of Object.getOwnPropertyNames(source)) { + if (!overwrite && Object.hasOwn(destination, name)) { + // Skip descriptor + continue; + } + + // Copy descriptor + const descriptor = Object.getOwnPropertyDescriptor(source, name); + Object.defineProperty(destination, name, descriptor); + } + + return destination; +} + +module.exports = mergeDescriptors; diff --git a/node_modules/merge-descriptors/license b/node_modules/merge-descriptors/license new file mode 100644 index 0000000000000000000000000000000000000000..c509d4557c0d11a3f7ea08d5e4ff0c77ff91f4cf --- /dev/null +++ b/node_modules/merge-descriptors/license @@ -0,0 +1,11 @@ +MIT License + +Copyright (c) Jonathan Ong +Copyright (c) Douglas Christopher Wilson +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/merge-descriptors/package.json b/node_modules/merge-descriptors/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9bedb250ba6f5976c708674d9d6b539e7ff3050e --- /dev/null +++ b/node_modules/merge-descriptors/package.json @@ -0,0 +1,50 @@ +{ + "name": "merge-descriptors", + "version": "2.0.0", + "description": "Merge objects using their property descriptors", + "license": "MIT", + "repository": "sindresorhus/merge-descriptors", + "funding": "https://github.com/sponsors/sindresorhus", + "contributors": [ + "Jonathan Ong ", + "Douglas Christopher Wilson ", + "Mike Grabowski ", + "Sindre Sorhus " + ], + "exports": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "main": "./index.js", + "types": "./index.d.ts", + "sideEffects": false, + "engines": { + "node": ">=18" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "merge", + "descriptors", + "object", + "property", + "properties", + "merging", + "getter", + "setter" + ], + "devDependencies": { + "ava": "^5.3.1", + "xo": "^0.56.0" + }, + "xo": { + "rules": { + "unicorn/prefer-module": "off" + } + } +} diff --git a/node_modules/merge-descriptors/readme.md b/node_modules/merge-descriptors/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..1dee67d843668d895d55ed100debc2a1b36254e6 --- /dev/null +++ b/node_modules/merge-descriptors/readme.md @@ -0,0 +1,55 @@ +# merge-descriptors + +> Merge objects using their property descriptors + +## Install + +```sh +npm install merge-descriptors +``` + +## Usage + +```js +import mergeDescriptors from 'merge-descriptors'; + +const thing = { + get name() { + return 'John' + } +} + +const animal = {}; + +mergeDescriptors(animal, thing); + +console.log(animal.name); +//=> 'John' +``` + +## API + +### merge(destination, source, overwrite?) + +Merges "own" properties from a source to a destination object, including non-enumerable and accessor-defined properties. It retains original values and descriptors, ensuring the destination receives a complete and accurate copy of the source's properties. + +Returns the modified destination object. + +#### destination + +Type: `object` + +The object to receive properties. + +#### source + +Type: `object` + +The object providing properties. + +#### overwrite + +Type: `boolean`\ +Default: `true` + +A boolean to control overwriting of existing properties. diff --git a/node_modules/miller-rabin/.npmignore b/node_modules/miller-rabin/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..1ca957177f035203810612d1d93a66b08caff296 --- /dev/null +++ b/node_modules/miller-rabin/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +npm-debug.log diff --git a/node_modules/miller-rabin/1.js b/node_modules/miller-rabin/1.js new file mode 100644 index 0000000000000000000000000000000000000000..92953789e90df5c470f63599511bfdd2979f2f3c --- /dev/null +++ b/node_modules/miller-rabin/1.js @@ -0,0 +1,7 @@ +'use strict'; + +const BN = require('bn.js'); + +const p = new BN('2e1b162f326430f5ac6af10f96b2a8350e01675d22324c9f', 'hex'); + +console.log(p.bitLength()); diff --git a/node_modules/miller-rabin/README.md b/node_modules/miller-rabin/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e9d76f67c436655f8a9d53b1e2e634008fc74f38 --- /dev/null +++ b/node_modules/miller-rabin/README.md @@ -0,0 +1,26 @@ +# Miller-Rabin + +#### LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2014. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/miller-rabin/bin/miller-rabin b/node_modules/miller-rabin/bin/miller-rabin new file mode 100644 index 0000000000000000000000000000000000000000..2e18dfd53eaf41eba6d0acd607e95e5e181a3296 --- /dev/null +++ b/node_modules/miller-rabin/bin/miller-rabin @@ -0,0 +1,29 @@ +#!/usr/bin/env node +var bn = require('bn.js'); +var fs = require('fs'); +var mr = require('../').create(); + +var num = ''; +if (process.argv[2]) { + num += fs.readFileSync(process.argv[2]); + start(num); +} else { + process.stdin.on('data', function(chunk) { + num += chunk.toString().replace(/[^0-9a-f]/gi, ''); + }); + process.stdin.once('end', function() { + start(num); + }); +} + +function start(text) { + var num = new bn(text, 16); + + var divisor = mr.getDivisor(num); + if (!divisor) + process.exit(1); + if (divisor.cmpn(1) === 0) + process.exit(0); + + console.log(divisor.toString(16)); +} diff --git a/node_modules/miller-rabin/lib/mr.js b/node_modules/miller-rabin/lib/mr.js new file mode 100644 index 0000000000000000000000000000000000000000..60d2a8ef97de3f722e5ea079b546ea14925e2977 --- /dev/null +++ b/node_modules/miller-rabin/lib/mr.js @@ -0,0 +1,115 @@ +var bn = require('bn.js'); +var brorand = require('brorand'); + +function MillerRabin(rand) { + this.rand = rand || new brorand.Rand(); +} +module.exports = MillerRabin; + +MillerRabin.create = function create(rand) { + return new MillerRabin(rand); +}; + +MillerRabin.prototype._randbelow = function _randbelow(n) { + var len = n.bitLength(); + var min_bytes = Math.ceil(len / 8); + + // Generage random bytes until a number less than n is found. + // This ensures that 0..n-1 have an equal probability of being selected. + do + var a = new bn(this.rand.generate(min_bytes)); + while (a.cmp(n) >= 0); + + return a; +}; + +MillerRabin.prototype._randrange = function _randrange(start, stop) { + // Generate a random number greater than or equal to start and less than stop. + var size = stop.sub(start); + return start.add(this._randbelow(size)); +}; + +MillerRabin.prototype.test = function test(n, k, cb) { + var len = n.bitLength(); + var red = bn.mont(n); + var rone = new bn(1).toRed(red); + + if (!k) + k = Math.max(1, (len / 48) | 0); + + // Find d and s, (n - 1) = (2 ^ s) * d; + var n1 = n.subn(1); + for (var s = 0; !n1.testn(s); s++) {} + var d = n.shrn(s); + + var rn1 = n1.toRed(red); + + var prime = true; + for (; k > 0; k--) { + var a = this._randrange(new bn(2), n1); + if (cb) + cb(a); + + var x = a.toRed(red).redPow(d); + if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) + continue; + + for (var i = 1; i < s; i++) { + x = x.redSqr(); + + if (x.cmp(rone) === 0) + return false; + if (x.cmp(rn1) === 0) + break; + } + + if (i === s) + return false; + } + + return prime; +}; + +MillerRabin.prototype.getDivisor = function getDivisor(n, k) { + var len = n.bitLength(); + var red = bn.mont(n); + var rone = new bn(1).toRed(red); + + if (!k) + k = Math.max(1, (len / 48) | 0); + + // Find d and s, (n - 1) = (2 ^ s) * d; + var n1 = n.subn(1); + for (var s = 0; !n1.testn(s); s++) {} + var d = n.shrn(s); + + var rn1 = n1.toRed(red); + + for (; k > 0; k--) { + var a = this._randrange(new bn(2), n1); + + var g = n.gcd(a); + if (g.cmpn(1) !== 0) + return g; + + var x = a.toRed(red).redPow(d); + if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) + continue; + + for (var i = 1; i < s; i++) { + x = x.redSqr(); + + if (x.cmp(rone) === 0) + return x.fromRed().subn(1).gcd(n); + if (x.cmp(rn1) === 0) + break; + } + + if (i === s) { + x = x.redSqr(); + return x.fromRed().subn(1).gcd(n); + } + } + + return false; +}; diff --git a/node_modules/miller-rabin/node_modules/bn.js/LICENSE b/node_modules/miller-rabin/node_modules/bn.js/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c328f0401e39c6ead737353c80d7356b86108e83 --- /dev/null +++ b/node_modules/miller-rabin/node_modules/bn.js/LICENSE @@ -0,0 +1,19 @@ +Copyright Fedor Indutny, 2015. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/miller-rabin/node_modules/bn.js/README.md b/node_modules/miller-rabin/node_modules/bn.js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..aecc3ba0fd0e27aac66909d0fb6eb714819535ed --- /dev/null +++ b/node_modules/miller-rabin/node_modules/bn.js/README.md @@ -0,0 +1,200 @@ +# bn.js + +> BigNum in pure javascript + +[![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) + +## Install +`npm install --save bn.js` + +## Usage + +```js +const BN = require('bn.js'); + +var a = new BN('dead', 16); +var b = new BN('101010', 2); + +var res = a.add(b); +console.log(res.toString(10)); // 57047 +``` + +**Note**: decimals are not supported in this library. + +## Notation + +### Prefixes + +There are several prefixes to instructions that affect the way the work. Here +is the list of them in the order of appearance in the function name: + +* `i` - perform operation in-place, storing the result in the host object (on + which the method was invoked). Might be used to avoid number allocation costs +* `u` - unsigned, ignore the sign of operands when performing operation, or + always return positive value. Second case applies to reduction operations + like `mod()`. In such cases if the result will be negative - modulo will be + added to the result to make it positive + +### Postfixes + +The only available postfix at the moment is: + +* `n` - which means that the argument of the function must be a plain JavaScript + Number. Decimals are not supported. + +### Examples + +* `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` +* `a.umod(b)` - reduce `a` modulo `b`, returning positive value +* `a.iushln(13)` - shift bits of `a` left by 13 + +## Instructions + +Prefixes/postfixes are put in parens at the of the line. `endian` - could be +either `le` (little-endian) or `be` (big-endian). + +### Utilities + +* `a.clone()` - clone number +* `a.toString(base, length)` - convert to base-string and pad with zeroes +* `a.toNumber()` - convert to Javascript Number (limited to 53 bits) +* `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) +* `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero + pad to length, throwing if already exceeding +* `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, + which must behave like an `Array` +* `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For + compatibility with browserify and similar tools, use this instead: + `a.toArrayLike(Buffer, endian, length)` +* `a.bitLength()` - get number of bits occupied +* `a.zeroBits()` - return number of less-significant consequent zero bits + (example: `1010000` has 4 zero bits) +* `a.byteLength()` - return number of bytes occupied +* `a.isNeg()` - true if the number is negative +* `a.isEven()` - no comments +* `a.isOdd()` - no comments +* `a.isZero()` - no comments +* `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) + depending on the comparison result (`ucmp`, `cmpn`) +* `a.lt(b)` - `a` less than `b` (`n`) +* `a.lte(b)` - `a` less than or equals `b` (`n`) +* `a.gt(b)` - `a` greater than `b` (`n`) +* `a.gte(b)` - `a` greater than or equals `b` (`n`) +* `a.eq(b)` - `a` equals `b` (`n`) +* `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width +* `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width +* `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance + +### Arithmetics + +* `a.neg()` - negate sign (`i`) +* `a.abs()` - absolute value (`i`) +* `a.add(b)` - addition (`i`, `n`, `in`) +* `a.sub(b)` - subtraction (`i`, `n`, `in`) +* `a.mul(b)` - multiply (`i`, `n`, `in`) +* `a.sqr()` - square (`i`) +* `a.pow(b)` - raise `a` to the power of `b` +* `a.div(b)` - divide (`divn`, `idivn`) +* `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) +* `a.divRound(b)` - rounded division + +### Bit operations + +* `a.or(b)` - or (`i`, `u`, `iu`) +* `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced + with `andn` in future) +* `a.xor(b)` - xor (`i`, `u`, `iu`) +* `a.setn(b)` - set specified bit to `1` +* `a.shln(b)` - shift left (`i`, `u`, `iu`) +* `a.shrn(b)` - shift right (`i`, `u`, `iu`) +* `a.testn(b)` - test if specified bit is set +* `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) +* `a.bincn(b)` - add `1 << b` to the number +* `a.notn(w)` - not (for the width specified by `w`) (`i`) + +### Reduction + +* `a.gcd(b)` - GCD +* `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) +* `a.invm(b)` - inverse `a` modulo `b` + +## Fast reduction + +When doing lots of reductions using the same modulo, it might be beneficial to +use some tricks: like [Montgomery multiplication][0], or using special algorithm +for [Mersenne Prime][1]. + +### Reduction context + +To enable this tricks one should create a reduction context: + +```js +var red = BN.red(num); +``` +where `num` is just a BN instance. + +Or: + +```js +var red = BN.red(primeName); +``` + +Where `primeName` is either of these [Mersenne Primes][1]: + +* `'k256'` +* `'p224'` +* `'p192'` +* `'p25519'` + +Or: + +```js +var red = BN.mont(num); +``` + +To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than +`.red(num)`, but slower than `BN.red(primeName)`. + +### Converting numbers + +Before performing anything in reduction context - numbers should be converted +to it. Usually, this means that one should: + +* Convert inputs to reducted ones +* Operate on them in reduction context +* Convert outputs back from the reduction context + +Here is how one may convert numbers to `red`: + +```js +var redA = a.toRed(red); +``` +Where `red` is a reduction context created using instructions above + +Here is how to convert them back: + +```js +var a = redA.fromRed(); +``` + +### Red instructions + +Most of the instructions from the very start of this readme have their +counterparts in red context: + +* `a.redAdd(b)`, `a.redIAdd(b)` +* `a.redSub(b)`, `a.redISub(b)` +* `a.redShl(num)` +* `a.redMul(b)`, `a.redIMul(b)` +* `a.redSqr()`, `a.redISqr()` +* `a.redSqrt()` - square root modulo reduction context's prime +* `a.redInvm()` - modular inverse of the number +* `a.redNeg()` +* `a.redPow(b)` - modular exponentiation + +## LICENSE + +This software is licensed under the MIT License. + +[0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication +[1]: https://en.wikipedia.org/wiki/Mersenne_prime diff --git a/node_modules/miller-rabin/node_modules/bn.js/lib/bn.js b/node_modules/miller-rabin/node_modules/bn.js/lib/bn.js new file mode 100644 index 0000000000000000000000000000000000000000..9f67ecfac1a4dc88577332d3374859f2354a1f90 --- /dev/null +++ b/node_modules/miller-rabin/node_modules/bn.js/lib/bn.js @@ -0,0 +1,3452 @@ +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = require('buffer').Buffer; + } + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } + + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } + } + } + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex4Bits (string, index) { + var c = string.charCodeAt(index); + // 'A' - 'F' + if (c >= 65 && c <= 70) { + return c - 55; + // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + // '0' - '9' + } else { + return (c - 48) & 0xf; + } + } + + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + // 24-bits chunks + var off = 0; + var j = 0; + + var w; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + this.strip(); + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + this.length = num === 0 ? 1 : this.length; + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is BN v4 instance + r.strip(); + } else { + // r is BN v5 instance + r._strip(); + } + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})(typeof module === 'undefined' || module, this); diff --git a/node_modules/miller-rabin/node_modules/bn.js/package.json b/node_modules/miller-rabin/node_modules/bn.js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dc35ff22082b467dd143895b29447918746c5dba --- /dev/null +++ b/node_modules/miller-rabin/node_modules/bn.js/package.json @@ -0,0 +1,36 @@ +{ + "name": "bn.js", + "version": "4.12.3", + "description": "Big number implementation in pure javascript", + "main": "lib/bn.js", + "scripts": { + "lint": "semistandard", + "unit": "mocha --reporter=spec test/*-test.js", + "test": "npm run lint && npm run unit" + }, + "repository": { + "type": "git", + "url": "git@github.com:indutny/bn.js" + }, + "keywords": [ + "BN", + "BigNum", + "Big number", + "Modulo", + "Montgomery" + ], + "author": "Fedor Indutny ", + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/bn.js/issues" + }, + "homepage": "https://github.com/indutny/bn.js", + "browser": { + "buffer": false + }, + "devDependencies": { + "istanbul": "^0.3.5", + "mocha": "^2.1.0", + "semistandard": "^7.0.4" + } +} diff --git a/node_modules/miller-rabin/node_modules/bn.js/util/genCombMulTo.js b/node_modules/miller-rabin/node_modules/bn.js/util/genCombMulTo.js new file mode 100644 index 0000000000000000000000000000000000000000..8b456c7c61541005f3305f764f8599f190075166 --- /dev/null +++ b/node_modules/miller-rabin/node_modules/bn.js/util/genCombMulTo.js @@ -0,0 +1,65 @@ +'use strict'; + +// NOTE: This could be potentionally used to generate loop-less multiplications +function genCombMulTo (alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = self.words;', + 'var b = num.words;', + 'var o = out.words;', + 'var c = 0;', + 'var lo;', + 'var mid;', + 'var hi;' + ]; + for (var i = 0; i < alen; i++) { + src.push('var a' + i + ' = a[' + i + '] | 0;'); + src.push('var al' + i + ' = a' + i + ' & 0x1fff;'); + src.push('var ah' + i + ' = a' + i + ' >>> 13;'); + } + for (i = 0; i < blen; i++) { + src.push('var b' + i + ' = b[' + i + '] | 0;'); + src.push('var bl' + i + ' = b' + i + ' & 0x1fff;'); + src.push('var bh' + i + ' = b' + i + ' >>> 13;'); + } + src.push(''); + src.push('out.negative = self.negative ^ num.negative;'); + src.push('out.length = ' + len + ';'); + + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + src.push('\/* k = ' + k + ' *\/'); + src.push('var w' + k + ' = c;'); + src.push('c = 0;'); + for (var j = minJ; j <= maxJ; j++) { + i = k - j; + + src.push('lo = Math.imul(al' + i + ', bl' + j + ');'); + src.push('mid = Math.imul(al' + i + ', bh' + j + ');'); + src.push('mid = (mid + Math.imul(ah' + i + ', bl' + j + ')) | 0;'); + src.push('hi = Math.imul(ah' + i + ', bh' + j + ');'); + + src.push('w' + k + ' = (w' + k + ' + lo) | 0;'); + src.push('w' + k + ' = (w' + k + ' + ((mid & 0x1fff) << 13)) | 0;'); + src.push('c = (c + hi) | 0;'); + src.push('c = (c + (mid >>> 13)) | 0;'); + src.push('c = (c + (w' + k + ' >>> 26)) | 0;'); + src.push('w' + k + ' &= 0x3ffffff;'); + } + } + // Store in separate step for better memory access + for (k = 0; k < len; k++) { + src.push('o[' + k + '] = w' + k + ';'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} + +console.log(genCombMulTo(10, 10)); diff --git a/node_modules/miller-rabin/node_modules/bn.js/util/genCombMulTo10.js b/node_modules/miller-rabin/node_modules/bn.js/util/genCombMulTo10.js new file mode 100644 index 0000000000000000000000000000000000000000..cf2e6e803cd4744e398b3404172bca56d1f90e8e --- /dev/null +++ b/node_modules/miller-rabin/node_modules/bn.js/util/genCombMulTo10.js @@ -0,0 +1,65 @@ +'use strict'; + +function genCombMulTo (alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = self.words;', + 'var b = num.words;', + 'var o = out.words;', + 'var c = 0;', + 'var lo;', + 'var mid;', + 'var hi;' + ]; + for (var i = 0; i < alen; i++) { + src.push('var a' + i + ' = a[' + i + '] | 0;'); + src.push('var al' + i + ' = a' + i + ' & 0x1fff;'); + src.push('var ah' + i + ' = a' + i + ' >>> 13;'); + } + for (i = 0; i < blen; i++) { + src.push('var b' + i + ' = b[' + i + '] | 0;'); + src.push('var bl' + i + ' = b' + i + ' & 0x1fff;'); + src.push('var bh' + i + ' = b' + i + ' >>> 13;'); + } + src.push(''); + src.push('out.negative = self.negative ^ num.negative;'); + src.push('out.length = ' + len + ';'); + + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + src.push('\/* k = ' + k + ' *\/'); + src.push('lo = Math.imul(al' + (k - minJ) + ', bl' + minJ + ');'); + src.push('mid = Math.imul(al' + (k - minJ) + ', bh' + minJ + ');'); + src.push( + 'mid = (mid + Math.imul(ah' + (k - minJ) + ', bl' + minJ + ')) | 0;'); + src.push('hi = Math.imul(ah' + (k - minJ) + ', bh' + minJ + ');'); + + for (var j = minJ + 1; j <= maxJ; j++) { + i = k - j; + + src.push('lo = (lo + Math.imul(al' + i + ', bl' + j + ')) | 0;'); + src.push('mid = (mid + Math.imul(al' + i + ', bh' + j + ')) | 0;'); + src.push('mid = (mid + Math.imul(ah' + i + ', bl' + j + ')) | 0;'); + src.push('hi = (hi + Math.imul(ah' + i + ', bh' + j + ')) | 0;'); + } + + src.push('var w' + k + ' = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;'); + src.push('c = (((hi + (mid >>> 13)) | 0) + (w' + k + ' >>> 26)) | 0;'); + src.push('w' + k + ' &= 0x3ffffff;'); + } + // Store in separate step for better memory access + for (k = 0; k < len; k++) { + src.push('o[' + k + '] = w' + k + ';'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} + +console.log(genCombMulTo(10, 10)); diff --git a/node_modules/miller-rabin/package.json b/node_modules/miller-rabin/package.json new file mode 100644 index 0000000000000000000000000000000000000000..af0f805732c8ee4cc9f07a0ac5ada41728ee20b3 --- /dev/null +++ b/node_modules/miller-rabin/package.json @@ -0,0 +1,32 @@ +{ + "name": "miller-rabin", + "version": "4.0.1", + "description": "Miller Rabin algorithm for primality test", + "main": "lib/mr.js", + "bin": "bin/miller-rabin", + "scripts": { + "test": "mocha --reporter=spec test/**/*-test.js" + }, + "repository": { + "type": "git", + "url": "git@github.com:indutny/miller-rabin" + }, + "keywords": [ + "prime", + "miller-rabin", + "bignumber" + ], + "author": "Fedor Indutny ", + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/miller-rabin/issues" + }, + "homepage": "https://github.com/indutny/miller-rabin", + "devDependencies": { + "mocha": "^2.0.1" + }, + "dependencies": { + "bn.js": "^4.0.0", + "brorand": "^1.0.1" + } +} diff --git a/node_modules/miller-rabin/test.js b/node_modules/miller-rabin/test.js new file mode 100644 index 0000000000000000000000000000000000000000..74b2ccfe40186dde3afb672fdc68c20c2e7580f2 --- /dev/null +++ b/node_modules/miller-rabin/test.js @@ -0,0 +1,25 @@ +var mr = require('./').create(); +var BN = require('bn.js'); + +var p = new BN( + `00:d3:99:af:83:02:de:91:f8:cc:1b:4e:2e:e0:18: + b3:0a:41:a4:77:98:d2:ad:66:0f:dc:17:85:ca:58: + b4:e4:88:55:c5:0a:82:08:7c:fb:70:a9:41:30:be: + af:50:d2:ce:93:cd:46:83:47:6e:c0:51:a7:10:e6: + 66:d1:08:e8:3d:b8:ce:fe:3e:4e:48:96:82:15:f7: + 2c:83:80:05:f2:14:3a:a4:5a:44:2b:22:22:67:e5: + 21:23:b7:cb:0f:71:5b:12:8b:3d:81:f6:5e:dc:99: + 8f:f9:80:38:75:57:c2:dd:9b:7a:b2:24:97:42:60: + 92:1f:1d:8a:68:c5:b8:7f:5d:c0:53:3d:15:f2:95: + b8:1d:8b:c2:e6:ca:a6:4c:bd:bf:88:9f:3e:d3:d7: + 24:18:27:62:6e:d0:52:75:68:9f:2a:c9:39:af:95: + 55:bb:11:08:dc:51:e9:8b:5a:38:e0:c0:e9:d8:a6: + 71:a5:03:f9:a7:2c:dd:1a:63:8e:7f:f0:36:68:a0: + 44:f8:09:48:3d:bd:de:b3:2d:3a:2f:73:88:8a:0c: + e2:7f:9b:dd:e8:c2:0e:ee:21:e4:a7:f9:4d:46:2f: + a7:f6:6d:fa:88:2e:95:60:ac:53:2e:45:a2:9d:9e: + c4:80:fc:c7:49:c9:42:bb:2b:66:f6:14:6d:7f:03: + 4e:f3`.replace(/[^a-f0-9]/g, ''), 16); +console.time(); +mr.test(p); +console.timeEnd(); diff --git a/node_modules/miller-rabin/test/api-test.js b/node_modules/miller-rabin/test/api-test.js new file mode 100644 index 0000000000000000000000000000000000000000..dee094d95e77678358a029d1dba707f748ab8ec1 --- /dev/null +++ b/node_modules/miller-rabin/test/api-test.js @@ -0,0 +1,18 @@ +var assert = require('assert'); +var mr = require('../').create(); +var bn = require('bn.js'); + +describe('Miller-Rabin', function() { + it('should test number for primality', function() { + assert(!mr.test(new bn(221))); + assert(mr.test(new bn(257))); + + var p = new bn('dba8191813fe8f51eaae1de70213aafede8f323f95f32cff' + + '8b64ebada275cfb18a446a0150e5fdaee246244c5f002ce0' + + 'aca97584be1745f2dd1eea2849c52aac8c4b5fb78a1c4da7' + + '052774338d3310a6e020c46168cb1f94014e9312511cc4fb' + + '79d695bb732449f0e015745b86bfa371dc6ca7386e9c7309' + + '5549c2e4b8002873', 16); + assert(mr.test(p)); + }); +}); diff --git a/node_modules/mime-db/HISTORY.md b/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..fb35beccad7e990844c8b39305e328db6b904f70 --- /dev/null +++ b/node_modules/mime-db/HISTORY.md @@ -0,0 +1,541 @@ +1.54.0 / 2025-03-17 +=================== + + * Update mime type for DCM format (#362) + * mark application/octet-stream as compressible (#163) + * Fix typo in application/x-zip-compressed mimetype (#359) + * Add mime-type for Jupyter notebooks (#282) + * Add Google Drive MIME types (#311) + * Add .blend file type (#338) + * Add support for the FBX file extension (#342) + * Add Adobe DNG file (#340) + * Add Procreate Brush and Brush Set file Types (#339) + * Add support for Procreate Dreams (#341) + * replace got with undici (#352) + * Added extensions list for model/step (#293) + * Add m4b as a type of audio/mp4 (#357) + * windows 11 application/x-zip-compressed (#346) + * add dotLottie mime type (#351) + * Add some MS-related extensions and types (#336) + +1.53.0 / 2024-07-12 +=================== + + * Add extension `.sql` to `application/sql` + * Add extensions `.aac` and `.adts` to `audio/aac` + * Add extensions `.js` and `.mjs` to `text/javascript` + * Add extensions for `application/mp4` from IANA + * Add extensions from IANA for more MIME types + * Add Microsoft app installer types and extensions + * Add new upstream MIME types + * Fix extensions for `text/markdown` to match IANA + * Remove extension `.mjs` from `application/javascript` + * Remove obsolete MIME types from IANA data + +1.52.0 / 2022-02-21 +=================== + + * Add extensions from IANA for more `image/*` types + * Add extension `.asc` to `application/pgp-keys` + * Add extensions to various XML types + * Add new upstream MIME types + +1.51.0 / 2021-11-08 +=================== + + * Add new upstream MIME types + * Mark `image/vnd.microsoft.icon` as compressible + * Mark `image/vnd.ms-dds` as compressible + +1.50.0 / 2021-09-15 +=================== + + * Add deprecated iWorks mime types and extensions + * Add new upstream MIME types + +1.49.0 / 2021-07-26 +=================== + + * Add extension `.trig` to `application/trig` + * Add new upstream MIME types + +1.48.0 / 2021-05-30 +=================== + + * Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + * Add new upstream MIME types + * Mark `text/yaml` as compressible + +1.47.0 / 2021-04-01 +=================== + + * Add new upstream MIME types + * Remove ambiguous extensions from IANA for `application/*+xml` types + * Update primary extension to `.es` for `application/ecmascript` + +1.46.0 / 2021-02-13 +=================== + + * Add extension `.amr` to `audio/amr` + * Add extension `.m4s` to `video/iso.segment` + * Add extension `.opus` to `audio/ogg` + * Add new upstream MIME types + +1.45.0 / 2020-09-22 +=================== + + * Add `application/ubjson` with extension `.ubj` + * Add `image/avif` with extension `.avif` + * Add `image/ktx2` with extension `.ktx2` + * Add extension `.dbf` to `application/vnd.dbf` + * Add extension `.rar` to `application/vnd.rar` + * Add extension `.td` to `application/urc-targetdesc+xml` + * Add new upstream MIME types + * Fix extension of `application/vnd.apple.keynote` to be `.key` + +1.44.0 / 2020-04-22 +=================== + + * Add charsets from IANA + * Add extension `.cjs` to `application/node` + * Add new upstream MIME types + +1.43.0 / 2020-01-05 +=================== + + * Add `application/x-keepass2` with extension `.kdbx` + * Add extension `.mxmf` to `audio/mobile-xmf` + * Add extensions from IANA for `application/*+xml` types + * Add new upstream MIME types + +1.42.0 / 2019-09-25 +=================== + + * Add `image/vnd.ms-dds` with extension `.dds` + * Add new upstream MIME types + * Remove compressible from `multipart/mixed` + +1.41.0 / 2019-08-30 +=================== + + * Add new upstream MIME types + * Add `application/toml` with extension `.toml` + * Mark `font/ttf` as compressible + +1.40.0 / 2019-04-20 +=================== + + * Add extensions from IANA for `model/*` types + * Add `text/mdx` with extension `.mdx` + +1.39.0 / 2019-04-04 +=================== + + * Add extensions `.siv` and `.sieve` to `application/sieve` + * Add new upstream MIME types + +1.38.0 / 2019-02-04 +=================== + + * Add extension `.nq` to `application/n-quads` + * Add extension `.nt` to `application/n-triples` + * Add new upstream MIME types + * Mark `text/less` as compressible + +1.37.0 / 2018-10-19 +=================== + + * Add extensions to HEIC image types + * Add new upstream MIME types + +1.36.0 / 2018-08-20 +=================== + + * Add Apple file extensions from IANA + * Add extensions from IANA for `image/*` types + * Add new upstream MIME types + +1.35.0 / 2018-07-15 +=================== + + * Add extension `.owl` to `application/rdf+xml` + * Add new upstream MIME types + - Removes extension `.woff` from `application/font-woff` + +1.34.0 / 2018-06-03 +=================== + + * Add extension `.csl` to `application/vnd.citationstyles.style+xml` + * Add extension `.es` to `application/ecmascript` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/turtle` + * Mark all XML-derived types as compressible + +1.33.0 / 2018-02-15 +=================== + + * Add extensions from IANA for `message/*` types + * Add new upstream MIME types + * Fix some incorrect OOXML types + * Remove `application/font-woff2` + +1.32.0 / 2017-11-29 +=================== + + * Add new upstream MIME types + * Update `text/hjson` to registered `application/hjson` + * Add `text/shex` with extension `.shex` + +1.31.0 / 2017-10-25 +=================== + + * Add `application/raml+yaml` with extension `.raml` + * Add `application/wasm` with extension `.wasm` + * Add new `font` type from IANA + * Add new upstream font extensions + * Add new upstream MIME types + * Add extensions for JPEG-2000 images + +1.30.0 / 2017-08-27 +=================== + + * Add `application/vnd.ms-outlook` + * Add `application/x-arj` + * Add extension `.mjs` to `application/javascript` + * Add glTF types and extensions + * Add new upstream MIME types + * Add `text/x-org` + * Add VirtualBox MIME types + * Fix `source` records for `video/*` types that are IANA + * Update `font/opentype` to registered `font/otf` + +1.29.0 / 2017-07-10 +=================== + + * Add `application/fido.trusted-apps+json` + * Add extension `.wadl` to `application/vnd.sun.wadl+xml` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/css` + +1.28.0 / 2017-05-14 +=================== + + * Add new upstream MIME types + * Add extension `.gz` to `application/gzip` + * Update extensions `.md` and `.markdown` to be `text/markdown` + +1.27.0 / 2017-03-16 +=================== + + * Add new upstream MIME types + * Add `image/apng` with extension `.apng` + +1.26.0 / 2017-01-14 +=================== + + * Add new upstream MIME types + * Add extension `.geojson` to `application/geo+json` + +1.25.0 / 2016-11-11 +=================== + + * Add new upstream MIME types + +1.24.0 / 2016-09-18 +=================== + + * Add `audio/mp3` + * Add new upstream MIME types + +1.23.0 / 2016-05-01 +=================== + + * Add new upstream MIME types + * Add extension `.3gpp` to `audio/3gpp` + +1.22.0 / 2016-02-15 +=================== + + * Add `text/slim` + * Add extension `.rng` to `application/xml` + * Add new upstream MIME types + * Fix extension of `application/dash+xml` to be `.mpd` + * Update primary extension to `.m4a` for `audio/mp4` + +1.21.0 / 2016-01-06 +=================== + + * Add Google document types + * Add new upstream MIME types + +1.20.0 / 2015-11-10 +=================== + + * Add `text/x-suse-ymp` + * Add new upstream MIME types + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.apple.pkpass` + * Add new upstream MIME types + +1.18.0 / 2015-09-03 +=================== + + * Add new upstream MIME types + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +1.13.0 / 2015-06-07 +=================== + + * Add nginx as a source + * Add `application/x-cocoa` + * Add `application/x-java-archive-diff` + * Add `application/x-makeself` + * Add `application/x-perl` + * Add `application/x-pilot` + * Add `application/x-redhat-package-manager` + * Add `application/x-sea` + * Add `audio/x-m4a` + * Add `audio/x-realaudio` + * Add `image/x-jng` + * Add `text/mathml` + +1.12.0 / 2015-06-05 +=================== + + * Add `application/bdoc` + * Add `application/vnd.hyperdrive+json` + * Add `application/x-bdoc` + * Add extension `.rtf` to `text/rtf` + +1.11.0 / 2015-05-31 +=================== + + * Add `audio/wav` + * Add `audio/wave` + * Add extension `.litcoffee` to `text/coffeescript` + * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` + * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` + +1.10.0 / 2015-05-19 +=================== + + * Add `application/vnd.balsamiq.bmpr` + * Add `application/vnd.microsoft.portable-executable` + * Add `application/x-ns-proxy-autoconfig` + +1.9.1 / 2015-04-19 +================== + + * Remove `.json` extension from `application/manifest+json` + - This is causing bugs downstream + +1.9.0 / 2015-04-19 +================== + + * Add `application/manifest+json` + * Add `application/vnd.micro+json` + * Add `image/vnd.zbrush.pcx` + * Add `image/x-ms-bmp` + +1.8.0 / 2015-03-13 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/node_modules/mime-db/LICENSE b/node_modules/mime-db/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0751cb10e94972be9a07b44cc261447bac726a7f --- /dev/null +++ b/node_modules/mime-db/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015-2022 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mime-db/README.md b/node_modules/mime-db/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ee93fa00ab2fbe05ba2ee0fcdc606d9aad12bd52 --- /dev/null +++ b/node_modules/mime-db/README.md @@ -0,0 +1,109 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a large database of mime types and information about them. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +It aggregates data from the following sources: + +- https://www.iana.org/assignments/media-types/media-types.xhtml +- https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +- https://hg.nginx.org/nginx/raw-file/default/conf/mime.types + +## Installation + +```bash +npm install mime-db +``` + +### Database Download + +If you intend to use this in a web browser, you can conveniently access the JSON file via [jsDelivr](https://www.jsdelivr.com/), a popular CDN (Content Delivery Network). To ensure stability and compatibility, it is advisable to specify [a release tag](https://github.com/jshttp/mime-db/tags) instead of using the 'master' branch. This is because the JSON file's format might change in future updates, and relying on a specific release tag will prevent potential issues arising from these changes. + +``` +https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json +``` + +## Usage + +```js +var db = require('mime-db') + +// grab data on .js files +var data = db['application/javascript'] +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + If not set, it's probably a custom media type. + - `apache` - [Apache common media types](https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) + - `iana` - [IANA-defined media types](https://www.iana.org/assignments/media-types/media-types.xhtml) + - `nginx` - [nginx media types](https://hg.nginx.org/nginx/raw-file/default/conf/mime.types) +- `.extensions[]` - known extensions associated with this mime type. +- `.compressible` - whether a file of this type can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Note on MIME Type Data and Semver + +This package considers the programmatic api as the semver compatibility. This means the MIME type resolution is *not* considered +in the semver bumps. This means that if you want to pin your `mime-db` data you will need to do it in your application. While +this expectation was not set in docs until now, it is how the pacakge operated, so we do not feel this is a breaking change. + +## Contributing + +The primary way to contribute to this database is by updating the data in +one of the upstream sources. The database is updated from the upstreams +periodically and will pull in any changes. + +### Registering Media Types + +The best way to get new media types included in this library is to register +them with the IANA. The community registration procedure is outlined in +[RFC 6838 section 5](https://tools.ietf.org/html/rfc6838#section-5). Types +registered with the IANA are automatically pulled into this library. + +### Direct Inclusion + +If that is not possible / feasible, they can be added directly here as a +"custom" type. To do this, it is required to have a primary source that +definitively lists the media type. If an extension is going to be listed as +associated with this media type, the source must definitively link the +media type and extension as well. + +To edit the database, only make PRs against `src/custom-types.json` or +`src/custom-suffix.json`. + +The `src/custom-types.json` file is a JSON object with the MIME type as the +keys and the values being an object with the following keys: + +- `compressible` - leave out if you don't know, otherwise `true`/`false` to + indicate whether the data represented by the type is typically compressible. +- `extensions` - include an array of file extensions that are associated with + the type. +- `notes` - human-readable notes about the type, typically what the type is. +- `sources` - include an array of URLs of where the MIME type and the associated + extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); + links to type aggregating sites and Wikipedia are _not acceptable_. + +To update the build, run `npm run build`. + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-db/master?label=ci +[ci-url]: https://github.com/jshttp/mime-db/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master +[node-image]: https://badgen.net/npm/node/mime-db +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-db +[npm-url]: https://npmjs.org/package/mime-db +[npm-version-image]: https://badgen.net/npm/v/mime-db diff --git a/node_modules/mime-db/db.json b/node_modules/mime-db/db.json new file mode 100644 index 0000000000000000000000000000000000000000..7e74733026db22005684393bf7a54c895e9f4abe --- /dev/null +++ b/node_modules/mime-db/db.json @@ -0,0 +1,9342 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/3gpp-ims+xml": { + "source": "iana", + "compressible": true + }, + "application/3gpphal+json": { + "source": "iana", + "compressible": true + }, + "application/3gpphalforms+json": { + "source": "iana", + "compressible": true + }, + "application/a2l": { + "source": "iana" + }, + "application/ace+cbor": { + "source": "iana" + }, + "application/ace+json": { + "source": "iana", + "compressible": true + }, + "application/ace-groupcomm+cbor": { + "source": "iana" + }, + "application/ace-trl+cbor": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/activity+json": { + "source": "iana", + "compressible": true + }, + "application/aif+cbor": { + "source": "iana" + }, + "application/aif+json": { + "source": "iana", + "compressible": true + }, + "application/alto-cdni+json": { + "source": "iana", + "compressible": true + }, + "application/alto-cdnifilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-propmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-propmapparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-tips+json": { + "source": "iana", + "compressible": true + }, + "application/alto-tipsparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamcontrol+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamparams+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/appinstaller": { + "compressible": false, + "extensions": ["appinstaller"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/appx": { + "compressible": false, + "extensions": ["appx"] + }, + "application/appxbundle": { + "compressible": false, + "extensions": ["appxbundle"] + }, + "application/at+jwt": { + "source": "iana" + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomdeleted"] + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomsvc"] + }, + "application/atsc-dwd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dwd"] + }, + "application/atsc-dynamic-event-message": { + "source": "iana" + }, + "application/atsc-held+xml": { + "source": "iana", + "compressible": true, + "extensions": ["held"] + }, + "application/atsc-rdt+json": { + "source": "iana", + "compressible": true + }, + "application/atsc-rsat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsat"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana", + "compressible": true + }, + "application/automationml-aml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["aml"] + }, + "application/automationml-amlx+zip": { + "source": "iana", + "compressible": false, + "extensions": ["amlx"] + }, + "application/bacnet-xdd+zip": { + "source": "iana", + "compressible": false + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/bufr": { + "source": "iana" + }, + "application/c2pa": { + "source": "iana" + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xcs"] + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/captive+json": { + "source": "iana", + "compressible": true + }, + "application/cbor": { + "source": "iana" + }, + "application/cbor-seq": { + "source": "iana" + }, + "application/cccex": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana", + "compressible": true + }, + "application/ccxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ccxml"] + }, + "application/cda+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/cdfx+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdfx"] + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/ce+cbor": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana", + "compressible": true + }, + "application/cellml+xml": { + "source": "iana", + "compressible": true + }, + "application/cfw": { + "source": "iana" + }, + "application/cid-edhoc+cbor-seq": { + "source": "iana" + }, + "application/city+json": { + "source": "iana", + "compressible": true + }, + "application/city+json-seq": { + "source": "iana" + }, + "application/clr": { + "source": "iana" + }, + "application/clue+xml": { + "source": "iana", + "compressible": true + }, + "application/clue_info+xml": { + "source": "iana", + "compressible": true + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana", + "compressible": true + }, + "application/coap-eap": { + "source": "iana" + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/coap-payload": { + "source": "iana" + }, + "application/commonground": { + "source": "iana" + }, + "application/concise-problem-details+cbor": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/cose": { + "source": "iana" + }, + "application/cose-key": { + "source": "iana" + }, + "application/cose-key-set": { + "source": "iana" + }, + "application/cose-x509": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cpl"] + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana", + "compressible": true + }, + "application/cstadata+xml": { + "source": "iana", + "compressible": true + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cwl": { + "source": "iana", + "extensions": ["cwl"] + }, + "application/cwl+json": { + "source": "iana", + "compressible": true + }, + "application/cwl+yaml": { + "source": "iana" + }, + "application/cwt": { + "source": "iana" + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpd"] + }, + "application/dash-patch+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "compressible": true, + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana", + "compressible": true + }, + "application/dicom": { + "source": "iana", + "extensions": ["dcm"] + }, + "application/dicom+json": { + "source": "iana", + "compressible": true + }, + "application/dicom+xml": { + "source": "iana", + "compressible": true + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/dns+json": { + "source": "iana", + "compressible": true + }, + "application/dns-message": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dbk"] + }, + "application/dots+cbor": { + "source": "iana" + }, + "application/dpop+jwt": { + "source": "iana" + }, + "application/dskpp+xml": { + "source": "iana", + "compressible": true + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/eat+cwt": { + "source": "iana" + }, + "application/eat+jwt": { + "source": "iana" + }, + "application/eat-bun+cbor": { + "source": "iana" + }, + "application/eat-bun+json": { + "source": "iana", + "compressible": true + }, + "application/eat-ucs+cbor": { + "source": "iana" + }, + "application/eat-ucs+json": { + "source": "iana", + "compressible": true + }, + "application/ecmascript": { + "source": "apache", + "compressible": true, + "extensions": ["ecma"] + }, + "application/edhoc+cbor-seq": { + "source": "iana" + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/efi": { + "source": "iana" + }, + "application/elm+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/elm+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.cap+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/emergencycalldata.comment+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.control+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.ecall.msd": { + "source": "iana" + }, + "application/emergencycalldata.legacyesn+json": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.veds+xml": { + "source": "iana", + "compressible": true + }, + "application/emma+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emotionml"] + }, + "application/encaprtp": { + "source": "iana" + }, + "application/entity-statement+jwt": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana", + "compressible": true + }, + "application/epub+zip": { + "source": "iana", + "compressible": false, + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/expect-ct-report+json": { + "source": "iana", + "compressible": true + }, + "application/express": { + "source": "iana", + "extensions": ["exp"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/fdt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fdt"] + }, + "application/fhir+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fhir+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fido.trusted-apps+json": { + "compressible": true + }, + "application/fits": { + "source": "iana" + }, + "application/flexfec": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false + }, + "application/framework-attributes+xml": { + "source": "iana", + "compressible": true + }, + "application/geo+json": { + "source": "iana", + "compressible": true, + "extensions": ["geojson"] + }, + "application/geo+json-seq": { + "source": "iana" + }, + "application/geopackage+sqlite3": { + "source": "iana" + }, + "application/geopose+json": { + "source": "iana", + "compressible": true + }, + "application/geoxacml+json": { + "source": "iana", + "compressible": true + }, + "application/geoxacml+xml": { + "source": "iana", + "compressible": true + }, + "application/gltf-buffer": { + "source": "iana" + }, + "application/gml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["gml"] + }, + "application/gnap-binding-jws": { + "source": "iana" + }, + "application/gnap-binding-jwsd": { + "source": "iana" + }, + "application/gnap-binding-rotation-jws": { + "source": "iana" + }, + "application/gnap-binding-rotation-jwsd": { + "source": "iana" + }, + "application/gpx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["gpx"] + }, + "application/grib": { + "source": "iana" + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false, + "extensions": ["gz"] + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana", + "compressible": true + }, + "application/hjson": { + "extensions": ["hjson"] + }, + "application/hl7v2+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pkg-reply+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana", + "compressible": true, + "extensions": ["its"] + }, + "application/java-archive": { + "source": "iana", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "apache", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js"] + }, + "application/jf2feed+json": { + "source": "iana", + "compressible": true + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/jscalendar+json": { + "source": "iana", + "compressible": true + }, + "application/jscontact+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jsonpath": { + "source": "iana" + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+jwt": { + "source": "iana" + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana", + "compressible": true + }, + "application/kpml-response+xml": { + "source": "iana", + "compressible": true + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/lgr+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lgr"] + }, + "application/link-format": { + "source": "iana" + }, + "application/linkset": { + "source": "iana" + }, + "application/linkset+json": { + "source": "iana", + "compressible": true + }, + "application/load-control+xml": { + "source": "iana", + "compressible": true + }, + "application/logout+jwt": { + "source": "iana" + }, + "application/lost+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana", + "compressible": true + }, + "application/lpf+zip": { + "source": "iana", + "compressible": false + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mads"] + }, + "application/manifest+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana", + "compressible": true + }, + "application/mathml-presentation+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-deregister+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-envelope+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-protection-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-reception-report+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-user-service-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpf"] + }, + "application/media_control+xml": { + "source": "iana", + "compressible": true + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "compressible": true, + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "compressible": true, + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mipc": { + "source": "iana" + }, + "application/missing-blocks+cbor-seq": { + "source": "iana" + }, + "application/mmt-aei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["maei"] + }, + "application/mmt-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musd"] + }, + "application/mods+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4","mpg4","mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana", + "compressible": true + }, + "application/mrb-publish+xml": { + "source": "iana", + "compressible": true + }, + "application/msc-ivr+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msc-mixer+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msix": { + "compressible": false, + "extensions": ["msix"] + }, + "application/msixbundle": { + "compressible": false, + "extensions": ["msixbundle"] + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mud+json": { + "source": "iana", + "compressible": true + }, + "application/multipart-core": { + "source": "iana" + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/n-quads": { + "source": "iana", + "extensions": ["nq"] + }, + "application/n-triples": { + "source": "iana", + "extensions": ["nt"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-groupinfo": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana", + "compressible": true + }, + "application/node": { + "source": "iana", + "extensions": ["cjs"] + }, + "application/nss": { + "source": "iana" + }, + "application/oauth-authz-req+jwt": { + "source": "iana" + }, + "application/oblivious-dns-message": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": true, + "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] + }, + "application/oda": { + "source": "iana", + "extensions": ["oda"] + }, + "application/odm+xml": { + "source": "iana", + "compressible": true + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/ohttp-keys": { + "source": "iana" + }, + "application/omdoc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg","one","onea"] + }, + "application/opc-nodeset+xml": { + "source": "iana", + "compressible": true + }, + "application/oscore": { + "source": "iana" + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p21": { + "source": "iana" + }, + "application/p21+zip": { + "source": "iana", + "compressible": false + }, + "application/p2p-overlay+xml": { + "source": "iana", + "compressible": true, + "extensions": ["relo"] + }, + "application/parityfec": { + "source": "iana" + }, + "application/passport": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pem-certificate-chain": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana", + "extensions": ["asc"] + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["sig","asc"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pidf-diff+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkcs8-encrypted": { + "source": "iana" + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/ppsp-tracker+json": { + "source": "iana", + "compressible": true + }, + "application/private-token-issuer-directory": { + "source": "iana" + }, + "application/private-token-request": { + "source": "iana" + }, + "application/private-token-response": { + "source": "iana" + }, + "application/problem+json": { + "source": "iana", + "compressible": true + }, + "application/problem+xml": { + "source": "iana", + "compressible": true + }, + "application/provenance+xml": { + "source": "iana", + "compressible": true, + "extensions": ["provx"] + }, + "application/provided-claims+jwt": { + "source": "iana" + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.cyn": { + "source": "iana", + "charset": "7-BIT" + }, + "application/prs.hpub+zip": { + "source": "iana", + "compressible": false + }, + "application/prs.implied-document+xml": { + "source": "iana", + "compressible": true + }, + "application/prs.implied-executable": { + "source": "iana" + }, + "application/prs.implied-object+json": { + "source": "iana", + "compressible": true + }, + "application/prs.implied-object+json-seq": { + "source": "iana" + }, + "application/prs.implied-object+yaml": { + "source": "iana" + }, + "application/prs.implied-structure": { + "source": "iana" + }, + "application/prs.mayfile": { + "source": "iana" + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.vcfbzip2": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsf"] + }, + "application/pskc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pskcxml"] + }, + "application/pvd+json": { + "source": "iana", + "compressible": true + }, + "application/qsig": { + "source": "iana" + }, + "application/raml+yaml": { + "compressible": true, + "extensions": ["raml"] + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf","owl"] + }, + "application/reginfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "apache" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resolve-response+jwt": { + "source": "iana" + }, + "application/resource-lists+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana", + "compressible": true + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana", + "compressible": true + }, + "application/rls-services+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rs"] + }, + "application/route-apd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rapd"] + }, + "application/route-s-tsid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sls"] + }, + "application/route-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rusd"] + }, + "application/rpki-checklist": { + "source": "iana" + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-publication": { + "source": "iana" + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-signed-tal": { + "source": "iana" + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana", + "compressible": true + }, + "application/samlmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/sarif+json": { + "source": "iana", + "compressible": true + }, + "application/sarif-external-properties+json": { + "source": "iana", + "compressible": true + }, + "application/sbe": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana", + "compressible": true + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/secevent+jwt": { + "source": "iana" + }, + "application/senml+cbor": { + "source": "iana" + }, + "application/senml+json": { + "source": "iana", + "compressible": true + }, + "application/senml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["senmlx"] + }, + "application/senml-etch+cbor": { + "source": "iana" + }, + "application/senml-etch+json": { + "source": "iana", + "compressible": true + }, + "application/senml-exi": { + "source": "iana" + }, + "application/sensml+cbor": { + "source": "iana" + }, + "application/sensml+json": { + "source": "iana", + "compressible": true + }, + "application/sensml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sensmlx"] + }, + "application/sensml-exi": { + "source": "iana" + }, + "application/sep+xml": { + "source": "iana", + "compressible": true + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana", + "extensions": ["siv","sieve"] + }, + "application/simple-filter+xml": { + "source": "iana", + "compressible": true + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/sipc": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "apache" + }, + "application/smil+xml": { + "source": "iana", + "compressible": true, + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "compressible": true, + "extensions": ["srx"] + }, + "application/spdx+json": { + "source": "iana", + "compressible": true + }, + "application/spirits-event+xml": { + "source": "iana", + "compressible": true + }, + "application/sql": { + "source": "iana", + "extensions": ["sql"] + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ssdl"] + }, + "application/sslkeylogfile": { + "source": "iana" + }, + "application/ssml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ssml"] + }, + "application/st2110-41": { + "source": "iana" + }, + "application/stix+json": { + "source": "iana", + "compressible": true + }, + "application/stratum": { + "source": "iana" + }, + "application/swid+cbor": { + "source": "iana" + }, + "application/swid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["swidtag"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/taxii+json": { + "source": "iana", + "compressible": true + }, + "application/td+json": { + "source": "iana", + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tei","teicorpus"] + }, + "application/tetra_isi": { + "source": "iana" + }, + "application/thraud+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/tlsrpt+gzip": { + "source": "iana" + }, + "application/tlsrpt+json": { + "source": "iana", + "compressible": true + }, + "application/tm+json": { + "source": "iana", + "compressible": true + }, + "application/tnauthlist": { + "source": "iana" + }, + "application/toc+cbor": { + "source": "iana" + }, + "application/token-introspection+jwt": { + "source": "iana" + }, + "application/toml": { + "source": "iana", + "compressible": true, + "extensions": ["toml"] + }, + "application/trickle-ice-sdpfrag": { + "source": "iana" + }, + "application/trig": { + "source": "iana", + "extensions": ["trig"] + }, + "application/trust-chain+json": { + "source": "iana", + "compressible": true + }, + "application/trust-mark+jwt": { + "source": "iana" + }, + "application/trust-mark-delegation+jwt": { + "source": "iana" + }, + "application/ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ttml"] + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/tzif": { + "source": "iana" + }, + "application/tzif-leap": { + "source": "iana" + }, + "application/ubjson": { + "compressible": false, + "extensions": ["ubj"] + }, + "application/uccs+cbor": { + "source": "iana" + }, + "application/ujcs+json": { + "source": "iana", + "compressible": true + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-ressheet+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsheet"] + }, + "application/urc-targetdesc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["td"] + }, + "application/urc-uisocketdesc+xml": { + "source": "iana", + "compressible": true + }, + "application/vc": { + "source": "iana" + }, + "application/vc+cose": { + "source": "iana" + }, + "application/vc+jwt": { + "source": "iana" + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana", + "compressible": true + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + "source": "iana", + "compressible": true, + "extensions": ["1km"] + }, + "application/vnd.1ob": { + "source": "iana" + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3a+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ach+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc8+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-v2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.5gnas": { + "source": "iana" + }, + "application/vnd.3gpp.5gsa2x": { + "source": "iana" + }, + "application/vnd.3gpp.5gsa2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.5gsv2x": { + "source": "iana" + }, + "application/vnd.3gpp.5gsv2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.crs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.current-location-discovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gmop+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gtpc": { + "source": "iana" + }, + "application/vnd.3gpp.interworking-data": { + "source": "iana" + }, + "application/vnd.3gpp.lpp": { + "source": "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-msgstore-ctrl-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-payload": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-regroup+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-signalling": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-regroup+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-regroup+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ngap": { + "source": "iana" + }, + "application/vnd.3gpp.pfcp": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.pinapp-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.s1ap": { + "source": "iana" + }, + "application/vnd.3gpp.seal-group-doc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-network-qos-management-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-ue-config-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-unicast-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.seal-user-profile-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.sms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.v2x": { + "source": "iana" + }, + "application/vnd.3gpp.vae-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + "source": "iana" + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acm.addressxfer+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.acm.chatbot+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "compressible": false, + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "apache", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + "source": "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + "source": "iana" + }, + "application/vnd.afpc.foca-charset": { + "source": "iana" + }, + "application/vnd.afpc.foca-codedfont": { + "source": "iana" + }, + "application/vnd.afpc.foca-codepage": { + "source": "iana" + }, + "application/vnd.afpc.modca": { + "source": "iana" + }, + "application/vnd.afpc.modca-cmtable": { + "source": "iana" + }, + "application/vnd.afpc.modca-formdef": { + "source": "iana" + }, + "application/vnd.afpc.modca-mediummap": { + "source": "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + "source": "iana" + }, + "application/vnd.afpc.modca-overlay": { + "source": "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + "source": "iana" + }, + "application/vnd.age": { + "source": "iana", + "extensions": ["age"] + }, + "application/vnd.ah-barcode": { + "source": "apache" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amadeus+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + "source": "iana" + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.android.ota": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.arrow.file": { + "source": "iana" + }, + "application/vnd.apache.arrow.stream": { + "source": "iana" + }, + "application/vnd.apache.parquet": { + "source": "iana" + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.apexlang": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.aplextor.warrp+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apothekende.reservation+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpkg"] + }, + "application/vnd.apple.keynote": { + "source": "iana", + "extensions": ["key"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.numbers": { + "source": "iana", + "extensions": ["numbers"] + }, + "application/vnd.apple.pages": { + "source": "iana", + "extensions": ["pages"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "apache" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artisan+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autodesk.fbx": { + "extensions": ["fbx"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avalon+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.avistar+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["bmml"] + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.banana-accounting": { + "source": "iana" + }, + "application/vnd.bbf.usp.error": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.belightsoft.lhzd+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.belightsoft.lhzl+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.bint.med-content": { + "source": "iana" + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.blink-idb-value-wrapper": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.bpf": { + "source": "iana" + }, + "application/vnd.bpf3": { + "source": "iana" + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.byu.uapi+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bzip3": { + "source": "iana" + }, + "application/vnd.c3voc.schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.capasystems-pg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdxml"] + }, + "application/vnd.chess-pgn": { + "source": "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.ciedi": { + "source": "iana" + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana", + "compressible": true, + "extensions": ["csl"] + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.cncf.helm.chart.content.v1.tar+gzip": { + "source": "iana" + }, + "application/vnd.cncf.helm.chart.provenance.v1.prov": { + "source": "iana" + }, + "application/vnd.cncf.helm.config.v1+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.comicbook+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.comicbook-rar": { + "source": "iana" + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wbs"] + }, + "application/vnd.cryptii.pipe+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.crypto-shade-file": { + "source": "iana" + }, + "application/vnd.cryptomator.encrypted": { + "source": "iana" + }, + "application/vnd.cryptomator.vault": { + "source": "iana" + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.cyclonedx+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cyclonedx+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.d3m-dataset": { + "source": "iana" + }, + "application/vnd.d3m-problem": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.datalog": { + "source": "iana" + }, + "application/vnd.datapackage+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dataresource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dbf": { + "source": "iana", + "extensions": ["dbf"] + }, + "application/vnd.dcmp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dcmp"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume.movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbisl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecip.rlp": { + "source": "iana" + }, + "application/vnd.eclipse.ditto+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.efi.img": { + "source": "iana" + }, + "application/vnd.efi.iso": { + "source": "iana" + }, + "application/vnd.eln+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.erofs": { + "source": "iana" + }, + "application/vnd.espass-espass+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "compressible": true, + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.cug+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.sci+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eu.kasparian.car+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.evolv.ecig.profile": { + "source": "iana" + }, + "application/vnd.evolv.ecig.settings": { + "source": "iana" + }, + "application/vnd.evolv.ecig.theme": { + "source": "iana" + }, + "application/vnd.exstream-empower+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.exstream-package": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.familysearch.gedcom+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "apache", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.fdsn.stationxml+xml": { + "source": "iana", + "charset": "XML-BASED", + "compressible": true + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.ficlab.flb+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.freelog.comic": { + "source": "iana" + }, + "application/vnd.frogans.fnc": { + "source": "apache", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "apache", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujifilm.fb.docuworks": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.futoin+cbor": { + "source": "iana" + }, + "application/vnd.futoin+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.ga4gh.passport+jwt": { + "source": "iana" + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.genozip": { + "source": "iana" + }, + "application/vnd.gentics.grd+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.gentoo.catmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gentoo.ebuild": { + "source": "iana" + }, + "application/vnd.gentoo.eclass": { + "source": "iana" + }, + "application/vnd.gentoo.gpkg": { + "source": "iana" + }, + "application/vnd.gentoo.manifest": { + "source": "iana" + }, + "application/vnd.gentoo.pkgmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gentoo.xpak": { + "source": "iana" + }, + "application/vnd.geo+json": { + "source": "apache", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.pinboard": { + "source": "iana" + }, + "application/vnd.geogebra.slides": { + "source": "iana", + "extensions": ["ggs"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.gnu.taler.exchange+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.gnu.taler.merchant+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.google-apps.audio": {}, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.drawing": { + "compressible": false, + "extensions": ["gdraw"] + }, + "application/vnd.google-apps.drive-sdk": { + "compressible": false + }, + "application/vnd.google-apps.file": {}, + "application/vnd.google-apps.folder": { + "compressible": false + }, + "application/vnd.google-apps.form": { + "compressible": false, + "extensions": ["gform"] + }, + "application/vnd.google-apps.fusiontable": {}, + "application/vnd.google-apps.jam": { + "compressible": false, + "extensions": ["gjam"] + }, + "application/vnd.google-apps.mail-layout": {}, + "application/vnd.google-apps.map": { + "compressible": false, + "extensions": ["gmap"] + }, + "application/vnd.google-apps.photo": {}, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.script": { + "compressible": false, + "extensions": ["gscript"] + }, + "application/vnd.google-apps.shortcut": {}, + "application/vnd.google-apps.site": { + "compressible": false, + "extensions": ["gsite"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-apps.unknown": {}, + "application/vnd.google-apps.video": {}, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdcf"] + }, + "application/vnd.gpxsee.map+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "compressible": true, + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.hdt": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.hsl": { + "source": "iana" + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyper-item+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "apache" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "apache", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.imagemeter.image+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.informix-visionary": { + "source": "apache" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.ipfs.ipns-record": { + "source": "iana" + }, + "application/vnd.ipld.car": { + "source": "iana" + }, + "application/vnd.ipld.dag-cbor": { + "source": "iana" + }, + "application/vnd.ipld.dag-json": { + "source": "iana" + }, + "application/vnd.ipld.raw": { + "source": "iana" + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.iso11783-10+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kdl": { + "source": "iana" + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.keyman.kmp+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.keyman.kmx": { + "source": "iana" + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las": { + "source": "iana" + }, + "application/vnd.las.las+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.las.las+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lasxml"] + }, + "application/vnd.laszip": { + "source": "iana" + }, + "application/vnd.ldev.productlicensing": { + "source": "iana" + }, + "application/vnd.leap+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.liberty-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lbe"] + }, + "application/vnd.logipipe.circuit+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.loom": { + "source": "iana" + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana", + "extensions": ["mvt"] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxar.archive.3tz+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.mdl": { + "source": "iana" + }, + "application/vnd.mdl-mbsdf": { + "source": "iana" + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.medicalholodeck.recordxr": { + "source": "iana" + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mermaid": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.modl": { + "source": "iana" + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-outlook": { + "compressible": false, + "extensions": ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-printschematicket+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-visio.viewer": { + "extensions": ["vdx"] + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msgpack": { + "source": "iana" + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.nacamar.ybrid+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nato.bindingdataobject+cbor": { + "source": "iana" + }, + "application/vnd.nato.bindingdataobject+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nato.bindingdataobject+xml": { + "source": "iana", + "compressible": true, + "extensions": ["bdo"] + }, + "application/vnd.nato.openxmlformats-package.iepd+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nearst.inv+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nebumind.line": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nimn": { + "source": "iana" + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ac"] + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "apache", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oai.workflows": { + "source": "iana" + }, + "application/vnd.oai.workflows+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oai.workflows+yaml": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.base": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "apache", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-master-template": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.ocf+cbor": { + "source": "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+cbor": { + "source": "iana" + }, + "application/vnd.oma.lwm2m+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+tlv": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-email+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-file+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-folder+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.onepager": { + "source": "iana" + }, + "application/vnd.onepagertamp": { + "source": "iana" + }, + "application/vnd.onepagertamx": { + "source": "iana" + }, + "application/vnd.onepagertat": { + "source": "iana" + }, + "application/vnd.onepagertatp": { + "source": "iana" + }, + "application/vnd.onepagertatx": { + "source": "iana" + }, + "application/vnd.onvif.metadata": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana", + "compressible": true, + "extensions": ["obgx"] + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osm"] + }, + "application/vnd.opentimestamps.ots": { + "source": "iana" + }, + "application/vnd.openvpi.dspx+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "iana", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "iana", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "iana", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "iana" + }, + "application/vnd.patentdive": { + "source": "iana" + }, + "application/vnd.patientecommsdoc": { + "source": "iana" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.procrate.brushset": { + "extensions": ["brushset"] + }, + "application/vnd.procreate.brush": { + "extensions": ["brush"] + }, + "application/vnd.procreate.dream": { + "extensions": ["drm"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.psfs": { + "source": "iana" + }, + "application/vnd.pt.mundusmundi": { + "source": "iana" + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtm"] + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quarantainenet": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.rar": { + "source": "iana", + "extensions": ["rar"] + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musicxml"] + }, + "application/vnd.relpipe": { + "source": "iana" + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.resilient.logic": { + "source": "iana" + }, + "application/vnd.restful+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "compressible": true, + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sar": { + "source": "iana" + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.seis+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shade-save-file": { + "source": "iana" + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.shootproof+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shopkick+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shp": { + "source": "iana" + }, + "application/vnd.shx": { + "source": "iana" + }, + "application/vnd.sigrok.session": { + "source": "iana" + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sketchometry": { + "source": "iana" + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.smintio.portals.archive": { + "source": "iana" + }, + "application/vnd.snesdev-page-table": { + "source": "iana" + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fo"] + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sqlite3": { + "source": "iana" + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wadl"] + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.sybyl.mol2": { + "source": "iana" + }, + "application/vnd.sycle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.syft+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["ddf"] + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tableschema+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.tri.onesource": { + "source": "iana" + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uic.osdm+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uoml","uo"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.vel+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.veraison.tsm-report+cbor": { + "source": "iana" + }, + "application/vnd.veraison.tsm-report+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.veritone.aion+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.veryant.thin": { + "source": "iana" + }, + "application/vnd.ves.encrypted": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw","vsdx","vtx"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vocalshaper.vsp4": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.wasmflow.wafl": { + "source": "iana" + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.dpp": { + "source": "iana" + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordlift": { + "source": "iana" + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.wv.ssp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xarin.cpj": { + "source": "iana" + }, + "application/vnd.xecrets-encrypted": { + "source": "iana" + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["vxml"] + }, + "application/voucher-cms+json": { + "source": "iana", + "compressible": true + }, + "application/voucher-jws+json": { + "source": "iana", + "compressible": true + }, + "application/vp": { + "source": "iana" + }, + "application/vp+cose": { + "source": "iana" + }, + "application/vp+jwt": { + "source": "iana" + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/wasm": { + "source": "iana", + "compressible": true, + "extensions": ["wasm"] + }, + "application/watcherinfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wif"] + }, + "application/webpush-options+json": { + "source": "iana", + "compressible": true + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-arj": { + "compressible": false, + "extensions": ["arj"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blender": { + "extensions": ["blend"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-compressed": { + "extensions": ["rar"] + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "compressible": true, + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-ipynb+json": { + "compressible": true, + "extensions": ["ipynb"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-iwork-keynote-sffkey": { + "extensions": ["key"] + }, + "application/x-iwork-numbers-sffnumbers": { + "extensions": ["numbers"] + }, + "application/x-iwork-pages-sffpages": { + "extensions": ["pages"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-keepass2": { + "extensions": ["kdbx"] + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "source": "apache", + "extensions": ["nc","cdf"] + }, + "application/x-ns-proxy-autoconfig": { + "compressible": true, + "extensions": ["pac"] + }, + "application/x-nzb": { + "source": "apache", + "extensions": ["nzb"] + }, + "application/x-perl": { + "source": "nginx", + "extensions": ["pl","pm"] + }, + "application/x-pilot": { + "source": "nginx", + "extensions": ["prc","pdb"] + }, + "application/x-pkcs12": { + "source": "apache", + "compressible": false, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-pki-message": { + "source": "iana" + }, + "application/x-rar-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["rar"] + }, + "application/x-redhat-package-manager": { + "source": "nginx", + "extensions": ["rpm"] + }, + "application/x-research-info-systems": { + "source": "apache", + "extensions": ["ris"] + }, + "application/x-sea": { + "source": "nginx", + "extensions": ["sea"] + }, + "application/x-sh": { + "source": "apache", + "compressible": true, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-virtualbox-hdd": { + "compressible": true, + "extensions": ["hdd"] + }, + "application/x-virtualbox-ova": { + "compressible": true, + "extensions": ["ova"] + }, + "application/x-virtualbox-ovf": { + "compressible": true, + "extensions": ["ovf"] + }, + "application/x-virtualbox-vbox": { + "compressible": true, + "extensions": ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + "compressible": false, + "extensions": ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + "compressible": true, + "extensions": ["vdi"] + }, + "application/x-virtualbox-vhd": { + "compressible": true, + "extensions": ["vhd"] + }, + "application/x-virtualbox-vmdk": { + "compressible": true, + "extensions": ["vmdk"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "iana", + "extensions": ["der","crt","pem"] + }, + "application/x-x509-ca-ra-cert": { + "source": "iana" + }, + "application/x-x509-next-ca-cert": { + "source": "iana" + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zip-compressed": { + "extensions": ["zip"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana", + "compressible": true + }, + "application/xaml+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xav"] + }, + "application/xcap-caps+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xca"] + }, + "application/xcap-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xel"] + }, + "application/xcap-error+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-ns+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xns"] + }, + "application/xcon-conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana", + "compressible": true + }, + "application/xenc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xenc"] + }, + "application/xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache", + "compressible": true + }, + "application/xliff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xlf"] + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd","rng"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/xmpp+xml": { + "source": "iana", + "compressible": true + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsl","xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yaml": { + "source": "iana" + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yang-data+cbor": { + "source": "iana" + }, + "application/yang-data+json": { + "source": "iana", + "compressible": true + }, + "application/yang-data+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+json": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-sid+json": { + "source": "iana", + "compressible": true + }, + "application/yin+xml": { + "source": "iana", + "compressible": true, + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zip+dotlottie": { + "extensions": ["lottie"] + }, + "application/zlib": { + "source": "iana" + }, + "application/zstd": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana", + "compressible": false, + "extensions": ["3gpp"] + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/aac": { + "source": "iana", + "extensions": ["adts","aac"] + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana", + "extensions": ["amr"] + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/flac": { + "source": "iana" + }, + "audio/flexfec": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/matroska": { + "source": "iana" + }, + "audio/melp": { + "source": "iana" + }, + "audio/melp1200": { + "source": "iana" + }, + "audio/melp2400": { + "source": "iana" + }, + "audio/melp600": { + "source": "iana" + }, + "audio/mhas": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/midi-clip": { + "source": "iana" + }, + "audio/mobile-xmf": { + "source": "iana", + "extensions": ["mxmf"] + }, + "audio/mp3": { + "compressible": false, + "extensions": ["mp3"] + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["m4a","mp4a","m4b"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx","opus"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/scip": { + "source": "iana" + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sofa": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tetra_acelp": { + "source": "iana" + }, + "audio/tetra_acelp_bb": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/tsvcis": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/usac": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dts.uhd": { + "source": "iana" + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.presonus.multitrack": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "apache" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/collection": { + "source": "iana", + "extensions": ["ttc"] + }, + "font/otf": { + "source": "iana", + "compressible": true, + "extensions": ["otf"] + }, + "font/sfnt": { + "source": "iana" + }, + "font/ttf": { + "source": "iana", + "compressible": true, + "extensions": ["ttf"] + }, + "font/woff": { + "source": "iana", + "extensions": ["woff"] + }, + "font/woff2": { + "source": "iana", + "extensions": ["woff2"] + }, + "image/aces": { + "source": "iana", + "extensions": ["exr"] + }, + "image/apng": { + "source": "iana", + "compressible": false, + "extensions": ["apng"] + }, + "image/avci": { + "source": "iana", + "extensions": ["avci"] + }, + "image/avcs": { + "source": "iana", + "extensions": ["avcs"] + }, + "image/avif": { + "source": "iana", + "compressible": false, + "extensions": ["avif"] + }, + "image/bmp": { + "source": "iana", + "compressible": true, + "extensions": ["bmp","dib"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/dicom-rle": { + "source": "iana", + "extensions": ["drle"] + }, + "image/dpx": { + "source": "iana", + "extensions": ["dpx"] + }, + "image/emf": { + "source": "iana", + "extensions": ["emf"] + }, + "image/fits": { + "source": "iana", + "extensions": ["fits"] + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/heic": { + "source": "iana", + "extensions": ["heic"] + }, + "image/heic-sequence": { + "source": "iana", + "extensions": ["heics"] + }, + "image/heif": { + "source": "iana", + "extensions": ["heif"] + }, + "image/heif-sequence": { + "source": "iana", + "extensions": ["heifs"] + }, + "image/hej2k": { + "source": "iana", + "extensions": ["hej2"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/j2c": { + "source": "iana" + }, + "image/jaii": { + "source": "iana", + "extensions": ["jaii"] + }, + "image/jais": { + "source": "iana", + "extensions": ["jais"] + }, + "image/jls": { + "source": "iana", + "extensions": ["jls"] + }, + "image/jp2": { + "source": "iana", + "compressible": false, + "extensions": ["jp2","jpg2"] + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpg","jpeg","jpe"] + }, + "image/jph": { + "source": "iana", + "extensions": ["jph"] + }, + "image/jphc": { + "source": "iana", + "extensions": ["jhc"] + }, + "image/jpm": { + "source": "iana", + "compressible": false, + "extensions": ["jpm","jpgm"] + }, + "image/jpx": { + "source": "iana", + "compressible": false, + "extensions": ["jpx","jpf"] + }, + "image/jxl": { + "source": "iana", + "extensions": ["jxl"] + }, + "image/jxr": { + "source": "iana", + "extensions": ["jxr"] + }, + "image/jxra": { + "source": "iana", + "extensions": ["jxra"] + }, + "image/jxrs": { + "source": "iana", + "extensions": ["jxrs"] + }, + "image/jxs": { + "source": "iana", + "extensions": ["jxs"] + }, + "image/jxsc": { + "source": "iana", + "extensions": ["jxsc"] + }, + "image/jxsi": { + "source": "iana", + "extensions": ["jxsi"] + }, + "image/jxss": { + "source": "iana", + "extensions": ["jxss"] + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/ktx2": { + "source": "iana", + "extensions": ["ktx2"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false, + "extensions": ["jfif"] + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif","btf"] + }, + "image/prs.pti": { + "source": "iana", + "extensions": ["pti"] + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana", + "extensions": ["t38"] + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tif","tiff"] + }, + "image/tiff-fx": { + "source": "iana", + "extensions": ["tfx"] + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana", + "extensions": ["azv"] + }, + "image/vnd.clip": { + "source": "iana" + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana", + "compressible": true, + "extensions": ["ico"] + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-dds": { + "compressible": true, + "extensions": ["dds"] + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.pco.b16": { + "source": "iana", + "extensions": ["b16"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana", + "extensions": ["tap"] + }, + "image/vnd.valve.source.texture": { + "source": "iana", + "extensions": ["vtf"] + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana", + "extensions": ["pcx"] + }, + "image/webp": { + "source": "iana", + "extensions": ["webp"] + }, + "image/wmf": { + "source": "iana", + "extensions": ["wmf"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-adobe-dng": { + "extensions": ["dng"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-emf": { + "source": "iana" + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "compressible": true, + "extensions": ["ico"] + }, + "image/x-jng": { + "source": "nginx", + "extensions": ["jng"] + }, + "image/x-mrsid-image": { + "source": "apache", + "extensions": ["sid"] + }, + "image/x-ms-bmp": { + "source": "nginx", + "compressible": true, + "extensions": ["bmp"] + }, + "image/x-pcx": { + "source": "apache", + "extensions": ["pcx"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-wmf": { + "source": "iana" + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/bhttp": { + "source": "iana" + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana", + "extensions": [ + "disposition-notification" + ] + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana", + "extensions": ["u8msg"] + }, + "message/global-delivery-status": { + "source": "iana", + "extensions": ["u8dsn"] + }, + "message/global-disposition-notification": { + "source": "iana", + "extensions": ["u8mdn"] + }, + "message/global-headers": { + "source": "iana", + "extensions": ["u8hdr"] + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/mls": { + "source": "iana" + }, + "message/news": { + "source": "apache" + }, + "message/ohttp-req": { + "source": "iana" + }, + "message/ohttp-res": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime","mht","mhtml"] + }, + "message/s-http": { + "source": "apache" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "apache" + }, + "message/vnd.wfa.wsc": { + "source": "iana", + "extensions": ["wsc"] + }, + "model/3mf": { + "source": "iana", + "extensions": ["3mf"] + }, + "model/e57": { + "source": "iana" + }, + "model/gltf+json": { + "source": "iana", + "compressible": true, + "extensions": ["gltf"] + }, + "model/gltf-binary": { + "source": "iana", + "compressible": true, + "extensions": ["glb"] + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/jt": { + "source": "iana", + "extensions": ["jt"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/mtl": { + "source": "iana", + "extensions": ["mtl"] + }, + "model/obj": { + "source": "iana", + "extensions": ["obj"] + }, + "model/prc": { + "source": "iana", + "extensions": ["prc"] + }, + "model/step": { + "source": "iana", + "extensions": ["step","stp","stpnc","p21","210"] + }, + "model/step+xml": { + "source": "iana", + "compressible": true, + "extensions": ["stpx"] + }, + "model/step+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpz"] + }, + "model/step-xml+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpxz"] + }, + "model/stl": { + "source": "iana", + "extensions": ["stl"] + }, + "model/u3d": { + "source": "iana", + "extensions": ["u3d"] + }, + "model/vnd.bary": { + "source": "iana", + "extensions": ["bary"] + }, + "model/vnd.cld": { + "source": "iana", + "extensions": ["cld"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana", + "compressible": true + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana", + "extensions": ["ogex"] + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana", + "extensions": ["x_b"] + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana", + "extensions": ["x_t"] + }, + "model/vnd.pytha.pyox": { + "source": "iana", + "extensions": ["pyo","pyox"] + }, + "model/vnd.rosette.annotated-data-model": { + "source": "iana" + }, + "model/vnd.sap.vds": { + "source": "iana", + "extensions": ["vds"] + }, + "model/vnd.usda": { + "source": "iana", + "extensions": ["usda"] + }, + "model/vnd.usdz+zip": { + "source": "iana", + "compressible": false, + "extensions": ["usdz"] + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana", + "extensions": ["bsp"] + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana", + "extensions": ["x3db"] + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana", + "extensions": ["x3dv"] + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana" + }, + "multipart/multilingual": { + "source": "iana" + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/vnd.bint.med-plus": { + "source": "iana" + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/cql": { + "source": "iana" + }, + "text/cql-expression": { + "source": "iana" + }, + "text/cql-identifier": { + "source": "iana" + }, + "text/css": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "apache" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fhirpath": { + "source": "iana" + }, + "text/flexfec": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/gff3": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/hl7v2": { + "source": "iana" + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js","mjs"] + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "compressible": true, + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana", + "compressible": true, + "extensions": ["md","markdown"] + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mdx": { + "compressible": true, + "extensions": ["mdx"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana", + "charset": "UTF-8" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana", + "charset": "UTF-8" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/prs.prop.logic": { + "source": "iana" + }, + "text/prs.texi": { + "source": "iana" + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/shaclc": { + "source": "iana" + }, + "text/shex": { + "source": "iana", + "extensions": ["shex"] + }, + "text/slim": { + "extensions": ["slim","slm"] + }, + "text/spdx": { + "source": "iana", + "extensions": ["spdx"] + }, + "text/strings": { + "source": "iana" + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.ascii-art": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.exchangeable": { + "source": "iana" + }, + "text/vnd.familysearch.gedcom": { + "source": "iana", + "extensions": ["ged"] + }, + "text/vnd.ficlab.flt": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.gml": { + "source": "iana" + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.hans": { + "source": "iana" + }, + "text/vnd.hgl": { + "source": "iana" + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.senx.warpscript": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "apache" + }, + "text/vnd.sosi": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.vcf": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vnd.zoo.kcl": { + "source": "iana" + }, + "text/vtt": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/wgsl": { + "source": "iana", + "extensions": ["wgsl"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-org": { + "compressible": true, + "extensions": ["org"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "compressible": true, + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "iana" + }, + "video/3gpp": { + "source": "iana", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "iana" + }, + "video/3gpp2": { + "source": "iana", + "extensions": ["3g2"] + }, + "video/av1": { + "source": "iana" + }, + "video/bmpeg": { + "source": "iana" + }, + "video/bt656": { + "source": "iana" + }, + "video/celb": { + "source": "iana" + }, + "video/dv": { + "source": "iana" + }, + "video/encaprtp": { + "source": "iana" + }, + "video/evc": { + "source": "iana" + }, + "video/ffv1": { + "source": "iana" + }, + "video/flexfec": { + "source": "iana" + }, + "video/h261": { + "source": "iana", + "extensions": ["h261"] + }, + "video/h263": { + "source": "iana", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "iana" + }, + "video/h263-2000": { + "source": "iana" + }, + "video/h264": { + "source": "iana", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "iana" + }, + "video/h264-svc": { + "source": "iana" + }, + "video/h265": { + "source": "iana" + }, + "video/h266": { + "source": "iana" + }, + "video/iso.segment": { + "source": "iana", + "extensions": ["m4s"] + }, + "video/jpeg": { + "source": "iana", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "iana" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/jxsv": { + "source": "iana" + }, + "video/lottie+json": { + "source": "iana", + "compressible": true + }, + "video/matroska": { + "source": "iana" + }, + "video/matroska-3d": { + "source": "iana" + }, + "video/mj2": { + "source": "iana", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "iana" + }, + "video/mp2p": { + "source": "iana" + }, + "video/mp2t": { + "source": "iana", + "extensions": ["ts","m2t","m2ts","mts"] + }, + "video/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "iana" + }, + "video/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "iana" + }, + "video/mpv": { + "source": "iana" + }, + "video/nv": { + "source": "iana" + }, + "video/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "iana" + }, + "video/pointer": { + "source": "iana" + }, + "video/quicktime": { + "source": "iana", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raptorfec": { + "source": "iana" + }, + "video/raw": { + "source": "iana" + }, + "video/rtp-enc-aescm128": { + "source": "iana" + }, + "video/rtploopback": { + "source": "iana" + }, + "video/rtx": { + "source": "iana" + }, + "video/scip": { + "source": "iana" + }, + "video/smpte291": { + "source": "iana" + }, + "video/smpte292m": { + "source": "iana" + }, + "video/ulpfec": { + "source": "iana" + }, + "video/vc1": { + "source": "iana" + }, + "video/vc2": { + "source": "iana" + }, + "video/vnd.cctv": { + "source": "iana" + }, + "video/vnd.dece.hd": { + "source": "iana", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "iana", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "iana" + }, + "video/vnd.dece.pd": { + "source": "iana", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "iana", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "iana", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "iana" + }, + "video/vnd.directv.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dvb.file": { + "source": "iana", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "iana", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "iana" + }, + "video/vnd.motorola.video": { + "source": "iana" + }, + "video/vnd.motorola.videop": { + "source": "iana" + }, + "video/vnd.mpegurl": { + "source": "iana", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "iana", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "iana" + }, + "video/vnd.nokia.mp4vr": { + "source": "iana" + }, + "video/vnd.nokia.videovoip": { + "source": "iana" + }, + "video/vnd.objectvideo": { + "source": "iana" + }, + "video/vnd.planar": { + "source": "iana" + }, + "video/vnd.radgamettools.bink": { + "source": "iana" + }, + "video/vnd.radgamettools.smacker": { + "source": "apache" + }, + "video/vnd.sealed.mpeg1": { + "source": "iana" + }, + "video/vnd.sealed.mpeg4": { + "source": "iana" + }, + "video/vnd.sealed.swf": { + "source": "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "iana" + }, + "video/vnd.uvvu.mp4": { + "source": "iana", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "iana", + "extensions": ["viv"] + }, + "video/vnd.youtube.yt": { + "source": "iana" + }, + "video/vp8": { + "source": "iana" + }, + "video/vp9": { + "source": "iana" + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/node_modules/mime-db/index.js b/node_modules/mime-db/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ec2be30de1663c20ea2166f33a583c9c0b84d029 --- /dev/null +++ b/node_modules/mime-db/index.js @@ -0,0 +1,12 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/node_modules/mime-db/package.json b/node_modules/mime-db/package.json new file mode 100644 index 0000000000000000000000000000000000000000..289a370c8f644df453d0fb395ba4a5f3fd0d3e27 --- /dev/null +++ b/node_modules/mime-db/package.json @@ -0,0 +1,56 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.54.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)", + "Robert Kieffer (http://github.com/broofa)" + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": "jshttp/mime-db", + "devDependencies": { + "csv-parse": "4.16.3", + "eslint": "8.32.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.27.5", + "eslint-plugin-markdown": "3.0.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.1.1", + "eslint-plugin-standard": "4.1.0", + "media-typer": "1.1.0", + "mocha": "10.2.0", + "nyc": "15.1.0", + "stream-to-array": "2.3.0", + "undici": "7.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "fetch": "node scripts/fetch-apache && node scripts/fetch-iana && node scripts/fetch-nginx", + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/mime-types/HISTORY.md b/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..9ba2dc077dd9f5ed292fcf3d7eaa2c396765a9d1 --- /dev/null +++ b/node_modules/mime-types/HISTORY.md @@ -0,0 +1,428 @@ +3.0.2 / 2025-11-20 +=================== + +* Fix: update JSDoc to reflect that functions return only `false` or `string`, not `boolean|string`. +* Fix: refined mime-score logic so `.mp4` resolves correctly +* Fix:reflect the current Node.js version supported to ≥ 18 (See 3.0.0 for more details). + +3.0.1 / 2025-03-26 +=================== + +* deps: mime-db@1.54.0 + +3.0.0 / 2024-08-31 +=================== + +* Drop support for node <18 +* deps: mime-db@1.53.0 +* resolve extension conflicts with mime-score (#119) + * asc -> application/pgp-signature is now application/pgp-keys + * mpp -> application/vnd.ms-project is now application/dash-patch+xml + * ac -> application/vnd.nokia.n-gage.ac+xml is now application/pkix-attr-cert + * bdoc -> application/x-bdoc is now application/bdoc + * wmz -> application/x-msmetafile is now application/x-ms-wmz + * xsl -> application/xslt+xml is now application/xml + * wav -> audio/wave is now audio/wav + * rtf -> text/rtf is now application/rtf + * xml -> text/xml is now application/xml + * mp4 -> video/mp4 is now application/mp4 + * mpg4 -> video/mp4 is now application/mp4 + + +2.1.35 / 2022-03-12 +=================== + + * deps: mime-db@1.52.0 + - Add extensions from IANA for more `image/*` types + - Add extension `.asc` to `application/pgp-keys` + - Add extensions to various XML types + - Add new upstream MIME types + +2.1.34 / 2021-11-08 +=================== + + * deps: mime-db@1.51.0 + - Add new upstream MIME types + +2.1.33 / 2021-10-01 +=================== + + * deps: mime-db@1.50.0 + - Add deprecated iWorks mime types and extensions + - Add new upstream MIME types + +2.1.32 / 2021-07-27 +=================== + + * deps: mime-db@1.49.0 + - Add extension `.trig` to `application/trig` + - Add new upstream MIME types + +2.1.31 / 2021-06-01 +=================== + + * deps: mime-db@1.48.0 + - Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + - Add new upstream MIME types + +2.1.30 / 2021-04-02 +=================== + + * deps: mime-db@1.47.0 + - Add extension `.amr` to `audio/amr` + - Remove ambigious extensions from IANA for `application/*+xml` types + - Update primary extension to `.es` for `application/ecmascript` + +2.1.29 / 2021-02-17 +=================== + + * deps: mime-db@1.46.0 + - Add extension `.amr` to `audio/amr` + - Add extension `.m4s` to `video/iso.segment` + - Add extension `.opus` to `audio/ogg` + - Add new upstream MIME types + +2.1.28 / 2021-01-01 +=================== + + * deps: mime-db@1.45.0 + - Add `application/ubjson` with extension `.ubj` + - Add `image/avif` with extension `.avif` + - Add `image/ktx2` with extension `.ktx2` + - Add extension `.dbf` to `application/vnd.dbf` + - Add extension `.rar` to `application/vnd.rar` + - Add extension `.td` to `application/urc-targetdesc+xml` + - Add new upstream MIME types + - Fix extension of `application/vnd.apple.keynote` to be `.key` + +2.1.27 / 2020-04-23 +=================== + + * deps: mime-db@1.44.0 + - Add charsets from IANA + - Add extension `.cjs` to `application/node` + - Add new upstream MIME types + +2.1.26 / 2020-01-05 +=================== + + * deps: mime-db@1.43.0 + - Add `application/x-keepass2` with extension `.kdbx` + - Add extension `.mxmf` to `audio/mobile-xmf` + - Add extensions from IANA for `application/*+xml` types + - Add new upstream MIME types + +2.1.25 / 2019-11-12 +=================== + + * deps: mime-db@1.42.0 + - Add new upstream MIME types + - Add `application/toml` with extension `.toml` + - Add `image/vnd.ms-dds` with extension `.dds` + +2.1.24 / 2019-04-20 +=================== + + * deps: mime-db@1.40.0 + - Add extensions from IANA for `model/*` types + - Add `text/mdx` with extension `.mdx` + +2.1.23 / 2019-04-17 +=================== + + * deps: mime-db@~1.39.0 + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add new upstream MIME types + +2.1.22 / 2019-02-14 +=================== + + * deps: mime-db@~1.38.0 + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add new upstream MIME types + +2.1.21 / 2018-10-19 +=================== + + * deps: mime-db@~1.37.0 + - Add extensions to HEIC image types + - Add new upstream MIME types + +2.1.20 / 2018-08-26 +=================== + + * deps: mime-db@~1.36.0 + - Add Apple file extensions from IANA + - Add extensions from IANA for `image/*` types + - Add new upstream MIME types + +2.1.19 / 2018-07-17 +=================== + + * deps: mime-db@~1.35.0 + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.owl` to `application/rdf+xml` + - Add new upstream MIME types + - Add UTF-8 as default charset for `text/turtle` + +2.1.18 / 2018-02-16 +=================== + + * deps: mime-db@~1.33.0 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add new upstream MIME types + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +2.1.17 / 2017-09-01 +=================== + + * deps: mime-db@~1.30.0 + - Add `application/vnd.ms-outlook` + - Add `application/x-arj` + - Add extension `.mjs` to `application/javascript` + - Add glTF types and extensions + - Add new upstream MIME types + - Add `text/x-org` + - Add VirtualBox MIME types + - Fix `source` records for `video/*` types that are IANA + - Update `font/opentype` to registered `font/otf` + +2.1.16 / 2017-07-24 +=================== + + * deps: mime-db@~1.29.0 + - Add `application/fido.trusted-apps+json` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add new upstream MIME types + - Update extensions `.md` and `.markdown` to be `text/markdown` + +2.1.15 / 2017-03-23 +=================== + + * deps: mime-db@~1.27.0 + - Add new mime types + - Add `image/apng` + +2.1.14 / 2017-01-14 +=================== + + * deps: mime-db@~1.26.0 + - Add new mime types + +2.1.13 / 2016-11-18 +=================== + + * deps: mime-db@~1.25.0 + - Add new mime types + +2.1.12 / 2016-09-18 +=================== + + * deps: mime-db@~1.24.0 + - Add new mime types + - Add `audio/mp3` + +2.1.11 / 2016-05-01 +=================== + + * deps: mime-db@~1.23.0 + - Add new mime types + +2.1.10 / 2016-02-15 +=================== + + * deps: mime-db@~1.22.0 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +2.1.1 / 2015-06-08 +================== + + * perf: fix deopt during mapping + +2.1.0 / 2015-06-07 +================== + + * Fix incorrectly treating extension-less file name as extension + - i.e. `'path/to/json'` will no longer return `application/json` + * Fix `.charset(type)` to accept parameters + * Fix `.charset(type)` to match case-insensitive + * Improve generation of extension to MIME mapping + * Refactor internals for readability and no argument reassignment + * Prefer `application/*` MIME types from the same source + * Prefer any type over `application/octet-stream` + * deps: mime-db@~1.13.0 + - Add nginx as a source + - Add new mime types + +2.0.14 / 2015-06-06 +=================== + + * deps: mime-db@~1.12.0 + - Add new mime types + +2.0.13 / 2015-05-31 +=================== + + * deps: mime-db@~1.11.0 + - Add new mime types + +2.0.12 / 2015-05-19 +=================== + + * deps: mime-db@~1.10.0 + - Add new mime types + +2.0.11 / 2015-05-05 +=================== + + * deps: mime-db@~1.9.1 + - Add new mime types + +2.0.10 / 2015-03-13 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/node_modules/mime-types/LICENSE b/node_modules/mime-types/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..06166077be4d1f620d89b9eb33c76d89e75857da --- /dev/null +++ b/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mime-types/README.md b/node_modules/mime-types/README.md new file mode 100644 index 0000000000000000000000000000000000000000..222d2b58a343a582ba534945387b9106bbd514a4 --- /dev/null +++ b/node_modules/mime-types/README.md @@ -0,0 +1,126 @@ +# mime-types + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +The ultimate javascript content-type utility. + +Similar to [the `mime@1.x` module](https://www.npmjs.com/package/mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, + `mime-types` simply returns `false`, so do + `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- No `.define()` functionality +- Bug fixes for `.lookup(path)` + +Otherwise, the API is compatible with `mime` 1.x. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install mime-types +``` + +## Note on MIME Type Data and Semver + +This package considers the programmatic api as the semver compatibility. Additionally, the package which provides the MIME data +for this package (`mime-db`) *also* considers it's programmatic api as the semver contract. This means the MIME type resolution is *not* considered +in the semver bumps. + +In the past the version of `mime-db` was pinned to give two decision points when adopting MIME data changes. This is no longer true. We still update the +`mime-db` package here as a `minor` release when necessary, but will use a `^` range going forward. This means that if you want to pin your `mime-db` data +you will need to do it in your application. While this expectation was not set in docs until now, it is how the pacakge operated, so we do not feel this is +a breaking change. + +If you wish to pin your `mime-db` version you can do that with overrides via your package manager of choice. See their documentation for how to correctly configure that. + +## Adding Types + +All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. +When given an extension, `mime.lookup` is used to get the matching +content-type, otherwise the given content-type is used. Then if the +content-type does not already have a `charset` parameter, `mime.charset` +is used to get the default charset and add to the returned content-type. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' +mime.contentType('text/html') // 'text/html; charset=utf-8' +mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-types/master?label=ci +[ci-url]: https://github.com/jshttp/mime-types/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master +[node-version-image]: https://badgen.net/npm/node/mime-types +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-types +[npm-url]: https://npmjs.org/package/mime-types +[npm-version-image]: https://badgen.net/npm/v/mime-types diff --git a/node_modules/mime-types/index.js b/node_modules/mime-types/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9725ddf3d42d9a0fccd6c3f7b69a794bf4fb6962 --- /dev/null +++ b/node_modules/mime-types/index.js @@ -0,0 +1,211 @@ +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var db = require('mime-db') +var extname = require('path').extname +var mimeScore = require('./mimeScore') + +/** + * Module variables. + * @private + */ + +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) +exports._extensionConflicts = [] + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {false|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {false|string} + */ + +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 ? exports.lookup(str) : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {false|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {false|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .slice(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps (extensions, types) { + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + types[extension] = _preferredType(extension, types[extension], type) + + // DELETE (eventually): Capture extension->type maps that change as a + // result of switching to mime-score. This is just to help make reviewing + // PR #119 easier, and can be removed once that PR is approved. + const legacyType = _preferredTypeLegacy( + extension, + types[extension], + type + ) + if (legacyType !== types[extension]) { + exports._extensionConflicts.push([extension, legacyType, types[extension]]) + } + } + }) +} + +// Resolve type conflict using mime-score +function _preferredType (ext, type0, type1) { + var score0 = type0 ? mimeScore(type0, db[type0].source) : 0 + var score1 = type1 ? mimeScore(type1, db[type1].source) : 0 + + return score0 > score1 ? type0 : type1 +} + +// Resolve type conflict using pre-mime-score logic +function _preferredTypeLegacy (ext, type0, type1) { + var SOURCE_RANK = ['nginx', 'apache', undefined, 'iana'] + + var score0 = type0 ? SOURCE_RANK.indexOf(db[type0].source) : 0 + var score1 = type1 ? SOURCE_RANK.indexOf(db[type1].source) : 0 + + if ( + exports.types[extension] !== 'application/octet-stream' && + (score0 > score1 || + (score0 === score1 && + exports.types[extension]?.slice(0, 12) === 'application/')) + ) { + return type0 + } + + return score0 > score1 ? type0 : type1 +} diff --git a/node_modules/mime-types/mimeScore.js b/node_modules/mime-types/mimeScore.js new file mode 100644 index 0000000000000000000000000000000000000000..fc2e6657aafcc80d2ca56fb9ba362cf949460478 --- /dev/null +++ b/node_modules/mime-types/mimeScore.js @@ -0,0 +1,57 @@ +// 'mime-score' back-ported to CommonJS + +// Score RFC facets (see https://tools.ietf.org/html/rfc6838#section-3) +var FACET_SCORES = { + 'prs.': 100, + 'x-': 200, + 'x.': 300, + 'vnd.': 400, + default: 900 +} + +// Score mime source (Logic originally from `jshttp/mime-types` module) +var SOURCE_SCORES = { + nginx: 10, + apache: 20, + iana: 40, + default: 30 // definitions added by `jshttp/mime-db` project? +} + +var TYPE_SCORES = { + // prefer application/xml over text/xml + // prefer application/rtf over text/rtf + application: 1, + + // prefer font/woff over application/font-woff + font: 2, + + // prefer video/mp4 over audio/mp4 over application/mp4 + // See https://www.rfc-editor.org/rfc/rfc4337.html#section-2 + audio: 2, + video: 3, + + default: 0 +} + +/** + * Get each component of the score for a mime type. The sum of these is the + * total score. The higher the score, the more "official" the type. + */ +module.exports = function mimeScore (mimeType, source = 'default') { + if (mimeType === 'application/octet-stream') { + return 0 + } + + const [type, subtype] = mimeType.split('/') + + const facet = subtype.replace(/(\.|x-).*/, '$1') + + const facetScore = FACET_SCORES[facet] || FACET_SCORES.default + const sourceScore = SOURCE_SCORES[source] || SOURCE_SCORES.default + const typeScore = TYPE_SCORES[type] || TYPE_SCORES.default + + // All else being equal prefer shorter types + const lengthScore = 1 - mimeType.length / 100 + + return facetScore + sourceScore + typeScore + lengthScore +} diff --git a/node_modules/mime-types/package.json b/node_modules/mime-types/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6c58c27afd32c5df6fd5d96dfe833b27f155770b --- /dev/null +++ b/node_modules/mime-types/package.json @@ -0,0 +1,49 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "3.0.2", + "contributors": [ + "Douglas Christopher Wilson ", + "Jeremiah Senkpiel (https://searchbeam.jit.su)", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": "jshttp/mime-types", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, + "dependencies": { + "mime-db": "^1.54.0" + }, + "devDependencies": { + "eslint": "8.33.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.32.0", + "eslint-plugin-markdown": "3.0.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.6.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "10.8.2", + "nyc": "15.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js", + "mimeScore.js" + ], + "engines": { + "node": ">=18" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec test/test.js", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/minimalistic-assert/LICENSE b/node_modules/minimalistic-assert/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..adca66b324acbda8c29f21423ae582a17400433f --- /dev/null +++ b/node_modules/minimalistic-assert/LICENSE @@ -0,0 +1,13 @@ +Copyright 2015 Calvin Metcalf + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. \ No newline at end of file diff --git a/node_modules/minimalistic-assert/index.js b/node_modules/minimalistic-assert/index.js new file mode 100644 index 0000000000000000000000000000000000000000..70b4ea5bba0a5daf39f735d6411f05333be0dff4 --- /dev/null +++ b/node_modules/minimalistic-assert/index.js @@ -0,0 +1,11 @@ +module.exports = assert; + +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} + +assert.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); +}; diff --git a/node_modules/minimalistic-assert/package.json b/node_modules/minimalistic-assert/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f8de10d9dc628f06e427b25d6b87099d05a86392 --- /dev/null +++ b/node_modules/minimalistic-assert/package.json @@ -0,0 +1,19 @@ +{ + "name": "minimalistic-assert", + "version": "1.0.1", + "description": "minimalistic-assert ===", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "https://github.com/calvinmetcalf/minimalistic-assert.git" + }, + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/calvinmetcalf/minimalistic-assert/issues" + }, + "homepage": "https://github.com/calvinmetcalf/minimalistic-assert" +} diff --git a/node_modules/minimalistic-assert/readme.md b/node_modules/minimalistic-assert/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..2ca0d256e05bf2b32d4b7468f28aea744a53cff0 --- /dev/null +++ b/node_modules/minimalistic-assert/readme.md @@ -0,0 +1,4 @@ +minimalistic-assert +=== + +very minimalistic assert module. diff --git a/node_modules/minimalistic-crypto-utils/.npmignore b/node_modules/minimalistic-crypto-utils/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..1ca957177f035203810612d1d93a66b08caff296 --- /dev/null +++ b/node_modules/minimalistic-crypto-utils/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +npm-debug.log diff --git a/node_modules/minimalistic-crypto-utils/.travis.yml b/node_modules/minimalistic-crypto-utils/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..ce24b7a773c60a3625b9698879b07c4fff694c57 --- /dev/null +++ b/node_modules/minimalistic-crypto-utils/.travis.yml @@ -0,0 +1,11 @@ +sudo: false + +language: node_js + +node_js: + - "4" + - "6" + - "stable" + +script: + - npm test diff --git a/node_modules/minimalistic-crypto-utils/README.md b/node_modules/minimalistic-crypto-utils/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9e58eba89a49af60dd6f5fbab6ad88c99e28de58 --- /dev/null +++ b/node_modules/minimalistic-crypto-utils/README.md @@ -0,0 +1,47 @@ +# minimalistic-crypto-utils +[![Build Status](https://secure.travis-ci.org/indutny/minimalistic-crypto-utils.svg)](http://travis-ci.org/indutny/minimalistic-crypto-utils) +[![NPM version](https://badge.fury.io/js/minimalistic-crypto-utils.svg)](http://badge.fury.io/js/minimalistic-crypto-utils) + +Very minimal utils that are required in order to write reasonable JS-only +crypto module. + +## Usage + +```js +const utils = require('minimalistic-crypto-utils'); + +utils.toArray('abcd', 'hex'); +utils.encode([ 1, 2, 3, 4 ], 'hex'); +utils.toHex([ 1, 2, 3, 4 ]); +``` + +#### LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2017. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. + +[0]: http://tools.ietf.org/html/rfc6979 +[1]: https://github.com/indutny/bn.js +[2]: https://github.com/indutny/hash.js +[3]: https://github.com/bitchan/eccrypto +[4]: https://github.com/wanderer/secp256k1-node diff --git a/node_modules/minimalistic-crypto-utils/lib/utils.js b/node_modules/minimalistic-crypto-utils/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..cd48daf126b35162b69f393d5b4b397c61b37a85 --- /dev/null +++ b/node_modules/minimalistic-crypto-utils/lib/utils.js @@ -0,0 +1,58 @@ +'use strict'; + +var utils = exports; + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg !== 'string') { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + return res; + } + if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } else { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } + return res; +} +utils.toArray = toArray; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +utils.zero2 = zero2; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +utils.toHex = toHex; + +utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; +}; diff --git a/node_modules/minimalistic-crypto-utils/package.json b/node_modules/minimalistic-crypto-utils/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bc4c79a4726cfea46e4b7c6f5e2a6860efdc5dfe --- /dev/null +++ b/node_modules/minimalistic-crypto-utils/package.json @@ -0,0 +1,27 @@ +{ + "name": "minimalistic-crypto-utils", + "version": "1.0.1", + "description": "Minimalistic tools for JS crypto modules", + "main": "lib/utils.js", + "scripts": { + "test": "mocha --reporter=spec test/*-test.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/minimalistic-crypto-utils.git" + }, + "keywords": [ + "minimalistic", + "utils", + "crypto" + ], + "author": "Fedor Indutny ", + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/minimalistic-crypto-utils/issues" + }, + "homepage": "https://github.com/indutny/minimalistic-crypto-utils#readme", + "devDependencies": { + "mocha": "^3.2.0" + } +} diff --git a/node_modules/minimalistic-crypto-utils/test/utils-test.js b/node_modules/minimalistic-crypto-utils/test/utils-test.js new file mode 100644 index 0000000000000000000000000000000000000000..3da812dbcc524ab9519122f49f51131050c0b8e9 --- /dev/null +++ b/node_modules/minimalistic-crypto-utils/test/utils-test.js @@ -0,0 +1,28 @@ +'use strict'; + +const assert = require('assert'); +const utils = require('../'); + +describe('utils', () => { + it('should convert to array', () => { + assert.deepEqual(utils.toArray('1234', 'hex'), [ 0x12, 0x34 ]); + assert.deepEqual(utils.toArray('1234'), [ 49, 50, 51, 52 ]); + assert.deepEqual(utils.toArray('1234', 'utf8'), [ 49, 50, 51, 52 ]); + assert.deepEqual(utils.toArray('\u1234234'), [ 18, 52, 50, 51, 52 ]); + assert.deepEqual(utils.toArray([ 1, 2, 3, 4 ]), [ 1, 2, 3, 4 ]); + }); + + it('should zero pad byte to hex', () => { + assert.equal(utils.zero2('0'), '00'); + assert.equal(utils.zero2('01'), '01'); + }); + + it('should convert to hex', () => { + assert.equal(utils.toHex([ 0, 1, 2, 3 ]), '00010203'); + }); + + it('should encode', () => { + assert.deepEqual(utils.encode([ 0, 1, 2, 3 ]), [ 0, 1, 2, 3 ]); + assert.deepEqual(utils.encode([ 0, 1, 2, 3 ], 'hex'), '00010203'); + }); +}); diff --git a/node_modules/minimist/.eslintrc b/node_modules/minimist/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..bd1a5e046b4148dfc6bfd15c8aa69c81ae809a28 --- /dev/null +++ b/node_modules/minimist/.eslintrc @@ -0,0 +1,29 @@ +{ + "root": true, + + "extends": "@ljharb/eslint-config/node/0.4", + + "rules": { + "array-element-newline": 0, + "complexity": 0, + "func-style": [2, "declaration"], + "max-lines-per-function": 0, + "max-nested-callbacks": 1, + "max-statements-per-line": 1, + "max-statements": 0, + "multiline-comment-style": 0, + "no-continue": 1, + "no-param-reassign": 1, + "no-restricted-syntax": 1, + "object-curly-newline": 0, + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "camelcase": 0, + }, + }, + ] +} diff --git a/node_modules/minimist/.github/FUNDING.yml b/node_modules/minimist/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..a9366222e92a9f9a7a2a4c4cf7cf0f011510924d --- /dev/null +++ b/node_modules/minimist/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/minimist +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/minimist/.nycrc b/node_modules/minimist/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..55c3d29367a4216abea3dc5eaa48b59826da355b --- /dev/null +++ b/node_modules/minimist/.nycrc @@ -0,0 +1,14 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "example", + "test" + ] +} diff --git a/node_modules/minimist/CHANGELOG.md b/node_modules/minimist/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..c9a1e15e6c2fe73a0ebf35040fef031b46437ba6 --- /dev/null +++ b/node_modules/minimist/CHANGELOG.md @@ -0,0 +1,298 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.8](https://github.com/minimistjs/minimist/compare/v1.2.7...v1.2.8) - 2023-02-09 + +### Merged + +- [Fix] Fix long option followed by single dash [`#17`](https://github.com/minimistjs/minimist/pull/17) +- [Tests] Remove duplicate test [`#12`](https://github.com/minimistjs/minimist/pull/12) +- [Fix] opt.string works with multiple aliases [`#10`](https://github.com/minimistjs/minimist/pull/10) + +### Fixed + +- [Fix] Fix long option followed by single dash (#17) [`#15`](https://github.com/minimistjs/minimist/issues/15) +- [Tests] Remove duplicate test (#12) [`#8`](https://github.com/minimistjs/minimist/issues/8) +- [Fix] Fix long option followed by single dash [`#15`](https://github.com/minimistjs/minimist/issues/15) +- [Fix] opt.string works with multiple aliases (#10) [`#9`](https://github.com/minimistjs/minimist/issues/9) +- [Fix] Fix handling of short option with non-trivial equals [`#5`](https://github.com/minimistjs/minimist/issues/5) +- [Tests] Remove duplicate test [`#8`](https://github.com/minimistjs/minimist/issues/8) +- [Fix] opt.string works with multiple aliases [`#9`](https://github.com/minimistjs/minimist/issues/9) + +### Commits + +- Merge tag 'v0.2.3' [`a026794`](https://github.com/minimistjs/minimist/commit/a0267947c7870fc5847cf2d437fbe33f392767da) +- [eslint] fix indentation and whitespace [`5368ca4`](https://github.com/minimistjs/minimist/commit/5368ca4147e974138a54cc0dc4cea8f756546b70) +- [eslint] fix indentation and whitespace [`e5f5067`](https://github.com/minimistjs/minimist/commit/e5f5067259ceeaf0b098d14bec910f87e58708c7) +- [eslint] more cleanup [`62fde7d`](https://github.com/minimistjs/minimist/commit/62fde7d935f83417fb046741531a9e2346a36976) +- [eslint] more cleanup [`36ac5d0`](https://github.com/minimistjs/minimist/commit/36ac5d0d95e4947d074e5737d94814034ca335d1) +- [meta] add `auto-changelog` [`73923d2`](https://github.com/minimistjs/minimist/commit/73923d223553fca08b1ba77e3fbc2a492862ae4c) +- [actions] add reusable workflows [`d80727d`](https://github.com/minimistjs/minimist/commit/d80727df77bfa9e631044d7f16368d8f09242c91) +- [eslint] add eslint; rules to enable later are warnings [`48bc06a`](https://github.com/minimistjs/minimist/commit/48bc06a1b41f00e9cdf183db34f7a51ba70e98d4) +- [eslint] fix indentation [`34b0f1c`](https://github.com/minimistjs/minimist/commit/34b0f1ccaa45183c3c4f06a91f9b405180a6f982) +- [readme] rename and add badges [`5df0fe4`](https://github.com/minimistjs/minimist/commit/5df0fe49211bd09a3636f8686a7cb3012c3e98f0) +- [Dev Deps] switch from `covert` to `nyc` [`a48b128`](https://github.com/minimistjs/minimist/commit/a48b128fdb8d427dfb20a15273f83e38d97bef07) +- [Dev Deps] update `covert`, `tape`; remove unnecessary `tap` [`f0fb958`](https://github.com/minimistjs/minimist/commit/f0fb958e9a1fe980cdffc436a211b0bda58f621b) +- [meta] create FUNDING.yml; add `funding` in package.json [`3639e0c`](https://github.com/minimistjs/minimist/commit/3639e0c819359a366387e425ab6eabf4c78d3caa) +- [meta] use `npmignore` to autogenerate an npmignore file [`be2e038`](https://github.com/minimistjs/minimist/commit/be2e038c342d8333b32f0fde67a0026b79c8150e) +- Only apps should have lockfiles [`282b570`](https://github.com/minimistjs/minimist/commit/282b570e7489d01b03f2d6d3dabf79cd3e5f84cf) +- isConstructorOrProto adapted from PR [`ef9153f`](https://github.com/minimistjs/minimist/commit/ef9153fc52b6cea0744b2239921c5dcae4697f11) +- [Dev Deps] update `@ljharb/eslint-config`, `aud` [`098873c`](https://github.com/minimistjs/minimist/commit/098873c213cdb7c92e55ae1ef5aa1af3a8192a79) +- [Dev Deps] update `@ljharb/eslint-config`, `aud` [`3124ed3`](https://github.com/minimistjs/minimist/commit/3124ed3e46306301ebb3c834874ce0241555c2c4) +- [meta] add `safe-publish-latest` [`4b927de`](https://github.com/minimistjs/minimist/commit/4b927de696d561c636b4f43bf49d4597cb36d6d6) +- [Tests] add `aud` in `posttest` [`b32d9bd`](https://github.com/minimistjs/minimist/commit/b32d9bd0ab340f4e9f8c3a97ff2a4424f25fab8c) +- [meta] update repo URLs [`f9fdfc0`](https://github.com/minimistjs/minimist/commit/f9fdfc032c54884d9a9996a390c63cd0719bbe1a) +- [actions] Avoid 0.6 tests due to build failures [`ba92fe6`](https://github.com/minimistjs/minimist/commit/ba92fe6ebbdc0431cca9a2ea8f27beb492f5e4ec) +- [Dev Deps] update `tape` [`950eaa7`](https://github.com/minimistjs/minimist/commit/950eaa74f112e04d23e9c606c67472c46739b473) +- [Dev Deps] add missing `npmignore` dev dep [`3226afa`](https://github.com/minimistjs/minimist/commit/3226afaf09e9d127ca369742437fe6e88f752d6b) +- Merge tag 'v0.2.2' [`980d7ac`](https://github.com/minimistjs/minimist/commit/980d7ac61a0b4bd552711251ac107d506b23e41f) + +## [v1.2.7](https://github.com/minimistjs/minimist/compare/v1.2.6...v1.2.7) - 2022-10-10 + +### Commits + +- [meta] add `auto-changelog` [`0ebf4eb`](https://github.com/minimistjs/minimist/commit/0ebf4ebcd5f7787a5524d31a849ef41316b83c3c) +- [actions] add reusable workflows [`e115b63`](https://github.com/minimistjs/minimist/commit/e115b63fa9d3909f33b00a2db647ff79068388de) +- [eslint] add eslint; rules to enable later are warnings [`f58745b`](https://github.com/minimistjs/minimist/commit/f58745b9bb84348e1be72af7dbba5840c7c13013) +- [Dev Deps] switch from `covert` to `nyc` [`ab03356`](https://github.com/minimistjs/minimist/commit/ab033567b9c8b31117cb026dc7f1e592ce455c65) +- [readme] rename and add badges [`236f4a0`](https://github.com/minimistjs/minimist/commit/236f4a07e4ebe5ee44f1496ec6974991ab293ffd) +- [meta] create FUNDING.yml; add `funding` in package.json [`783a49b`](https://github.com/minimistjs/minimist/commit/783a49bfd47e8335d3098a8cac75662cf71eb32a) +- [meta] use `npmignore` to autogenerate an npmignore file [`f81ece6`](https://github.com/minimistjs/minimist/commit/f81ece6aaec2fa14e69ff4f1e0407a8c4e2635a2) +- Only apps should have lockfiles [`56cad44`](https://github.com/minimistjs/minimist/commit/56cad44c7f879b9bb5ec18fcc349308024a89bfc) +- [Dev Deps] update `covert`, `tape`; remove unnecessary `tap` [`49c5f9f`](https://github.com/minimistjs/minimist/commit/49c5f9fb7e6a92db9eb340cc679de92fb3aacded) +- [Tests] add `aud` in `posttest` [`228ae93`](https://github.com/minimistjs/minimist/commit/228ae938f3cd9db9dfd8bd7458b076a7b2aef280) +- [meta] add `safe-publish-latest` [`01fc23f`](https://github.com/minimistjs/minimist/commit/01fc23f5104f85c75059972e01dd33796ab529ff) +- [meta] update repo URLs [`6b164c7`](https://github.com/minimistjs/minimist/commit/6b164c7d68e0b6bf32f894699effdfb7c63041dd) + +## [v1.2.6](https://github.com/minimistjs/minimist/compare/v1.2.5...v1.2.6) - 2022-03-21 + +### Commits + +- test from prototype pollution PR [`bc8ecee`](https://github.com/minimistjs/minimist/commit/bc8ecee43875261f4f17eb20b1243d3ed15e70eb) +- isConstructorOrProto adapted from PR [`c2b9819`](https://github.com/minimistjs/minimist/commit/c2b981977fa834b223b408cfb860f933c9811e4d) +- security notice for additional prototype pollution issue [`ef88b93`](https://github.com/minimistjs/minimist/commit/ef88b9325f77b5ee643ccfc97e2ebda577e4c4e2) + +## [v1.2.5](https://github.com/minimistjs/minimist/compare/v1.2.4...v1.2.5) - 2020-03-12 + +## [v1.2.4](https://github.com/minimistjs/minimist/compare/v1.2.3...v1.2.4) - 2020-03-11 + +### Commits + +- security notice [`4cf1354`](https://github.com/minimistjs/minimist/commit/4cf1354839cb972e38496d35e12f806eea92c11f) +- additional test for constructor prototype pollution [`1043d21`](https://github.com/minimistjs/minimist/commit/1043d212c3caaf871966e710f52cfdf02f9eea4b) + +## [v1.2.3](https://github.com/minimistjs/minimist/compare/v1.2.2...v1.2.3) - 2020-03-10 + +### Commits + +- more failing proto pollution tests [`13c01a5`](https://github.com/minimistjs/minimist/commit/13c01a5327736903704984b7f65616b8476850cc) +- even more aggressive checks for protocol pollution [`38a4d1c`](https://github.com/minimistjs/minimist/commit/38a4d1caead72ef99e824bb420a2528eec03d9ab) + +## [v1.2.2](https://github.com/minimistjs/minimist/compare/v1.2.1...v1.2.2) - 2020-03-10 + +### Commits + +- failing test for protocol pollution [`0efed03`](https://github.com/minimistjs/minimist/commit/0efed0340ec8433638758f7ca0c77cb20a0bfbab) +- cleanup [`67d3722`](https://github.com/minimistjs/minimist/commit/67d3722413448d00a62963d2d30c34656a92d7e2) +- console.dir -> console.log [`47acf72`](https://github.com/minimistjs/minimist/commit/47acf72c715a630bf9ea013867f47f1dd69dfc54) +- don't assign onto __proto__ [`63e7ed0`](https://github.com/minimistjs/minimist/commit/63e7ed05aa4b1889ec2f3b196426db4500cbda94) + +## [v1.2.1](https://github.com/minimistjs/minimist/compare/v1.2.0...v1.2.1) - 2020-03-10 + +### Merged + +- move the `opts['--']` example back where it belongs [`#63`](https://github.com/minimistjs/minimist/pull/63) + +### Commits + +- add test [`6be5dae`](https://github.com/minimistjs/minimist/commit/6be5dae35a32a987bcf4137fcd6c19c5200ee909) +- fix bad boolean regexp [`ac3fc79`](https://github.com/minimistjs/minimist/commit/ac3fc796e63b95128fdbdf67ea7fad71bd59aa76) + +## [v1.2.0](https://github.com/minimistjs/minimist/compare/v1.1.3...v1.2.0) - 2015-08-24 + +### Commits + +- failing -k=v short test [`63416b8`](https://github.com/minimistjs/minimist/commit/63416b8cd1d0d70e4714564cce465a36e4dd26d7) +- kv short fix [`6bbe145`](https://github.com/minimistjs/minimist/commit/6bbe14529166245e86424f220a2321442fe88dc3) +- failing kv short test [`f72ab7f`](https://github.com/minimistjs/minimist/commit/f72ab7f4572adc52902c9b6873cc969192f01b10) +- fixed kv test [`f5a48c3`](https://github.com/minimistjs/minimist/commit/f5a48c3e50e40ca54f00c8e84de4b4d6e9897fa8) +- enforce space between arg key and value [`86b321a`](https://github.com/minimistjs/minimist/commit/86b321affe648a8e016c095a4f0efa9d9074f502) + +## [v1.1.3](https://github.com/minimistjs/minimist/compare/v1.1.2...v1.1.3) - 2015-08-06 + +### Commits + +- add failing test - boolean alias array [`0fa3c5b`](https://github.com/minimistjs/minimist/commit/0fa3c5b3dd98551ddecf5392831b4c21211743fc) +- fix boolean values with multiple aliases [`9c0a6e7`](https://github.com/minimistjs/minimist/commit/9c0a6e7de25a273b11bbf9a7464f0bd833779795) + +## [v1.1.2](https://github.com/minimistjs/minimist/compare/v1.1.1...v1.1.2) - 2015-07-22 + +### Commits + +- Convert boolean arguments to boolean values [`8f3dc27`](https://github.com/minimistjs/minimist/commit/8f3dc27cf833f1d54671b6d0bcb55c2fe19672a9) +- use non-ancient npm, node 0.12 and iojs [`61ed1d0`](https://github.com/minimistjs/minimist/commit/61ed1d034b9ec7282764ce76f3992b1a0b4906ae) +- an older npm for 0.8 [`25cf778`](https://github.com/minimistjs/minimist/commit/25cf778b1220e7838a526832ad6972f75244054f) + +## [v1.1.1](https://github.com/minimistjs/minimist/compare/v1.1.0...v1.1.1) - 2015-03-10 + +### Commits + +- check that they type of a value is a boolean, not just that it is currently set to a boolean [`6863198`](https://github.com/minimistjs/minimist/commit/6863198e36139830ff1f20ffdceaddd93f2c1db9) +- upgrade tape, fix type issues from old tape version [`806712d`](https://github.com/minimistjs/minimist/commit/806712df91604ed02b8e39aa372b84aea659ee34) +- test for setting a boolean to a null default [`8c444fe`](https://github.com/minimistjs/minimist/commit/8c444fe89384ded7d441c120915ea60620b01dd3) +- if the previous value was a boolean, without an default (or with an alias) don't make an array either [`e5f419a`](https://github.com/minimistjs/minimist/commit/e5f419a3b5b3bc3f9e5ac71b7040621af70ed2dd) + +## [v1.1.0](https://github.com/minimistjs/minimist/compare/v1.0.0...v1.1.0) - 2014-08-10 + +### Commits + +- add support for handling "unknown" options not registered with the parser. [`6f3cc5d`](https://github.com/minimistjs/minimist/commit/6f3cc5d4e84524932a6ef2ce3592acc67cdd4383) +- reformat package.json [`02ed371`](https://github.com/minimistjs/minimist/commit/02ed37115194d3697ff358e8e25e5e66bab1d9f8) +- coverage script [`e5531ba`](https://github.com/minimistjs/minimist/commit/e5531ba0479da3b8138d3d8cac545d84ccb1c8df) +- extra fn to get 100% coverage again [`a6972da`](https://github.com/minimistjs/minimist/commit/a6972da89e56bf77642f8ec05a13b6558db93498) + +## [v1.0.0](https://github.com/minimistjs/minimist/compare/v0.2.3...v1.0.0) - 2014-08-10 + +### Commits + +- added stopEarly option [`471c7e4`](https://github.com/minimistjs/minimist/commit/471c7e4a7e910fc7ad8f9df850a186daf32c64e9) +- fix list [`fef6ae7`](https://github.com/minimistjs/minimist/commit/fef6ae79c38b9dc1c49569abb7cd04eb965eac5e) + +## [v0.2.3](https://github.com/minimistjs/minimist/compare/v0.2.2...v0.2.3) - 2023-02-09 + +### Merged + +- [Fix] Fix long option followed by single dash [`#17`](https://github.com/minimistjs/minimist/pull/17) +- [Tests] Remove duplicate test [`#12`](https://github.com/minimistjs/minimist/pull/12) +- [Fix] opt.string works with multiple aliases [`#10`](https://github.com/minimistjs/minimist/pull/10) + +### Fixed + +- [Fix] Fix long option followed by single dash (#17) [`#15`](https://github.com/minimistjs/minimist/issues/15) +- [Tests] Remove duplicate test (#12) [`#8`](https://github.com/minimistjs/minimist/issues/8) +- [Fix] opt.string works with multiple aliases (#10) [`#9`](https://github.com/minimistjs/minimist/issues/9) + +### Commits + +- [eslint] fix indentation and whitespace [`e5f5067`](https://github.com/minimistjs/minimist/commit/e5f5067259ceeaf0b098d14bec910f87e58708c7) +- [eslint] more cleanup [`36ac5d0`](https://github.com/minimistjs/minimist/commit/36ac5d0d95e4947d074e5737d94814034ca335d1) +- [eslint] fix indentation [`34b0f1c`](https://github.com/minimistjs/minimist/commit/34b0f1ccaa45183c3c4f06a91f9b405180a6f982) +- isConstructorOrProto adapted from PR [`ef9153f`](https://github.com/minimistjs/minimist/commit/ef9153fc52b6cea0744b2239921c5dcae4697f11) +- [Dev Deps] update `@ljharb/eslint-config`, `aud` [`098873c`](https://github.com/minimistjs/minimist/commit/098873c213cdb7c92e55ae1ef5aa1af3a8192a79) +- [Dev Deps] add missing `npmignore` dev dep [`3226afa`](https://github.com/minimistjs/minimist/commit/3226afaf09e9d127ca369742437fe6e88f752d6b) + +## [v0.2.2](https://github.com/minimistjs/minimist/compare/v0.2.1...v0.2.2) - 2022-10-10 + +### Commits + +- [meta] add `auto-changelog` [`73923d2`](https://github.com/minimistjs/minimist/commit/73923d223553fca08b1ba77e3fbc2a492862ae4c) +- [actions] add reusable workflows [`d80727d`](https://github.com/minimistjs/minimist/commit/d80727df77bfa9e631044d7f16368d8f09242c91) +- [eslint] add eslint; rules to enable later are warnings [`48bc06a`](https://github.com/minimistjs/minimist/commit/48bc06a1b41f00e9cdf183db34f7a51ba70e98d4) +- [readme] rename and add badges [`5df0fe4`](https://github.com/minimistjs/minimist/commit/5df0fe49211bd09a3636f8686a7cb3012c3e98f0) +- [Dev Deps] switch from `covert` to `nyc` [`a48b128`](https://github.com/minimistjs/minimist/commit/a48b128fdb8d427dfb20a15273f83e38d97bef07) +- [Dev Deps] update `covert`, `tape`; remove unnecessary `tap` [`f0fb958`](https://github.com/minimistjs/minimist/commit/f0fb958e9a1fe980cdffc436a211b0bda58f621b) +- [meta] create FUNDING.yml; add `funding` in package.json [`3639e0c`](https://github.com/minimistjs/minimist/commit/3639e0c819359a366387e425ab6eabf4c78d3caa) +- [meta] use `npmignore` to autogenerate an npmignore file [`be2e038`](https://github.com/minimistjs/minimist/commit/be2e038c342d8333b32f0fde67a0026b79c8150e) +- Only apps should have lockfiles [`282b570`](https://github.com/minimistjs/minimist/commit/282b570e7489d01b03f2d6d3dabf79cd3e5f84cf) +- [meta] add `safe-publish-latest` [`4b927de`](https://github.com/minimistjs/minimist/commit/4b927de696d561c636b4f43bf49d4597cb36d6d6) +- [Tests] add `aud` in `posttest` [`b32d9bd`](https://github.com/minimistjs/minimist/commit/b32d9bd0ab340f4e9f8c3a97ff2a4424f25fab8c) +- [meta] update repo URLs [`f9fdfc0`](https://github.com/minimistjs/minimist/commit/f9fdfc032c54884d9a9996a390c63cd0719bbe1a) + +## [v0.2.1](https://github.com/minimistjs/minimist/compare/v0.2.0...v0.2.1) - 2020-03-12 + +## [v0.2.0](https://github.com/minimistjs/minimist/compare/v0.1.0...v0.2.0) - 2014-06-19 + +### Commits + +- support all-boolean mode [`450a97f`](https://github.com/minimistjs/minimist/commit/450a97f6e2bc85c7a4a13185c19a818d9a5ebe69) + +## [v0.1.0](https://github.com/minimistjs/minimist/compare/v0.0.10...v0.1.0) - 2014-05-12 + +### Commits + +- Provide a mechanism to segregate -- arguments [`ce4a1e6`](https://github.com/minimistjs/minimist/commit/ce4a1e63a7e8d5ab88d2a3768adefa6af98a445a) +- documented argv['--'] [`14db0e6`](https://github.com/minimistjs/minimist/commit/14db0e6dbc6d2b9e472adaa54dad7004b364634f) +- Adding a test-case for notFlags segregation [`715c1e3`](https://github.com/minimistjs/minimist/commit/715c1e3714be223f998f6c537af6b505f0236c16) + +## [v0.0.10](https://github.com/minimistjs/minimist/compare/v0.0.9...v0.0.10) - 2014-05-11 + +### Commits + +- dedicated boolean test [`46e448f`](https://github.com/minimistjs/minimist/commit/46e448f9f513cfeb2bcc8b688b9b47ba1e515c2b) +- dedicated num test [`9bf2d36`](https://github.com/minimistjs/minimist/commit/9bf2d36f1d3b8795be90b8f7de0a937f098aa394) +- aliased values treated as strings [`1ab743b`](https://github.com/minimistjs/minimist/commit/1ab743bad4484d69f1259bed42f9531de01119de) +- cover the case of already numbers, at 100% coverage [`b2bb044`](https://github.com/minimistjs/minimist/commit/b2bb04436599d77a2ce029e8e555e25b3aa55d13) +- another test for higher coverage [`3662624`](https://github.com/minimistjs/minimist/commit/3662624be976d5489d486a856849c048d13be903) + +## [v0.0.9](https://github.com/minimistjs/minimist/compare/v0.0.8...v0.0.9) - 2014-05-08 + +### Commits + +- Eliminate `longest` fn. [`824f642`](https://github.com/minimistjs/minimist/commit/824f642038d1b02ede68b6261d1d65163390929a) + +## [v0.0.8](https://github.com/minimistjs/minimist/compare/v0.0.7...v0.0.8) - 2014-02-20 + +### Commits + +- return '' if flag is string and empty [`fa63ed4`](https://github.com/minimistjs/minimist/commit/fa63ed4651a4ef4eefddce34188e0d98d745a263) +- handle joined single letters [`66c248f`](https://github.com/minimistjs/minimist/commit/66c248f0241d4d421d193b022e9e365f11178534) + +## [v0.0.7](https://github.com/minimistjs/minimist/compare/v0.0.6...v0.0.7) - 2014-02-08 + +### Commits + +- another swap of .test for .match [`d1da408`](https://github.com/minimistjs/minimist/commit/d1da40819acbe846d89a5c02721211e3c1260dde) + +## [v0.0.6](https://github.com/minimistjs/minimist/compare/v0.0.5...v0.0.6) - 2014-02-08 + +### Commits + +- use .test() instead of .match() to not crash on non-string values in the arguments array [`7e0d1ad`](https://github.com/minimistjs/minimist/commit/7e0d1add8c9e5b9b20a4d3d0f9a94d824c578da1) + +## [v0.0.5](https://github.com/minimistjs/minimist/compare/v0.0.4...v0.0.5) - 2013-09-18 + +### Commits + +- Improve '--' handling. [`b11822c`](https://github.com/minimistjs/minimist/commit/b11822c09cc9d2460f30384d12afc0b953c037a4) + +## [v0.0.4](https://github.com/minimistjs/minimist/compare/v0.0.3...v0.0.4) - 2013-09-17 + +## [v0.0.3](https://github.com/minimistjs/minimist/compare/v0.0.2...v0.0.3) - 2013-09-12 + +### Commits + +- failing test for single dash preceeding a double dash [`b465514`](https://github.com/minimistjs/minimist/commit/b465514b82c9ae28972d714facd951deb2ad762b) +- fix for the dot test [`6a095f1`](https://github.com/minimistjs/minimist/commit/6a095f1d364c8fab2d6753d2291a0649315d297a) + +## [v0.0.2](https://github.com/minimistjs/minimist/compare/v0.0.1...v0.0.2) - 2013-08-28 + +### Commits + +- allow dotted aliases & defaults [`321c33e`](https://github.com/minimistjs/minimist/commit/321c33e755485faaeb44eeb1c05d33b2e0a5a7c4) +- use a better version of ff [`e40f611`](https://github.com/minimistjs/minimist/commit/e40f61114cf7be6f7947f7b3eed345853a67dbbb) + +## [v0.0.1](https://github.com/minimistjs/minimist/compare/v0.0.0...v0.0.1) - 2013-06-25 + +### Commits + +- remove trailing commas [`6ff0fa0`](https://github.com/minimistjs/minimist/commit/6ff0fa055064f15dbe06d50b89d5173a6796e1db) + +## v0.0.0 - 2013-06-25 + +### Commits + +- half of the parse test ported [`3079326`](https://github.com/minimistjs/minimist/commit/307932601325087de6cf94188eb798ffc4f3088a) +- stripped down code and a passing test from optimist [`7cced88`](https://github.com/minimistjs/minimist/commit/7cced88d82e399d1a03ed23eb667f04d3f320d10) +- ported parse tests completely over [`9448754`](https://github.com/minimistjs/minimist/commit/944875452e0820df6830b1408c26a0f7d3e1db04) +- docs, package.json [`a5bf46a`](https://github.com/minimistjs/minimist/commit/a5bf46ac9bb3bd114a9c340276c62c1091e538d5) +- move more short tests into short.js [`503edb5`](https://github.com/minimistjs/minimist/commit/503edb5c41d89c0d40831ee517154fc13b0f18b9) +- default bool test was wrong, not the code [`1b9f5db`](https://github.com/minimistjs/minimist/commit/1b9f5db4741b49962846081b68518de824992097) +- passing long tests ripped out of parse.js [`7972c4a`](https://github.com/minimistjs/minimist/commit/7972c4aff1f4803079e1668006658e2a761a0428) +- badges [`84c0370`](https://github.com/minimistjs/minimist/commit/84c037063664d42878aace715fe6572ce01b6f3b) +- all the tests now ported, some failures [`64239ed`](https://github.com/minimistjs/minimist/commit/64239edfe92c711c4eb0da254fcdfad2a5fdb605) +- failing short test [`f8a5341`](https://github.com/minimistjs/minimist/commit/f8a534112dd1138d2fad722def56a848480c446f) +- fixed the numeric test [`6b034f3`](https://github.com/minimistjs/minimist/commit/6b034f37c79342c60083ed97fd222e16928aac51) diff --git a/node_modules/minimist/LICENSE b/node_modules/minimist/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ee27ba4b4412b0e4a05af5e3d8a005bc6681fdf3 --- /dev/null +++ b/node_modules/minimist/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/minimist/README.md b/node_modules/minimist/README.md new file mode 100644 index 0000000000000000000000000000000000000000..74da3234b4844a2d381a0c6f29f893beee5591bd --- /dev/null +++ b/node_modules/minimist/README.md @@ -0,0 +1,121 @@ +# minimist [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +parse argument options + +This module is the guts of optimist's argument parser without all the +fanciful decoration. + +# example + +``` js +var argv = require('minimist')(process.argv.slice(2)); +console.log(argv); +``` + +``` +$ node example/parse.js -a beep -b boop +{ _: [], a: 'beep', b: 'boop' } +``` + +``` +$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz +{ + _: ['foo', 'bar', 'baz'], + x: 3, + y: 4, + n: 5, + a: true, + b: true, + c: true, + beep: 'boop' +} +``` + +# security + +Previous versions had a prototype pollution bug that could cause privilege +escalation in some circumstances when handling untrusted user input. + +Please use version 1.2.6 or later: + +* https://security.snyk.io/vuln/SNYK-JS-MINIMIST-2429795 (version <=1.2.5) +* https://snyk.io/vuln/SNYK-JS-MINIMIST-559764 (version <=1.2.3) + +# methods + +``` js +var parseArgs = require('minimist') +``` + +## var argv = parseArgs(args, opts={}) + +Return an argument object `argv` populated with the array arguments from `args`. + +`argv._` contains all the arguments that didn't have an option associated with +them. + +Numeric-looking arguments will be returned as numbers unless `opts.string` or +`opts.boolean` is set for that argument name. + +Any arguments after `'--'` will not be parsed and will end up in `argv._`. + +options can be: + +* `opts.string` - a string or array of strings argument names to always treat as +strings +* `opts.boolean` - a boolean, string or array of strings to always treat as +booleans. if `true` will treat all double hyphenated arguments without equal signs +as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`) +* `opts.alias` - an object mapping string names to strings or arrays of string +argument names to use as aliases +* `opts.default` - an object mapping string argument names to default values +* `opts.stopEarly` - when true, populate `argv._` with everything after the +first non-option +* `opts['--']` - when true, populate `argv._` with everything before the `--` +and `argv['--']` with everything after the `--`. Here's an example: + + ``` + > require('./')('one two three -- four five --six'.split(' '), { '--': true }) + { + _: ['one', 'two', 'three'], + '--': ['four', 'five', '--six'] + } + ``` + + Note that with `opts['--']` set, parsing for arguments still stops after the + `--`. + +* `opts.unknown` - a function which is invoked with a command line parameter not +defined in the `opts` configuration object. If the function returns `false`, the +unknown option is not added to `argv`. + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install minimist +``` + +# license + +MIT + +[package-url]: https://npmjs.org/package/minimist +[npm-version-svg]: https://versionbadg.es/minimistjs/minimist.svg +[npm-badge-png]: https://nodei.co/npm/minimist.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/minimist.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/minimist.svg +[downloads-url]: https://npm-stat.com/charts.html?package=minimist +[codecov-image]: https://codecov.io/gh/minimistjs/minimist/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/minimistjs/minimist/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/minimistjs/minimist +[actions-url]: https://github.com/minimistjs/minimist/actions diff --git a/node_modules/minimist/example/parse.js b/node_modules/minimist/example/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..9d90ffb2642b4caddde1ec6fb0cff2e78192bb09 --- /dev/null +++ b/node_modules/minimist/example/parse.js @@ -0,0 +1,4 @@ +'use strict'; + +var argv = require('../')(process.argv.slice(2)); +console.log(argv); diff --git a/node_modules/minimist/index.js b/node_modules/minimist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f020f3940e129c361dc89226efaf8775a4af8752 --- /dev/null +++ b/node_modules/minimist/index.js @@ -0,0 +1,263 @@ +'use strict'; + +function hasKey(obj, keys) { + var o = obj; + keys.slice(0, -1).forEach(function (key) { + o = o[key] || {}; + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function isNumber(x) { + if (typeof x === 'number') { return true; } + if ((/^0x[0-9a-f]+$/i).test(x)) { return true; } + return (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/).test(x); +} + +function isConstructorOrProto(obj, key) { + return (key === 'constructor' && typeof obj[key] === 'function') || key === '__proto__'; +} + +module.exports = function (args, opts) { + if (!opts) { opts = {}; } + + var flags = { + bools: {}, + strings: {}, + unknownFn: null, + }; + + if (typeof opts.unknown === 'function') { + flags.unknownFn = opts.unknown; + } + + if (typeof opts.boolean === 'boolean' && opts.boolean) { + flags.allBools = true; + } else { + [].concat(opts.boolean).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + } + + var aliases = {}; + + function aliasIsBoolean(key) { + return aliases[key].some(function (x) { + return flags.bools[x]; + }); + } + + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + if (aliases[key]) { + [].concat(aliases[key]).forEach(function (k) { + flags.strings[k] = true; + }); + } + }); + + var defaults = opts.default || {}; + + var argv = { _: [] }; + + function argDefined(key, arg) { + return (flags.allBools && (/^--[^=]+$/).test(arg)) + || flags.strings[key] + || flags.bools[key] + || aliases[key]; + } + + function setKey(obj, keys, value) { + var o = obj; + for (var i = 0; i < keys.length - 1; i++) { + var key = keys[i]; + if (isConstructorOrProto(o, key)) { return; } + if (o[key] === undefined) { o[key] = {}; } + if ( + o[key] === Object.prototype + || o[key] === Number.prototype + || o[key] === String.prototype + ) { + o[key] = {}; + } + if (o[key] === Array.prototype) { o[key] = []; } + o = o[key]; + } + + var lastKey = keys[keys.length - 1]; + if (isConstructorOrProto(o, lastKey)) { return; } + if ( + o === Object.prototype + || o === Number.prototype + || o === String.prototype + ) { + o = {}; + } + if (o === Array.prototype) { o = []; } + if (o[lastKey] === undefined || flags.bools[lastKey] || typeof o[lastKey] === 'boolean') { + o[lastKey] = value; + } else if (Array.isArray(o[lastKey])) { + o[lastKey].push(value); + } else { + o[lastKey] = [o[lastKey], value]; + } + } + + function setArg(key, val, arg) { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) { return; } + } + + var value = !flags.strings[key] && isNumber(val) + ? Number(val) + : val; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--') + 1); + args = args.slice(0, args.indexOf('--')); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + var key; + var next; + + if ((/^--.+=/).test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + key = m[1]; + var value = m[2]; + if (flags.bools[key]) { + value = value !== 'false'; + } + setArg(key, value, arg); + } else if ((/^--no-.+/).test(arg)) { + key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false, arg); + } else if ((/^--.+/).test(arg)) { + key = arg.match(/^--(.+)/)[1]; + next = args[i + 1]; + if ( + next !== undefined + && !(/^(-|--)[^-]/).test(next) + && !flags.bools[key] + && !flags.allBools + && (aliases[key] ? !aliasIsBoolean(key) : true) + ) { + setArg(key, next, arg); + i += 1; + } else if ((/^(true|false)$/).test(next)) { + setArg(key, next === 'true', arg); + i += 1; + } else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } else if ((/^-[^-]+/).test(arg)) { + var letters = arg.slice(1, -1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + + if (next === '-') { + setArg(letters[j], next, arg); + continue; + } + + if ((/[A-Za-z]/).test(letters[j]) && next[0] === '=') { + setArg(letters[j], next.slice(1), arg); + broken = true; + break; + } + + if ( + (/[A-Za-z]/).test(letters[j]) + && (/-?\d+(\.\d*)?(e-?\d+)?$/).test(next) + ) { + setArg(letters[j], next, arg); + broken = true; + break; + } + + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], arg.slice(j + 2), arg); + broken = true; + break; + } else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); + } + } + + key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if ( + args[i + 1] + && !(/^(-|--)[^-]/).test(args[i + 1]) + && !flags.bools[key] + && (aliases[key] ? !aliasIsBoolean(key) : true) + ) { + setArg(key, args[i + 1], arg); + i += 1; + } else if (args[i + 1] && (/^(true|false)$/).test(args[i + 1])) { + setArg(key, args[i + 1] === 'true', arg); + i += 1; + } else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + } else { + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg)); + } + if (opts.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } + } + } + + Object.keys(defaults).forEach(function (k) { + if (!hasKey(argv, k.split('.'))) { + setKey(argv, k.split('.'), defaults[k]); + + (aliases[k] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[k]); + }); + } + }); + + if (opts['--']) { + argv['--'] = notFlags.slice(); + } else { + notFlags.forEach(function (k) { + argv._.push(k); + }); + } + + return argv; +}; diff --git a/node_modules/minimist/package.json b/node_modules/minimist/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c10a3344411197a716883caad07f0319f5d69b89 --- /dev/null +++ b/node_modules/minimist/package.json @@ -0,0 +1,75 @@ +{ + "name": "minimist", + "version": "1.2.8", + "description": "parse argument options", + "main": "index.js", + "devDependencies": { + "@ljharb/eslint-config": "^21.0.1", + "aud": "^2.0.2", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.3" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "ff/5", + "firefox/latest", + "chrome/10", + "chrome/latest", + "safari/5.1", + "safari/latest", + "opera/12" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/minimistjs/minimist.git" + }, + "homepage": "https://github.com/minimistjs/minimist", + "keywords": [ + "argv", + "getopt", + "parser", + "optimist" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/minimist/test/all_bool.js b/node_modules/minimist/test/all_bool.js new file mode 100644 index 0000000000000000000000000000000000000000..befa0c99769080972260dac9e4a77630857000f2 --- /dev/null +++ b/node_modules/minimist/test/all_bool.js @@ -0,0 +1,34 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('flag boolean true (default all --args to boolean)', function (t) { + var argv = parse(['moo', '--honk', 'cow'], { + boolean: true, + }); + + t.deepEqual(argv, { + honk: true, + _: ['moo', 'cow'], + }); + + t.deepEqual(typeof argv.honk, 'boolean'); + t.end(); +}); + +test('flag boolean true only affects double hyphen arguments without equals signs', function (t) { + var argv = parse(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], { + boolean: true, + }); + + t.deepEqual(argv, { + honk: true, + tacos: 'good', + p: 55, + _: ['moo', 'cow'], + }); + + t.deepEqual(typeof argv.honk, 'boolean'); + t.end(); +}); diff --git a/node_modules/minimist/test/bool.js b/node_modules/minimist/test/bool.js new file mode 100644 index 0000000000000000000000000000000000000000..e58d47e442ce127bfe5703b6b64d14c3e4511223 --- /dev/null +++ b/node_modules/minimist/test/bool.js @@ -0,0 +1,177 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('flag boolean default false', function (t) { + var argv = parse(['moo'], { + boolean: ['t', 'verbose'], + default: { verbose: false, t: false }, + }); + + t.deepEqual(argv, { + verbose: false, + t: false, + _: ['moo'], + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); + +}); + +test('boolean groups', function (t) { + var argv = parse(['-x', '-z', 'one', 'two', 'three'], { + boolean: ['x', 'y', 'z'], + }); + + t.deepEqual(argv, { + x: true, + y: false, + z: true, + _: ['one', 'two', 'three'], + }); + + t.deepEqual(typeof argv.x, 'boolean'); + t.deepEqual(typeof argv.y, 'boolean'); + t.deepEqual(typeof argv.z, 'boolean'); + t.end(); +}); +test('boolean and alias with chainable api', function (t) { + var aliased = ['-h', 'derp']; + var regular = ['--herp', 'derp']; + var aliasedArgv = parse(aliased, { + boolean: 'herp', + alias: { h: 'herp' }, + }); + var propertyArgv = parse(regular, { + boolean: 'herp', + alias: { h: 'herp' }, + }); + var expected = { + herp: true, + h: true, + _: ['derp'], + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias with options hash', function (t) { + var aliased = ['-h', 'derp']; + var regular = ['--herp', 'derp']; + var opts = { + alias: { h: 'herp' }, + boolean: 'herp', + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + _: ['derp'], + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias array with options hash', function (t) { + var aliased = ['-h', 'derp']; + var regular = ['--herp', 'derp']; + var alt = ['--harp', 'derp']; + var opts = { + alias: { h: ['herp', 'harp'] }, + boolean: 'h', + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var altPropertyArgv = parse(alt, opts); + var expected = { + harp: true, + herp: true, + h: true, + _: ['derp'], + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.same(altPropertyArgv, expected); + t.end(); +}); + +test('boolean and alias using explicit true', function (t) { + var aliased = ['-h', 'true']; + var regular = ['--herp', 'true']; + var opts = { + alias: { h: 'herp' }, + boolean: 'h', + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + _: [], + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +// regression, see https://github.com/substack/node-optimist/issues/71 +test('boolean and --x=true', function (t) { + var parsed = parse(['--boool', '--other=true'], { + boolean: 'boool', + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'true'); + + parsed = parse(['--boool', '--other=false'], { + boolean: 'boool', + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'false'); + t.end(); +}); + +test('boolean --boool=true', function (t) { + var parsed = parse(['--boool=true'], { + default: { + boool: false, + }, + boolean: ['boool'], + }); + + t.same(parsed.boool, true); + t.end(); +}); + +test('boolean --boool=false', function (t) { + var parsed = parse(['--boool=false'], { + default: { + boool: true, + }, + boolean: ['boool'], + }); + + t.same(parsed.boool, false); + t.end(); +}); + +test('boolean using something similar to true', function (t) { + var opts = { boolean: 'h' }; + var result = parse(['-h', 'true.txt'], opts); + var expected = { + h: true, + _: ['true.txt'], + }; + + t.same(result, expected); + t.end(); +}); diff --git a/node_modules/minimist/test/dash.js b/node_modules/minimist/test/dash.js new file mode 100644 index 0000000000000000000000000000000000000000..707881771e275240a0e0d6d4d2fb8d31a564d74f --- /dev/null +++ b/node_modules/minimist/test/dash.js @@ -0,0 +1,43 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('-', function (t) { + t.plan(6); + t.deepEqual(parse(['-n', '-']), { n: '-', _: [] }); + t.deepEqual(parse(['--nnn', '-']), { nnn: '-', _: [] }); + t.deepEqual(parse(['-']), { _: ['-'] }); + t.deepEqual(parse(['-f-']), { f: '-', _: [] }); + t.deepEqual( + parse(['-b', '-'], { boolean: 'b' }), + { b: true, _: ['-'] } + ); + t.deepEqual( + parse(['-s', '-'], { string: 's' }), + { s: '-', _: [] } + ); +}); + +test('-a -- b', function (t) { + t.plan(2); + t.deepEqual(parse(['-a', '--', 'b']), { a: true, _: ['b'] }); + t.deepEqual(parse(['--a', '--', 'b']), { a: true, _: ['b'] }); +}); + +test('move arguments after the -- into their own `--` array', function (t) { + t.plan(1); + t.deepEqual( + parse(['--name', 'John', 'before', '--', 'after'], { '--': true }), + { name: 'John', _: ['before'], '--': ['after'] } + ); +}); + +test('--- option value', function (t) { + // A multi-dash value is largely an edge case, but check the behaviour is as expected, + // and in particular the same for short option and long option (as made consistent in Jan 2023). + t.plan(2); + t.deepEqual(parse(['-n', '---']), { n: '---', _: [] }); + t.deepEqual(parse(['--nnn', '---']), { nnn: '---', _: [] }); +}); + diff --git a/node_modules/minimist/test/default_bool.js b/node_modules/minimist/test/default_bool.js new file mode 100644 index 0000000000000000000000000000000000000000..4e9f6250f08ea8e005b66729630660a3db195566 --- /dev/null +++ b/node_modules/minimist/test/default_bool.js @@ -0,0 +1,37 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../'); + +test('boolean default true', function (t) { + var argv = parse([], { + boolean: 'sometrue', + default: { sometrue: true }, + }); + t.equal(argv.sometrue, true); + t.end(); +}); + +test('boolean default false', function (t) { + var argv = parse([], { + boolean: 'somefalse', + default: { somefalse: false }, + }); + t.equal(argv.somefalse, false); + t.end(); +}); + +test('boolean default to null', function (t) { + var argv = parse([], { + boolean: 'maybe', + default: { maybe: null }, + }); + t.equal(argv.maybe, null); + + var argvLong = parse(['--maybe'], { + boolean: 'maybe', + default: { maybe: null }, + }); + t.equal(argvLong.maybe, true); + t.end(); +}); diff --git a/node_modules/minimist/test/dotted.js b/node_modules/minimist/test/dotted.js new file mode 100644 index 0000000000000000000000000000000000000000..126ff033b4237334be18dafed9f2b4636f684d2d --- /dev/null +++ b/node_modules/minimist/test/dotted.js @@ -0,0 +1,24 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('dotted alias', function (t) { + var argv = parse(['--a.b', '22'], { default: { 'a.b': 11 }, alias: { 'a.b': 'aa.bb' } }); + t.equal(argv.a.b, 22); + t.equal(argv.aa.bb, 22); + t.end(); +}); + +test('dotted default', function (t) { + var argv = parse('', { default: { 'a.b': 11 }, alias: { 'a.b': 'aa.bb' } }); + t.equal(argv.a.b, 11); + t.equal(argv.aa.bb, 11); + t.end(); +}); + +test('dotted default with no alias', function (t) { + var argv = parse('', { default: { 'a.b': 11 } }); + t.equal(argv.a.b, 11); + t.end(); +}); diff --git a/node_modules/minimist/test/kv_short.js b/node_modules/minimist/test/kv_short.js new file mode 100644 index 0000000000000000000000000000000000000000..6d1b53a7a7ee1fcbeb9b12c9804f83ff90f46ccd --- /dev/null +++ b/node_modules/minimist/test/kv_short.js @@ -0,0 +1,32 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('short -k=v', function (t) { + t.plan(1); + + var argv = parse(['-b=123']); + t.deepEqual(argv, { b: 123, _: [] }); +}); + +test('multi short -k=v', function (t) { + t.plan(1); + + var argv = parse(['-a=whatever', '-b=robots']); + t.deepEqual(argv, { a: 'whatever', b: 'robots', _: [] }); +}); + +test('short with embedded equals -k=a=b', function (t) { + t.plan(1); + + var argv = parse(['-k=a=b']); + t.deepEqual(argv, { k: 'a=b', _: [] }); +}); + +test('short with later equals like -ab=c', function (t) { + t.plan(1); + + var argv = parse(['-ab=c']); + t.deepEqual(argv, { a: true, b: 'c', _: [] }); +}); diff --git a/node_modules/minimist/test/long.js b/node_modules/minimist/test/long.js new file mode 100644 index 0000000000000000000000000000000000000000..9fef51f1fa8d9bf8ef9e92ad2ce5742f009ab941 --- /dev/null +++ b/node_modules/minimist/test/long.js @@ -0,0 +1,33 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../'); + +test('long opts', function (t) { + t.deepEqual( + parse(['--bool']), + { bool: true, _: [] }, + 'long boolean' + ); + t.deepEqual( + parse(['--pow', 'xixxle']), + { pow: 'xixxle', _: [] }, + 'long capture sp' + ); + t.deepEqual( + parse(['--pow=xixxle']), + { pow: 'xixxle', _: [] }, + 'long capture eq' + ); + t.deepEqual( + parse(['--host', 'localhost', '--port', '555']), + { host: 'localhost', port: 555, _: [] }, + 'long captures sp' + ); + t.deepEqual( + parse(['--host=localhost', '--port=555']), + { host: 'localhost', port: 555, _: [] }, + 'long captures eq' + ); + t.end(); +}); diff --git a/node_modules/minimist/test/num.js b/node_modules/minimist/test/num.js new file mode 100644 index 0000000000000000000000000000000000000000..074393ecaf1705b9a6170c35ad23d55df943f306 --- /dev/null +++ b/node_modules/minimist/test/num.js @@ -0,0 +1,38 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('nums', function (t) { + var argv = parse([ + '-x', '1234', + '-y', '5.67', + '-z', '1e7', + '-w', '10f', + '--hex', '0xdeadbeef', + '789', + ]); + t.deepEqual(argv, { + x: 1234, + y: 5.67, + z: 1e7, + w: '10f', + hex: 0xdeadbeef, + _: [789], + }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv.y, 'number'); + t.deepEqual(typeof argv.z, 'number'); + t.deepEqual(typeof argv.w, 'string'); + t.deepEqual(typeof argv.hex, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); + +test('already a number', function (t) { + var argv = parse(['-x', 1234, 789]); + t.deepEqual(argv, { x: 1234, _: [789] }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); diff --git a/node_modules/minimist/test/parse.js b/node_modules/minimist/test/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..65d9d90927b91baa152a32e1485479307f1acf44 --- /dev/null +++ b/node_modules/minimist/test/parse.js @@ -0,0 +1,209 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('parse args', function (t) { + t.deepEqual( + parse(['--no-moo']), + { moo: false, _: [] }, + 'no' + ); + t.deepEqual( + parse(['-v', 'a', '-v', 'b', '-v', 'c']), + { v: ['a', 'b', 'c'], _: [] }, + 'multi' + ); + t.end(); +}); + +test('comprehensive', function (t) { + t.deepEqual( + parse([ + '--name=meowmers', 'bare', '-cats', 'woo', + '-h', 'awesome', '--multi=quux', + '--key', 'value', + '-b', '--bool', '--no-meep', '--multi=baz', + '--', '--not-a-flag', 'eek', + ]), + { + c: true, + a: true, + t: true, + s: 'woo', + h: 'awesome', + b: true, + bool: true, + key: 'value', + multi: ['quux', 'baz'], + meep: false, + name: 'meowmers', + _: ['bare', '--not-a-flag', 'eek'], + } + ); + t.end(); +}); + +test('flag boolean', function (t) { + var argv = parse(['-t', 'moo'], { boolean: 't' }); + t.deepEqual(argv, { t: true, _: ['moo'] }); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('flag boolean value', function (t) { + var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], { + boolean: ['t', 'verbose'], + default: { verbose: true }, + }); + + t.deepEqual(argv, { + verbose: false, + t: true, + _: ['moo'], + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('newlines in params', function (t) { + var args = parse(['-s', 'X\nX']); + t.deepEqual(args, { _: [], s: 'X\nX' }); + + // reproduce in bash: + // VALUE="new + // line" + // node program.js --s="$VALUE" + args = parse(['--s=X\nX']); + t.deepEqual(args, { _: [], s: 'X\nX' }); + t.end(); +}); + +test('strings', function (t) { + var s = parse(['-s', '0001234'], { string: 's' }).s; + t.equal(s, '0001234'); + t.equal(typeof s, 'string'); + + var x = parse(['-x', '56'], { string: 'x' }).x; + t.equal(x, '56'); + t.equal(typeof x, 'string'); + t.end(); +}); + +test('stringArgs', function (t) { + var s = parse([' ', ' '], { string: '_' })._; + t.same(s.length, 2); + t.same(typeof s[0], 'string'); + t.same(s[0], ' '); + t.same(typeof s[1], 'string'); + t.same(s[1], ' '); + t.end(); +}); + +test('empty strings', function (t) { + var s = parse(['-s'], { string: 's' }).s; + t.equal(s, ''); + t.equal(typeof s, 'string'); + + var str = parse(['--str'], { string: 'str' }).str; + t.equal(str, ''); + t.equal(typeof str, 'string'); + + var letters = parse(['-art'], { + string: ['a', 't'], + }); + + t.equal(letters.a, ''); + t.equal(letters.r, true); + t.equal(letters.t, ''); + + t.end(); +}); + +test('string and alias', function (t) { + var x = parse(['--str', '000123'], { + string: 's', + alias: { s: 'str' }, + }); + + t.equal(x.str, '000123'); + t.equal(typeof x.str, 'string'); + t.equal(x.s, '000123'); + t.equal(typeof x.s, 'string'); + + var y = parse(['-s', '000123'], { + string: 'str', + alias: { str: 's' }, + }); + + t.equal(y.str, '000123'); + t.equal(typeof y.str, 'string'); + t.equal(y.s, '000123'); + t.equal(typeof y.s, 'string'); + + var z = parse(['-s123'], { + alias: { str: ['s', 'S'] }, + string: ['str'], + }); + + t.deepEqual( + z, + { _: [], s: '123', S: '123', str: '123' }, + 'opt.string works with multiple aliases' + ); + t.end(); +}); + +test('slashBreak', function (t) { + t.same( + parse(['-I/foo/bar/baz']), + { I: '/foo/bar/baz', _: [] } + ); + t.same( + parse(['-xyz/foo/bar/baz']), + { x: true, y: true, z: '/foo/bar/baz', _: [] } + ); + t.end(); +}); + +test('alias', function (t) { + var argv = parse(['-f', '11', '--zoom', '55'], { + alias: { z: 'zoom' }, + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.f, 11); + t.end(); +}); + +test('multiAlias', function (t) { + var argv = parse(['-f', '11', '--zoom', '55'], { + alias: { z: ['zm', 'zoom'] }, + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.z, argv.zm); + t.equal(argv.f, 11); + t.end(); +}); + +test('nested dotted objects', function (t) { + var argv = parse([ + '--foo.bar', '3', '--foo.baz', '4', + '--foo.quux.quibble', '5', '--foo.quux.o_O', + '--beep.boop', + ]); + + t.same(argv.foo, { + bar: 3, + baz: 4, + quux: { + quibble: 5, + o_O: true, + }, + }); + t.same(argv.beep, { boop: true }); + t.end(); +}); diff --git a/node_modules/minimist/test/parse_modified.js b/node_modules/minimist/test/parse_modified.js new file mode 100644 index 0000000000000000000000000000000000000000..32965d130fbd4f59b9a6e12488cf18901004d1f8 --- /dev/null +++ b/node_modules/minimist/test/parse_modified.js @@ -0,0 +1,11 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('parse with modifier functions', function (t) { + t.plan(1); + + var argv = parse(['-b', '123'], { boolean: 'b' }); + t.deepEqual(argv, { b: true, _: [123] }); +}); diff --git a/node_modules/minimist/test/proto.js b/node_modules/minimist/test/proto.js new file mode 100644 index 0000000000000000000000000000000000000000..6e629dd34ef0942c19c4d124542f5f030c228ae4 --- /dev/null +++ b/node_modules/minimist/test/proto.js @@ -0,0 +1,64 @@ +'use strict'; + +/* eslint no-proto: 0 */ + +var parse = require('../'); +var test = require('tape'); + +test('proto pollution', function (t) { + var argv = parse(['--__proto__.x', '123']); + t.equal({}.x, undefined); + t.equal(argv.__proto__.x, undefined); + t.equal(argv.x, undefined); + t.end(); +}); + +test('proto pollution (array)', function (t) { + var argv = parse(['--x', '4', '--x', '5', '--x.__proto__.z', '789']); + t.equal({}.z, undefined); + t.deepEqual(argv.x, [4, 5]); + t.equal(argv.x.z, undefined); + t.equal(argv.x.__proto__.z, undefined); + t.end(); +}); + +test('proto pollution (number)', function (t) { + var argv = parse(['--x', '5', '--x.__proto__.z', '100']); + t.equal({}.z, undefined); + t.equal((4).z, undefined); + t.equal(argv.x, 5); + t.equal(argv.x.z, undefined); + t.end(); +}); + +test('proto pollution (string)', function (t) { + var argv = parse(['--x', 'abc', '--x.__proto__.z', 'def']); + t.equal({}.z, undefined); + t.equal('...'.z, undefined); + t.equal(argv.x, 'abc'); + t.equal(argv.x.z, undefined); + t.end(); +}); + +test('proto pollution (constructor)', function (t) { + var argv = parse(['--constructor.prototype.y', '123']); + t.equal({}.y, undefined); + t.equal(argv.y, undefined); + t.end(); +}); + +test('proto pollution (constructor function)', function (t) { + var argv = parse(['--_.concat.constructor.prototype.y', '123']); + function fnToBeTested() {} + t.equal(fnToBeTested.y, undefined); + t.equal(argv.y, undefined); + t.end(); +}); + +// powered by snyk - https://github.com/backstage/backstage/issues/10343 +test('proto pollution (constructor function) snyk', function (t) { + var argv = parse('--_.constructor.constructor.prototype.foo bar'.split(' ')); + t.equal(function () {}.foo, undefined); + t.equal(argv.y, undefined); + t.end(); +}); diff --git a/node_modules/minimist/test/short.js b/node_modules/minimist/test/short.js new file mode 100644 index 0000000000000000000000000000000000000000..4a7b84385bbfdc74314f5e8f7cc4c36afd52b8bd --- /dev/null +++ b/node_modules/minimist/test/short.js @@ -0,0 +1,69 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('numeric short args', function (t) { + t.plan(2); + t.deepEqual(parse(['-n123']), { n: 123, _: [] }); + t.deepEqual( + parse(['-123', '456']), + { 1: true, 2: true, 3: 456, _: [] } + ); +}); + +test('short', function (t) { + t.deepEqual( + parse(['-b']), + { b: true, _: [] }, + 'short boolean' + ); + t.deepEqual( + parse(['foo', 'bar', 'baz']), + { _: ['foo', 'bar', 'baz'] }, + 'bare' + ); + t.deepEqual( + parse(['-cats']), + { c: true, a: true, t: true, s: true, _: [] }, + 'group' + ); + t.deepEqual( + parse(['-cats', 'meow']), + { c: true, a: true, t: true, s: 'meow', _: [] }, + 'short group next' + ); + t.deepEqual( + parse(['-h', 'localhost']), + { h: 'localhost', _: [] }, + 'short capture' + ); + t.deepEqual( + parse(['-h', 'localhost', '-p', '555']), + { h: 'localhost', p: 555, _: [] }, + 'short captures' + ); + t.end(); +}); + +test('mixed short bool and capture', function (t) { + t.same( + parse(['-h', 'localhost', '-fp', '555', 'script.js']), + { + f: true, p: 555, h: 'localhost', + _: ['script.js'], + } + ); + t.end(); +}); + +test('short and long', function (t) { + t.deepEqual( + parse(['-h', 'localhost', '-fp', '555', 'script.js']), + { + f: true, p: 555, h: 'localhost', + _: ['script.js'], + } + ); + t.end(); +}); diff --git a/node_modules/minimist/test/stop_early.js b/node_modules/minimist/test/stop_early.js new file mode 100644 index 0000000000000000000000000000000000000000..52a6a91903028d5230729df63afcdb80d79b0c68 --- /dev/null +++ b/node_modules/minimist/test/stop_early.js @@ -0,0 +1,17 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('stops parsing on the first non-option when stopEarly is set', function (t) { + var argv = parse(['--aaa', 'bbb', 'ccc', '--ddd'], { + stopEarly: true, + }); + + t.deepEqual(argv, { + aaa: 'bbb', + _: ['ccc', '--ddd'], + }); + + t.end(); +}); diff --git a/node_modules/minimist/test/unknown.js b/node_modules/minimist/test/unknown.js new file mode 100644 index 0000000000000000000000000000000000000000..4f2e0ca447f4ccc2fb7ba4df3876bf45d3f0423a --- /dev/null +++ b/node_modules/minimist/test/unknown.js @@ -0,0 +1,104 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('boolean and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = ['-h', 'true', '--derp', 'true']; + var regular = ['--herp', 'true', '-d', 'true']; + var opts = { + alias: { h: 'herp' }, + boolean: 'h', + unknown: unknownFn, + }; + parse(aliased, opts); + parse(regular, opts); + + t.same(unknown, ['--derp', '-d']); + t.end(); +}); + +test('flag boolean true any double hyphen argument is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var argv = parse(['--honk', '--tacos=good', 'cow', '-p', '55'], { + boolean: true, + unknown: unknownFn, + }); + t.same(unknown, ['--tacos=good', 'cow', '-p']); + t.same(argv, { + honk: true, + _: [], + }); + t.end(); +}); + +test('string and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = ['-h', 'hello', '--derp', 'goodbye']; + var regular = ['--herp', 'hello', '-d', 'moon']; + var opts = { + alias: { h: 'herp' }, + string: 'h', + unknown: unknownFn, + }; + parse(aliased, opts); + parse(regular, opts); + + t.same(unknown, ['--derp', '-d']); + t.end(); +}); + +test('default and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = ['-h', 'hello']; + var regular = ['--herp', 'hello']; + var opts = { + default: { h: 'bar' }, + alias: { h: 'herp' }, + unknown: unknownFn, + }; + parse(aliased, opts); + parse(regular, opts); + + t.same(unknown, []); + t.end(); + unknownFn(); // exercise fn for 100% coverage +}); + +test('value following -- is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = ['--bad', '--', 'good', 'arg']; + var opts = { + '--': true, + unknown: unknownFn, + }; + var argv = parse(aliased, opts); + + t.same(unknown, ['--bad']); + t.same(argv, { + '--': ['good', 'arg'], + _: [], + }); + t.end(); +}); diff --git a/node_modules/minimist/test/whitespace.js b/node_modules/minimist/test/whitespace.js new file mode 100644 index 0000000000000000000000000000000000000000..4fdaf1d3943f5a16b9d76af9cd7bbc82f2f54b54 --- /dev/null +++ b/node_modules/minimist/test/whitespace.js @@ -0,0 +1,10 @@ +'use strict'; + +var parse = require('../'); +var test = require('tape'); + +test('whitespace should be whitespace', function (t) { + t.plan(1); + var x = parse(['-x', '\t']).x; + t.equal(x, '\t'); +}); diff --git a/node_modules/mouse-change/.npmignore b/node_modules/mouse-change/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..ddc9ab330c2a9e77591abb3effd1b9ebf278a988 --- /dev/null +++ b/node_modules/mouse-change/.npmignore @@ -0,0 +1,16 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log +node_modules/* +*.DS_Store \ No newline at end of file diff --git a/node_modules/mouse-change/LICENSE b/node_modules/mouse-change/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1815ddd61d61d007ca9c832c7d69ffc8a4f9f86a --- /dev/null +++ b/node_modules/mouse-change/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2015 Mikola Lysenko + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/mouse-change/README.md b/node_modules/mouse-change/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7593f20901d01e0283ae0e0710a0ac86b002b4bb --- /dev/null +++ b/node_modules/mouse-change/README.md @@ -0,0 +1,58 @@ +mouse-change +============ +Listens for any mouse state changes. + +# Example + +```javascript +require('mouse-change')(function(buttons, x, y) { + document.body.innerHTML = + '

Buttons: 0b' + buttons.toString(2) + + ', x:' + x + + ', y:' + y + '

' +}) +``` + +[Try it out in your browser](https://mikolalysenko.github.io/mouse-change) + +# Install + +``` +npm i mouse-change +``` + +# API + +#### `var l = require('mouse-change')([element, onchange(buttons,x,y,mods)])` +Listens for any mouse state changes on the given element. + +* `element` is an optional element +* `onchange(buttons,x,y,mods)` is an optional callback which gets called every time that the mouse state changes inside `element` + + `buttons` is the state of the mouse buttons + + `x` is the x coordinate of the mouse + + `y` is the y coordinate of the mouse + + `mods` is an object storing the state of any key modifiers + * `mods.shift` is the state of the shift key + * `mods.alt` is the state of then alt key + * `mods.control` is the state of the control key + * `mods.meta` is the state of the meta key + +**Returns** A new listener object which can be used to configure the listener. + +#### `l.enabled` +Toggles whether or not + +#### `l.x` +The x coordinate of the mouse + +#### `l.y` +The y coordinate of the mouse + +#### `l.buttons` +The button state of the mouse + +#### `l.mods` +The current state of the keyboard modifiers + +# License +(c) 2015 Mikola Lysenko. MIT License diff --git a/node_modules/mouse-change/example/example.js b/node_modules/mouse-change/example/example.js new file mode 100644 index 0000000000000000000000000000000000000000..745c797841857910f6023cf0daa23864235712be --- /dev/null +++ b/node_modules/mouse-change/example/example.js @@ -0,0 +1,7 @@ +require('../mouse-listen')(function(buttons, x, y, mods) { + document.body.innerHTML = + '

Buttons: 0b' + buttons.toString(2) + + ', x:' + x + + ', y:' + y + + ', mods:' + JSON.stringify(mods) + '

' +}) diff --git a/node_modules/mouse-change/mouse-listen.js b/node_modules/mouse-change/mouse-listen.js new file mode 100644 index 0000000000000000000000000000000000000000..f751326353c47460d34e96246885da1135c09ea7 --- /dev/null +++ b/node_modules/mouse-change/mouse-listen.js @@ -0,0 +1,205 @@ +'use strict' + +module.exports = mouseListen + +var mouse = require('mouse-event') + +function mouseListen (element, callback) { + if (!callback) { + callback = element + element = window + } + + var buttonState = 0 + var x = 0 + var y = 0 + var mods = { + shift: false, + alt: false, + control: false, + meta: false + } + var attached = false + + function updateMods (ev) { + var changed = false + if ('altKey' in ev) { + changed = changed || ev.altKey !== mods.alt + mods.alt = !!ev.altKey + } + if ('shiftKey' in ev) { + changed = changed || ev.shiftKey !== mods.shift + mods.shift = !!ev.shiftKey + } + if ('ctrlKey' in ev) { + changed = changed || ev.ctrlKey !== mods.control + mods.control = !!ev.ctrlKey + } + if ('metaKey' in ev) { + changed = changed || ev.metaKey !== mods.meta + mods.meta = !!ev.metaKey + } + return changed + } + + function handleEvent (nextButtons, ev) { + var nextX = mouse.x(ev) + var nextY = mouse.y(ev) + if ('buttons' in ev) { + nextButtons = ev.buttons | 0 + } + if (nextButtons !== buttonState || + nextX !== x || + nextY !== y || + updateMods(ev)) { + buttonState = nextButtons | 0 + x = nextX || 0 + y = nextY || 0 + callback && callback(buttonState, x, y, mods) + } + } + + function clearState (ev) { + handleEvent(0, ev) + } + + function handleBlur () { + if (buttonState || + x || + y || + mods.shift || + mods.alt || + mods.meta || + mods.control) { + x = y = 0 + buttonState = 0 + mods.shift = mods.alt = mods.control = mods.meta = false + callback && callback(0, 0, 0, mods) + } + } + + function handleMods (ev) { + if (updateMods(ev)) { + callback && callback(buttonState, x, y, mods) + } + } + + function handleMouseMove (ev) { + if (mouse.buttons(ev) === 0) { + handleEvent(0, ev) + } else { + handleEvent(buttonState, ev) + } + } + + function handleMouseDown (ev) { + handleEvent(buttonState | mouse.buttons(ev), ev) + } + + function handleMouseUp (ev) { + handleEvent(buttonState & ~mouse.buttons(ev), ev) + } + + function attachListeners () { + if (attached) { + return + } + attached = true + + element.addEventListener('mousemove', handleMouseMove) + + element.addEventListener('mousedown', handleMouseDown) + + element.addEventListener('mouseup', handleMouseUp) + + element.addEventListener('mouseleave', clearState) + element.addEventListener('mouseenter', clearState) + element.addEventListener('mouseout', clearState) + element.addEventListener('mouseover', clearState) + + element.addEventListener('blur', handleBlur) + + element.addEventListener('keyup', handleMods) + element.addEventListener('keydown', handleMods) + element.addEventListener('keypress', handleMods) + + if (element !== window) { + window.addEventListener('blur', handleBlur) + + window.addEventListener('keyup', handleMods) + window.addEventListener('keydown', handleMods) + window.addEventListener('keypress', handleMods) + } + } + + function detachListeners () { + if (!attached) { + return + } + attached = false + + element.removeEventListener('mousemove', handleMouseMove) + + element.removeEventListener('mousedown', handleMouseDown) + + element.removeEventListener('mouseup', handleMouseUp) + + element.removeEventListener('mouseleave', clearState) + element.removeEventListener('mouseenter', clearState) + element.removeEventListener('mouseout', clearState) + element.removeEventListener('mouseover', clearState) + + element.removeEventListener('blur', handleBlur) + + element.removeEventListener('keyup', handleMods) + element.removeEventListener('keydown', handleMods) + element.removeEventListener('keypress', handleMods) + + if (element !== window) { + window.removeEventListener('blur', handleBlur) + + window.removeEventListener('keyup', handleMods) + window.removeEventListener('keydown', handleMods) + window.removeEventListener('keypress', handleMods) + } + } + + // Attach listeners + attachListeners() + + var result = { + element: element + } + + Object.defineProperties(result, { + enabled: { + get: function () { return attached }, + set: function (f) { + if (f) { + attachListeners() + } else { + detachListeners() + } + }, + enumerable: true + }, + buttons: { + get: function () { return buttonState }, + enumerable: true + }, + x: { + get: function () { return x }, + enumerable: true + }, + y: { + get: function () { return y }, + enumerable: true + }, + mods: { + get: function () { return mods }, + enumerable: true + } + }) + + return result +} diff --git a/node_modules/mouse-change/package.json b/node_modules/mouse-change/package.json new file mode 100644 index 0000000000000000000000000000000000000000..23615c55bffee6ca7187616b7431265741ae05f1 --- /dev/null +++ b/node_modules/mouse-change/package.json @@ -0,0 +1,41 @@ +{ + "name": "mouse-change", + "version": "1.4.0", + "description": "Mouse state change listener", + "main": "mouse-listen.js", + "directories": { + "example": "example" + }, + "dependencies": { + "mouse-event": "^1.0.0" + }, + "devDependencies": {}, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "https://github.com/mikolalysenko/mouse-change.git" + }, + "keywords": [ + "mouse", + "state", + "listen", + "change", + "button", + "click", + "hold", + "up", + "down", + "over", + "polyfill", + "bug", + "fix" + ], + "author": "Mikola Lysenko", + "license": "MIT", + "bugs": { + "url": "https://github.com/mikolalysenko/mouse-change/issues" + }, + "homepage": "https://github.com/mikolalysenko/mouse-change" +} diff --git a/node_modules/mouse-event-offset/.npmignore b/node_modules/mouse-event-offset/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..bd11a0be2a1b9c72cfe67f1fa1b393aed0923fc3 --- /dev/null +++ b/node_modules/mouse-event-offset/.npmignore @@ -0,0 +1,8 @@ +bower_components +node_modules +*.log +.DS_Store +bundle.js +test +test.js +demo/ \ No newline at end of file diff --git a/node_modules/mouse-event-offset/LICENSE.md b/node_modules/mouse-event-offset/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..927a999b6ee41b2e53992f0eecdd5ee939cf7038 --- /dev/null +++ b/node_modules/mouse-event-offset/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) +Copyright (c) 2014 Matt DesLauriers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/mouse-event-offset/README.md b/node_modules/mouse-event-offset/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0f29786b885cc40a4fdc2ea0bedccb2d453777fd --- /dev/null +++ b/node_modules/mouse-event-offset/README.md @@ -0,0 +1,35 @@ +# mouse-event-offset + +[![stable](http://badges.github.io/stability-badges/dist/stable.svg)](http://github.com/badges/stability-badges) + +Computes the `[ offsetX, offsetY ]` from a mouse or touch event, relative to the top left of the `target` element. + +```js +var offset = require('mouse-event-offset') + +window.addEventListener('touchstart', function (ev) { + var target = ev.currentTarget + var touch = ev.changedTouches[0] + var pos = offset(touch, target) + //=> [ 128, 52 ] +}) +``` +## Usage + +### `position = offset(event, [target], [out])` + +Pass a MouseEvent or TouchEvent as `event`. + +Optionally, you can specify a `target` element which the touch event should be relative to. Defaults to `event.currentTarget`, falling back to `event.srcElement` for older IE. + +You can also specifiy `out` to store the position in that array, and avoid creating a new one. + +## Changelog + +- `3.x` new version; simpler API, less assumptions, avoids GC thrashing +- `2.x` uses `ev.currentTarget` instead of `ev.target` +- `1.x` simple implementation using `ev.target || ev.srcElement` + +## License + +MIT, see [LICENSE.md](http://github.com/mattdesl/mouse-event-offset/blob/master/LICENSE.md) for details. diff --git a/node_modules/mouse-event-offset/index.js b/node_modules/mouse-event-offset/index.js new file mode 100644 index 0000000000000000000000000000000000000000..432feba49653c8edcec4347958d1ab1d0b029e51 --- /dev/null +++ b/node_modules/mouse-event-offset/index.js @@ -0,0 +1,25 @@ +var rootPosition = { left: 0, top: 0 } + +module.exports = mouseEventOffset +function mouseEventOffset (ev, target, out) { + target = target || ev.currentTarget || ev.srcElement + if (!Array.isArray(out)) { + out = [ 0, 0 ] + } + var cx = ev.clientX || 0 + var cy = ev.clientY || 0 + var rect = getBoundingClientOffset(target) + out[0] = cx - rect.left + out[1] = cy - rect.top + return out +} + +function getBoundingClientOffset (element) { + if (element === window || + element === document || + element === document.body) { + return rootPosition + } else { + return element.getBoundingClientRect() + } +} diff --git a/node_modules/mouse-event-offset/package.json b/node_modules/mouse-event-offset/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c5a9c7ca0c7afe51915e644fd70ec29fa31a431b --- /dev/null +++ b/node_modules/mouse-event-offset/package.json @@ -0,0 +1,52 @@ +{ + "name": "mouse-event-offset", + "version": "3.0.2", + "description": "get relative position from an event", + "main": "index.js", + "license": "MIT", + "author": "Matt DesLauriers ", + "dependencies": {}, + "devDependencies": { + "tape": "~2.13.2" + }, + "scripts": { + "test": "node test.js" + }, + "testling": { + "files": "test.js", + "browsers": [ + "ie/6..latest", + "chrome/22..latest", + "firefox/16..latest", + "safari/latest", + "opera/11.0..latest", + "iphone/6", + "ipad/6", + "android-browser/latest" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/mattdesl/mouse-event-offset.git" + }, + "homepage": "https://github.com/mattdesl/mouse-event-offset", + "bugs": { + "url": "https://github.com/mattdesl/mouse-event-offset/issues" + }, + "keywords": [ + "mouse", + "event", + "offset", + "top", + "left", + "corner", + "clientX", + "clientY", + "offsetX", + "offsetY", + "getBoundingClientRect", + "click", + "relative", + "position" + ] +} diff --git a/node_modules/mouse-event/.npmignore b/node_modules/mouse-event/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..ddc9ab330c2a9e77591abb3effd1b9ebf278a988 --- /dev/null +++ b/node_modules/mouse-event/.npmignore @@ -0,0 +1,16 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log +node_modules/* +*.DS_Store \ No newline at end of file diff --git a/node_modules/mouse-event/LICENSE b/node_modules/mouse-event/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1815ddd61d61d007ca9c832c7d69ffc8a4f9f86a --- /dev/null +++ b/node_modules/mouse-event/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2015 Mikola Lysenko + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/mouse-event/README.md b/node_modules/mouse-event/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0d885b9918c64ebd301445fe7deac14a5c428ec2 --- /dev/null +++ b/node_modules/mouse-event/README.md @@ -0,0 +1,70 @@ +# mouse-event +Provides a normalized, cross-browser, garbage-collection-free API for reading out the state of a mouse event. + +### Why is this needed? +Because it is 2015 and somehow every major browser still disagrees on even the most basic details of MouseEvents. Seriously guys. + +# Example + +```javascript +var mouse = require('mouse-event') + +window.addEventListener('mousemove', function(ev) { + document.body.innerHTML = + '

Buttons: ' + mouse.buttons(ev) + + ' x:' + mouse.x(ev) + + ' y:' + mouse.y(ev) + '

' +}) +``` + +[Try this in your browser](https://mikolalysenko.github.io/mouse-event) + +# Install + +``` +npm i mouse-event +``` + +# API + +```javascript +var mouse = require('mouse-event') +``` + +#### `mouse.buttons(event)` +Returns a bit vector, similar to `event.which` in WebKit encoding the state of the mouse buttons. + +* `event` is a mouse event + +**Returns** A bit vector with the following interpretation for the flags: +* `1` - left mouse +* `2` - right mouse +* `4` - middle mouse +* `8` - button 4 +* `16` - button 5 +* ... +* `1<Buttons: ' + mouse.buttons(ev) + + ' x:' + mouse.x(ev) + + ' y:' + mouse.y(ev) + '

' +} + +window.oncontextmenu = function(ev) { + ev.stopPropagation() + ev.preventDefault() + return false +} \ No newline at end of file diff --git a/node_modules/mouse-event/mouse.js b/node_modules/mouse-event/mouse.js new file mode 100644 index 0000000000000000000000000000000000000000..fe37124ae08740f3b10c328aadd71b0091d9d4d1 --- /dev/null +++ b/node_modules/mouse-event/mouse.js @@ -0,0 +1,60 @@ +'use strict' + +function mouseButtons(ev) { + if(typeof ev === 'object') { + if('buttons' in ev) { + return ev.buttons + } else if('which' in ev) { + var b = ev.which + if(b === 2) { + return 4 + } else if(b === 3) { + return 2 + } else if(b > 0) { + return 1<<(b-1) + } + } else if('button' in ev) { + var b = ev.button + if(b === 1) { + return 4 + } else if(b === 2) { + return 2 + } else if(b >= 0) { + return 1<' +}) +``` + +# Install + +``` +npm i mouse-wheel +``` + +# API + +#### `require('mouse-wheel')(element, callback, noScroll)` +Hook an event handler for the mouse wheel on `element`. + +* `element` is an optional DOM element, or if unspecified then is the window object. +* `callback(dx, dy, dz, ev)` is called whenever the mouse scrolls + + `dx, dy, dz` is the amount of scrolling vertically, horizontally and depth-wise in pixels + + `ev` is the MouseEvent object associated with the event +* `noScroll` is an optional flag, which if set disables scrolling the page + +Returns listener function `listener` so that it may be detached later with `element.removeEventListener('wheel', listener)` + +# License +(c) 2015 Mikola Lysenko. MIT License diff --git a/node_modules/mouse-wheel/example/example.js b/node_modules/mouse-wheel/example/example.js new file mode 100644 index 0000000000000000000000000000000000000000..95da96bffded28d0466a48fe855e1f016819004e --- /dev/null +++ b/node_modules/mouse-wheel/example/example.js @@ -0,0 +1,27 @@ +'use strict' + +var totalX = (window.innerWidth/2)|0, totalY = (window.innerHeight/2)|0 + +var box = document.createElement('div') +box.style.position = 'absolute' +box.style.width = '20px' +box.style.height = '20px' +box.style.left = totalX + 'px' +box.style.top = totalY + 'px' +box.style['background-color'] = '#f00' +box.style['z-index'] = 10 +document.body.appendChild(box) + +var infoLog = document.createElement('div') +infoLog.innerHTML = 'Scroll to move box' +document.body.appendChild(infoLog) + +require('../wheel')(function(dx, dy) { + totalX -= dx + totalY -= dy + box.style.left = totalX + 'px' + box.style.top = totalY + 'px' + infoLog.innerHTML = + '

Scroll:' + dx + ',' + dy + ' - ' + + totalX + ',' + totalY + '

' +}, true) \ No newline at end of file diff --git a/node_modules/mouse-wheel/package.json b/node_modules/mouse-wheel/package.json new file mode 100644 index 0000000000000000000000000000000000000000..cbbdf86f06992d214de411b5d5ed9c352c9a5879 --- /dev/null +++ b/node_modules/mouse-wheel/package.json @@ -0,0 +1,39 @@ +{ + "name": "mouse-wheel", + "version": "1.2.0", + "description": "Consistent cross browser mouse wheel movement", + "main": "wheel.js", + "directories": { + "example": "example" + }, + "dependencies": { + "right-now": "^1.0.0", + "to-px": "^1.0.1", + "signum": "^1.0.0" + }, + "devDependencies": {}, + "scripts": { + "test": "tape test/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/mikolalysenko/mouse-wheel.git" + }, + "keywords": [ + "mouse", + "wheel", + "browser", + "speed", + "consistent", + "portability", + "poly", + "fill", + "fix" + ], + "author": "Mikola Lysenko", + "license": "MIT", + "bugs": { + "url": "https://github.com/mikolalysenko/mouse-wheel/issues" + }, + "homepage": "https://github.com/mikolalysenko/mouse-wheel" +} diff --git a/node_modules/mouse-wheel/wheel.js b/node_modules/mouse-wheel/wheel.js new file mode 100644 index 0000000000000000000000000000000000000000..aacb942fb8b06f54e19a7d8bed127d8ff38bf8a2 --- /dev/null +++ b/node_modules/mouse-wheel/wheel.js @@ -0,0 +1,40 @@ +'use strict' + +var toPX = require('to-px') + +module.exports = mouseWheelListen + +function mouseWheelListen(element, callback, noScroll) { + if(typeof element === 'function') { + noScroll = !!callback + callback = element + element = window + } + var lineHeight = toPX('ex', element) + var listener = function(ev) { + if(noScroll) { + ev.preventDefault() + } + var dx = ev.deltaX || 0 + var dy = ev.deltaY || 0 + var dz = ev.deltaZ || 0 + var mode = ev.deltaMode + var scale = 1 + switch(mode) { + case 1: + scale = lineHeight + break + case 2: + scale = window.innerHeight + break + } + dx *= scale + dy *= scale + dz *= scale + if(dx || dy || dz) { + return callback(dx, dy, dz, ev) + } + } + element.addEventListener('wheel', listener) + return listener +} diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ea734fb73820316ed1c0f6a2f6e96dce0e3eb6f0 --- /dev/null +++ b/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 0000000000000000000000000000000000000000..fa5d39b6213f8a5e142b643575f99d9149cc71c6 --- /dev/null +++ b/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 0000000000000000000000000000000000000000..49971890df8e2b9a4a5f4909fbd6678b862d8a50 --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,38 @@ +{ + "name": "ms", + "version": "2.1.3", + "description": "Tiny millisecond conversion utility", + "repository": "vercel/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.18.2", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1", + "prettier": "2.0.5" + } +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..0fc1abb3b8e30a3ab97023d243127c75b1b3a4d7 --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,59 @@ +# ms + +![CI](https://github.com/vercel/ms/workflows/CI/badge.svg) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/mumath/.eslintrc.json b/node_modules/mumath/.eslintrc.json new file mode 100644 index 0000000000000000000000000000000000000000..c50c250446ee6d06a87a590ecbf3905696b0871d --- /dev/null +++ b/node_modules/mumath/.eslintrc.json @@ -0,0 +1,43 @@ +{ + "env": { + "browser": true, + "node": true, + "commonjs": true, + "es6": true + }, + "extends": "eslint:recommended", + "rules": { + "strict": 2, + "indent": 0, + "linebreak-style": 0, + "quotes": 0, + "semi": 0, + "no-cond-assign": 1, + "no-constant-condition": 1, + "no-duplicate-case": 1, + "no-empty": 1, + "no-ex-assign": 1, + "no-extra-boolean-cast": 1, + "no-extra-semi": 1, + "no-fallthrough": 1, + "no-func-assign": 1, + "no-global-assign": 1, + "no-implicit-globals": 2, + "no-inner-declarations": ["error", "functions"], + "no-irregular-whitespace": 2, + "no-loop-func": 1, + "no-multi-str": 1, + "no-mixed-spaces-and-tabs": 1, + "no-proto": 1, + "no-sequences": 1, + "no-throw-literal": 1, + "no-unmodified-loop-condition": 1, + "no-useless-call": 1, + "no-void": 1, + "no-with": 2, + "wrap-iife": 1, + "no-redeclare": 1, + "no-unused-vars": ["error", { "vars": "all", "args": "none" }], + "no-sparse-arrays": 1 + } +} diff --git a/node_modules/mumath/.npmignore b/node_modules/mumath/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..f9d5e7e8582d590e8ee6d8c4612911d2e5c869e3 --- /dev/null +++ b/node_modules/mumath/.npmignore @@ -0,0 +1,38 @@ +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +node_modules + +# Optional npm cache directory +.npm + +# Optional REPL history +.node_repl_history + +bundle.js +demo + +images \ No newline at end of file diff --git a/node_modules/mumath/.travis.yml b/node_modules/mumath/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..0bb209b82e5ed58ae2152aa0c5f7167feada35d4 --- /dev/null +++ b/node_modules/mumath/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "4" + - "6" + - "node" diff --git a/node_modules/mumath/README.md b/node_modules/mumath/README.md new file mode 100644 index 0000000000000000000000000000000000000000..06aace11c056a172870192d213f0bdf7b65cfaa1 --- /dev/null +++ b/node_modules/mumath/README.md @@ -0,0 +1,85 @@ +# μMath [![Build Status](https://travis-ci.org/dfcreative/mumath.svg?branch=master)](https://travis-ci.org/dfcreative/mumath) [![Code Climate](https://codeclimate.com/github/dfcreative/mumath/badges/gpa.svg)](https://codeclimate.com/github/dfcreative/mumath) + +Set of practical math utils to shorten code. + +[`$ npm install mumath`](https://npmjs.org/package/mumath) + +```js +var round = require('mumath/round'); +round(123.32, .5); //123.5 + +//require any function as +//var = require('mumath/'); +``` + +## API + +### `round(value, step?)` + +Rounds value to optional `step`. + +`round(0.3, .5)` → `.5` + + +### `len(a, b)` + +Return length of a vector. + + +### `precision(value)` + +Get precision from float: + +`1.1 → 1, 1234 → 0, .1234 → 4` + + +### `clamp(value, left, right)` + +Return value clamped by left/right limits (or vice-versa). + + +### `lerp(x, y, ratio)` + +Return value interpolated between x and y. + + +### `within(value, left, right)` + +Whether element is between left & right, including. + + +### `mod(value, min?, max)` + +An enhanced [mod-loop](http://npmjs.org/package/mod-loop) — loops value within a frame. + + +### `closest(value, list)` + +Get closest value out of a set. + + +### `scale(value, list)` + +Get first scale out of a list of basic scales, aligned to the power. E. g. + +`step(.37, [1, 2, 5])` → `.5` +`step(456, [1, 2])` → `1000` + +Similar to closest, but takes all possible powers of scales. + +### `order(value)` + +Get order of magnitude for a number. + +`order(123) → 100; order(-0.0003) → 0.0001;` + + +### `isMultiple(a, b, eps?)` + +Same as `a % b === 0`, but with precision check. + + +## Related + +* [bit-twiddle](https://www.npmjs.com/package/bit-twiddle) — utils for power-of-two numbers. +* [pretty-number](https://www.npmjs.com/package/pretty-number) — format number to pretty view. diff --git a/node_modules/mumath/UNLICENSE b/node_modules/mumath/UNLICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b0a72fb2d1e53f83243083169964676d58452f82 --- /dev/null +++ b/node_modules/mumath/UNLICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to \ No newline at end of file diff --git a/node_modules/mumath/clamp.js b/node_modules/mumath/clamp.js new file mode 100644 index 0000000000000000000000000000000000000000..0f7b2d32d18589d5c2bc5a263a78e75d60659b1c --- /dev/null +++ b/node_modules/mumath/clamp.js @@ -0,0 +1,14 @@ +/** + * Clamp value. + * Detects proper clamp min/max. + * + * @param {number} a Current value to cut off + * @param {number} min One side limit + * @param {number} max Other side limit + * + * @return {number} Clamped value + */ +'use strict'; +module.exports = function(a, min, max){ + return max > min ? Math.max(Math.min(a,max),min) : Math.max(Math.min(a,min),max); +}; diff --git a/node_modules/mumath/closest.js b/node_modules/mumath/closest.js new file mode 100644 index 0000000000000000000000000000000000000000..bc582571663908279c9f201e9f63cbb05e63e6a8 --- /dev/null +++ b/node_modules/mumath/closest.js @@ -0,0 +1,17 @@ +/** + * @module mumath/closest + */ +'use strict'; + +module.exports = function closest (num, arr) { + var curr = arr[0]; + var diff = Math.abs (num - curr); + for (var val = 0; val < arr.length; val++) { + var newdiff = Math.abs (num - arr[val]); + if (newdiff < diff) { + diff = newdiff; + curr = arr[val]; + } + } + return curr; +} diff --git a/node_modules/mumath/index.js b/node_modules/mumath/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6ed2fcc9cebcb5bb346e895219d24e657a275f96 --- /dev/null +++ b/node_modules/mumath/index.js @@ -0,0 +1,24 @@ +/** + * Composed set of all math utils, wrapped + * + * @module mumath + */ +'use strict'; +const wrap = require('./wrap'); + +module.exports = { + clamp: wrap(require('./clamp')), + within: wrap(require('./within')), + round: wrap(require('./round')), + precision: wrap(require('./precision')), + mod: wrap(require('./mod')), + log10: wrap(require('./log10')), + len: wrap(require('./len')), + closest: wrap(require('./closest')), + order: wrap(require('./order')), + lerp: wrap(require('./lerp')), + isMultiple: wrap(require('./is-multiple')), + normalize: wrap(require('./normalize')), + scale: wrap(require('./scale')), + // pretty: wrap(require('./pretty')), +}; diff --git a/node_modules/mumath/is-multiple.js b/node_modules/mumath/is-multiple.js new file mode 100644 index 0000000000000000000000000000000000000000..8a6284cfefb432ff65371cda776bb355cddb3567 --- /dev/null +++ b/node_modules/mumath/is-multiple.js @@ -0,0 +1,20 @@ +/** + * Check if one number is multiple of other + * + * @module mumath/is-multiple + */ +'use strict'; +var almost = require('almost-equal'); + +module.exports = isMultiple; + +function isMultiple (a, b, eps) { + var remainder = a % b; + + if (!eps) eps = almost.FLT_EPSILON; + + if (!remainder) return true; + if (almost(0, remainder, eps, 0) || almost(Math.abs(b), Math.abs(remainder), eps, 0)) return true; + + return false; +} diff --git a/node_modules/mumath/len.js b/node_modules/mumath/len.js new file mode 100644 index 0000000000000000000000000000000000000000..23d7d2965dc7c87600c399349e62b038cbb31571 --- /dev/null +++ b/node_modules/mumath/len.js @@ -0,0 +1,11 @@ +/** + * Return quadratic length + * + * @module mumath/loop + * + */ +'use strict'; + +module.exports = function (a, b) { + return Math.sqrt(a*a + b*b); +}; diff --git a/node_modules/mumath/lerp.js b/node_modules/mumath/lerp.js new file mode 100644 index 0000000000000000000000000000000000000000..561b7ba4f6b145912f422b9c23a7758849967279 --- /dev/null +++ b/node_modules/mumath/lerp.js @@ -0,0 +1,7 @@ +/** + * @module mumath/lerp + */ +'use strict'; +module.exports = function (x, y, a) { + return x * (1.0 - a) + y * a; +}; diff --git a/node_modules/mumath/log10.js b/node_modules/mumath/log10.js new file mode 100644 index 0000000000000000000000000000000000000000..225cb8afd4825aa1ff6faf43d716af6a36719d63 --- /dev/null +++ b/node_modules/mumath/log10.js @@ -0,0 +1,9 @@ +/** + * Base 10 logarithm + * + * @module mumath/log10 + */ +'use strict'; +module.exports = Math.log10 || function (a) { + return Math.log(a) / Math.log(10); +}; diff --git a/node_modules/mumath/mod.js b/node_modules/mumath/mod.js new file mode 100644 index 0000000000000000000000000000000000000000..fcd05b8eff44f8462a22b75266ee3d6f16f82946 --- /dev/null +++ b/node_modules/mumath/mod.js @@ -0,0 +1,31 @@ +/** + * Looping function for any framesize. + * Like fmod. + * + * @module mumath/loop + * + */ + +'use strict'; +module.exports = function (value, left, right) { + //detect single-arg case, like mod-loop or fmod + if (right === undefined) { + right = left; + left = 0; + } + + //swap frame order + if (left > right) { + var tmp = right; + right = left; + left = tmp; + } + + var frame = right - left; + + value = ((value + left) % frame) - left; + if (value < left) value += frame; + if (value > right) value -= frame; + + return value; +}; diff --git a/node_modules/mumath/normalize.js b/node_modules/mumath/normalize.js new file mode 100644 index 0000000000000000000000000000000000000000..625bd6129b427762c5ceab974a221b832efc7cd8 --- /dev/null +++ b/node_modules/mumath/normalize.js @@ -0,0 +1,35 @@ +/** + * Get rid of float remainder + * + * @module mumath/normalize + */ +'use strict'; + +var almost = require('almost-equal'); + +module.exports = function(value, eps) { + //ignore ints + var rem = value%1; + if (!rem) return value; + + if (eps == null) eps = Number.EPSILON || almost.FLT_EPSILON; + + //pick number’s neighbour, which is way shorter, like 0.4999999999999998 → 0.5 + //O(20) + var range = 5; + var len = (rem+'').length; + + for (var i = 1; i < range; i+=.5) { + var left = rem - eps*i, + right = rem + eps*i; + + var leftStr = left+'', rightStr = right + ''; + + if (len - leftStr.length > 2) return value - eps*i; + if (len - rightStr.length > 2) return value + eps*i; + + // if (leftStr[2] != rightStr[2]) + } + + return value; +}; diff --git a/node_modules/mumath/order.js b/node_modules/mumath/order.js new file mode 100644 index 0000000000000000000000000000000000000000..87723dfeddd5e9bb3bc66b5184db2a5590c95709 --- /dev/null +++ b/node_modules/mumath/order.js @@ -0,0 +1,9 @@ +/** + * @module mumath/order + */ +'use strict'; +module.exports = function (n) { + n = Math.abs(n); + var order = Math.floor(Math.log(n) / Math.LN10 + 0.000000001); + return Math.pow(10,order); +}; diff --git a/node_modules/mumath/package.json b/node_modules/mumath/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1e6e09c21332178c456de231e1e76558e44d8e9b --- /dev/null +++ b/node_modules/mumath/package.json @@ -0,0 +1,26 @@ +{ + "name": "mumath", + "version": "3.3.4", + "description": "Practical math utils for components", + "main": "index.js", + "scripts": { + "test": "node test/index.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/dfcreative/mumath.git" + }, + "keywords": [ + "math", + "geometry" + ], + "author": "dfcreative", + "license": "Unlicense", + "bugs": { + "url": "https://github.com/dfcreative/mumath/issues" + }, + "homepage": "https://github.com/dfcreative/mumath", + "dependencies": { + "almost-equal": "^1.1.0" + } +} diff --git a/node_modules/mumath/precision.js b/node_modules/mumath/precision.js new file mode 100644 index 0000000000000000000000000000000000000000..d70b234316984450f2c46c49ebf879624fcc3b5c --- /dev/null +++ b/node_modules/mumath/precision.js @@ -0,0 +1,40 @@ +/** + * @module mumath/precision + * + * Get precision from float: + * + * @example + * 1.1 → 1, 1234 → 0, .1234 → 4 + * + * @param {number} n + * + * @return {number} decimap places + */ +'use strict'; + +var almost = require('almost-equal'); +var norm = require('./normalize'); + +module.exports = function (n, eps) { + n = norm(n); + + var str = n + ''; + + //1e-10 etc + var e = str.indexOf('e-'); + if (e >= 0) return parseInt(str.substring(e+2)); + + //imperfect ints, like 3.0000000000000004 or 1.9999999999999998 + var remainder = Math.abs(n % 1); + var remStr = remainder + ''; + + if (almost(remainder, 1, eps) || almost(remainder, 0, eps)) return 0; + + //usual floats like .0123 + var d = remStr.indexOf('.') + 1; + + if (d) return remStr.length - d; + + //regular inte + return 0; +}; diff --git a/node_modules/mumath/pretty.js b/node_modules/mumath/pretty.js new file mode 100644 index 0000000000000000000000000000000000000000..2b0bcd792d27bd0d19959589adb94551625de1fa --- /dev/null +++ b/node_modules/mumath/pretty.js @@ -0,0 +1,23 @@ +/** + * Format number nicely + * + * @module mumath/loop + * + */ +'use strict'; + +var precision = require('./precision'); +var almost = require('almost-equal'); +var normalize = require('./normalize'); + +module.exports = function (v, prec) { + if (almost(v, 0)) return '0'; + + if (prec == null) { + prec = precision(v); + prec = Math.min(prec, 20); + } + + // return v.toFixed(prec); + return v.toFixed(prec); +}; diff --git a/node_modules/mumath/round.js b/node_modules/mumath/round.js new file mode 100644 index 0000000000000000000000000000000000000000..637ec819187095f7066ea63d337805377ac0e64b --- /dev/null +++ b/node_modules/mumath/round.js @@ -0,0 +1,22 @@ +/** + * Precision round + * + * @param {number} value + * @param {number} step Minimal discrete to round + * + * @return {number} + * + * @example + * toPrecision(213.34, 1) == 213 + * toPrecision(213.34, .1) == 213.3 + * toPrecision(213.34, 10) == 210 + */ +'use strict'; +var precision = require('./precision'); + +module.exports = function(value, step) { + if (step === 0) return value; + if (!step) return Math.round(value); + value = Math.round(value / step) * step; + return parseFloat(value.toFixed(precision(step))); +}; diff --git a/node_modules/mumath/scale.js b/node_modules/mumath/scale.js new file mode 100644 index 0000000000000000000000000000000000000000..6e26427c25b43b8e6b6c371192932539c04fe8fc --- /dev/null +++ b/node_modules/mumath/scale.js @@ -0,0 +1,26 @@ +/** + * Get step out of the set + * + * @module mumath/step + */ +'use strict'; + +var lg = require('./log10'); + +module.exports = function (minStep, srcSteps) { + var power = Math.floor(lg(minStep)); + + var order = Math.pow(10, power); + var steps = srcSteps.map(v => v*order); + order = Math.pow(10, power+1); + steps = steps.concat(srcSteps.map(v => v*order)); + + //find closest scale + var step = 0; + for (var i = 0; i < steps.length; i++) { + step = steps[i]; + if (step >= minStep) break; + } + + return step; +}; diff --git a/node_modules/mumath/test/index.js b/node_modules/mumath/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0504648fdec779a4f3d32d9abec465dff9e1eb0a --- /dev/null +++ b/node_modules/mumath/test/index.js @@ -0,0 +1,108 @@ +var m = require('../index'); +var assert = require('assert'); + +// assert.equal(m.min(0,2),0); +// assert.equal(m.max(0,2),2); +// assert.deepEqual(m.min([0,0],[2,-2]),[0,-2]); + +assert.equal(m.clamp(-100, 0, 100), 0); +assert.equal(m.clamp(-100, 100, 0), 0); +assert.equal(m.clamp(-Infinity, -100, 0), -100); + +//limit arrays +assert.deepEqual(m.clamp([-100, -200], -100, 100), [-100, -100]); +assert.deepEqual(m.clamp([-101, 101], [-50, -100], [100, 50]), [-50, 50]); + +//limit objects +assert.deepEqual(m.clamp({top: 120, bottom: -10}, 0, 100), {top: 100, bottom: 0}); +assert.deepEqual(m.clamp({top: 120, bottom: -10}, {top: 0, bottom:0}, {top: 100, bottom: 100}), {top: 100, bottom: 0}); + +//normalize +assert.equal(m.normalize(-0.4999999999999998), -.5); +assert.equal(m.normalize(1.5000000000000002), 1.5); +assert.equal(m.normalize(10.5000000000000002), 10.5); +assert.equal(m.normalize(-0.7999999999999996), -.8); + + +//precisions +assert.equal(m.precision(1.0000000000000005e+33), 0); +assert.equal(m.precision(3.0000000000000004), 0); +assert.equal(m.precision(1.9999999999999998), 0); +assert.equal(m.precision(0.02), 2); +assert.equal(m.precision(100), 0); +assert.equal(m.precision(1e-1), 1); +assert.equal(m.precision(1e-5), 5); +assert.equal(m.precision(1e-19), 19); +assert.equal(m.precision(1.0000000000000001e+33), 0); +assert.equal(m.precision(-0.4999999999999998), 1); +assert.equal(m.precision(1.5000000000000002), 1); +assert.equal(m.precision(-0.7999999999999996), 1); + + +assert.equal(m.round(0.3, .5), .5); + +//multiple +assert.equal(m.isMultiple(100,10), true); +assert.equal(m.isMultiple(100.1,10, .1), true); + +//loop +assert.equal(m.mod(10, 100), 10); + +assert.equal(m.mod(110, 100), 10); +assert.equal(m.mod(110, 90), 20); + +assert.equal(m.mod(-110, 100), 90); + +assert.equal(m.mod(110, 0, 100), 10); +assert.equal(m.mod(110, -10, 100), 0); +assert.equal(m.mod(110, -10, 90), 10); +assert.equal(m.mod(-110, -100, 0), -10); +assert.equal(m.mod(-110, -100, 10), 0); +assert.equal(m.mod(-110, -90, 10), -10); + +//lg +assert.equal(m.log10(100), 2); +assert.equal(m.log10(10), 1); +assert.equal(m.log10(1), 0); +assert.equal(Math.round(m.log10(0.1)), -1); + +//len +assert.equal(m.len(3,4), 5); + +//closest +assert.equal(m.closest(0.2, [0.01, 0.1, 1, 10, 100]), 0.1); + +//order +assert.equal(m.order(123), 100); +assert.equal(m.order(0.000213), 0.0001); +assert.equal(m.order(-123), 100); +assert.equal(m.order(-0.0000123), 0.00001); + +assert(m.within(1, 0, 2)); +assert(m.within(1, 2, 0)); +assert(!m.within(0, 2, 1)); + + +assert.equal(m.lerp(1,0,.5), .5); + + +//step +assert.equal(m.scale(.1, [1, 2, 5]), .1); +assert.equal(m.scale(.1, [1, 2, 5]), .1); + + + +//formatting +// assert.equal(m.pretty(1.9999999999999998), '2'); +// assert.equal(m.pretty(1.0000000000000005e+33), '1e+33'); +// assert.equal(m.pretty(0.1), '0.1'); +// assert.equal(m.pretty(3.0000000000000004), '3'); +// assert.equal(m.pretty(7.0000000000000036, 2), '7'); +// assert.equal(m.pretty(3.885780586188048e-16), '0'); +// assert.equal(m.pretty(-1.9999999999999993), '-2'); +// assert.equal(m.pretty(-0.9999999999999996), '-1'); +// assert.equal(m.pretty(1.5000000000000002), '1.5'); +// assert.equal(m.pretty(-0.4999999999999998), '-0.5'); +// assert.equal(m.pretty(-0.7999999999999996), '-0.8'); +// assert.equal(m.pretty(500), '500'); +// assert.equal(m.pretty(0.4000000000000002), '0.4'); diff --git a/node_modules/mumath/within.js b/node_modules/mumath/within.js new file mode 100644 index 0000000000000000000000000000000000000000..851cc1cb22465abd4ffeb0bb6706f6b5ec39f8e5 --- /dev/null +++ b/node_modules/mumath/within.js @@ -0,0 +1,19 @@ +/** + * Whether element is between left & right including + * + * @param {number} a + * @param {number} left + * @param {number} right + * + * @return {Boolean} + */ +'use strict'; +module.exports = function(a, left, right){ + if (left > right) { + var tmp = left; + left = right; + right = tmp; + } + if (a <= right && a >= left) return true; + return false; +}; diff --git a/node_modules/mumath/wrap.js b/node_modules/mumath/wrap.js new file mode 100644 index 0000000000000000000000000000000000000000..977bb4cbf1ff10ed8d12dd11f1cd79965bd78a81 --- /dev/null +++ b/node_modules/mumath/wrap.js @@ -0,0 +1,38 @@ +/** + * Get fn wrapped with array/object attrs recognition + * + * @return {Function} Target function + */ +'use strict'; +module.exports = function(fn){ + return function (a) { + var args = arguments; + if (a instanceof Array) { + var result = new Array(a.length), slice; + for (var i = 0; i < a.length; i++){ + slice = []; + for (var j = 0, l = args.length, val; j < l; j++){ + val = args[j] instanceof Array ? args[j][i] : args[j]; + slice.push(val); + } + result[i] = fn.apply(this, slice); + } + return result; + } + else if (typeof a === 'object') { + var result = {}, slice; + for (var i in a){ + slice = []; + for (var j = 0, l = args.length, val; j < l; j++){ + val = typeof args[j] === 'object' ? args[j][i] : args[j]; + slice.push(val); + } + result[i] = fn.apply(this, slice); + } + return result; + } + else { + return fn.apply(this, args); + } + }; +}; diff --git a/node_modules/murmurhash-js/README.md b/node_modules/murmurhash-js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..62cb1e9aad8c886a2c5967e9c7ad2bb0e7571fa6 --- /dev/null +++ b/node_modules/murmurhash-js/README.md @@ -0,0 +1,40 @@ +# MurmurHash.js + +An optimized JavaScript implementation of the MurmurHash algorithms. + +These algorithms take a JavaScript string (and a seed), and quickly create a non-cryptographic 32-bit hash from it. And by quick I mean sub-millisecond performance. + +More information about these algorithms can be found at: + +* [MurmurHash Homepage](http://sites.google.com/site/murmurhash/) +* [Wikipedia Entry on MurmurHash](http://en.wikipedia.org/wiki/MurmurHash) + +## Install + + npm install murmurhash-js + +## API + +```javascript +var murmur = require("murmurhash-js") +``` + +### Methods + +#### `murmur.murmur2(key, seed)` +Runs the murmur2 hash algorithm on the string `key` with initial seed `seed`. + +#### `murmur.murmur3(key, seed)` +Runs the murmur3 hash algorithm on the string `key` with initial seed `seed`. + +**Note** `require("murmur-hash")` is the same as `murmur.murmur3` + +## License (MIT) + +Copyright (c) 2011 Gary Court + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/murmurhash-js/index.js b/node_modules/murmurhash-js/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d56fbcf780307cc4671d08f8376633dae3fb00b7 --- /dev/null +++ b/node_modules/murmurhash-js/index.js @@ -0,0 +1,6 @@ +var murmur3 = require("./murmurhash3_gc.js") +var murmur2 = require("./murmurhash2_gc.js") + +module.exports = murmur3 +module.exports.murmur3 = murmur3 +module.exports.murmur2 = murmur2 diff --git a/node_modules/murmurhash-js/murmurhash2_gc.js b/node_modules/murmurhash-js/murmurhash2_gc.js new file mode 100644 index 0000000000000000000000000000000000000000..1d169614b50d541927649f2f2089e48a69d86c28 --- /dev/null +++ b/node_modules/murmurhash-js/murmurhash2_gc.js @@ -0,0 +1,54 @@ +/** + * JS Implementation of MurmurHash2 + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} str ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ + +function murmurhash2_32_gc(str, seed) { + var + l = str.length, + h = seed ^ l, + i = 0, + k; + + while (l >= 4) { + k = + ((str.charCodeAt(i) & 0xff)) | + ((str.charCodeAt(++i) & 0xff) << 8) | + ((str.charCodeAt(++i) & 0xff) << 16) | + ((str.charCodeAt(++i) & 0xff) << 24); + + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + k ^= k >>> 24; + k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; + + l -= 4; + ++i; + } + + switch (l) { + case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; + case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; + case 1: h ^= (str.charCodeAt(i) & 0xff); + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + } + + h ^= h >>> 13; + h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + h ^= h >>> 15; + + return h >>> 0; +} + +if(typeof module !== undefined) { + module.exports = murmurhash2_32_gc +} diff --git a/node_modules/murmurhash-js/murmurhash3_gc.js b/node_modules/murmurhash-js/murmurhash3_gc.js new file mode 100644 index 0000000000000000000000000000000000000000..c9b0b6ad7757dacffefecc534f0a5b5d8082fd0b --- /dev/null +++ b/node_modules/murmurhash-js/murmurhash3_gc.js @@ -0,0 +1,68 @@ +/** + * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) + * + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + * + * @param {string} key ASCII only + * @param {number} seed Positive integer only + * @return {number} 32-bit positive integer hash + */ + +function murmurhash3_32_gc(key, seed) { + var remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i; + + remainder = key.length & 3; // key.length % 4 + bytes = key.length - remainder; + h1 = seed; + c1 = 0xcc9e2d51; + c2 = 0x1b873593; + i = 0; + + while (i < bytes) { + k1 = + ((key.charCodeAt(i) & 0xff)) | + ((key.charCodeAt(++i) & 0xff) << 8) | + ((key.charCodeAt(++i) & 0xff) << 16) | + ((key.charCodeAt(++i) & 0xff) << 24); + ++i; + + k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff; + + h1 ^= k1; + h1 = (h1 << 13) | (h1 >>> 19); + h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff; + h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16)); + } + + k1 = 0; + + switch (remainder) { + case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; + case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; + case 1: k1 ^= (key.charCodeAt(i) & 0xff); + + k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; + h1 ^= k1; + } + + h1 ^= key.length; + + h1 ^= h1 >>> 16; + h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; + h1 ^= h1 >>> 13; + h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff; + h1 ^= h1 >>> 16; + + return h1 >>> 0; +} + +if(typeof module !== "undefined") { + module.exports = murmurhash3_32_gc +} \ No newline at end of file diff --git a/node_modules/murmurhash-js/package.json b/node_modules/murmurhash-js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f12ada4fad29ce2ac369bf960e947b6941986464 --- /dev/null +++ b/node_modules/murmurhash-js/package.json @@ -0,0 +1,28 @@ +{ + "name": "murmurhash-js", + "version": "1.0.0", + "description": "Native JS murmur hash implementation", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/mikolalysenko/murmurhash-js.git" + }, + "keywords": [ + "murmur", + "hash", + "string", + "murmur2", + "murmur3", + "fast" + ], + "author": "Gary Court", + "license": "MIT", + "readmeFilename": "README.md", + "gitHead": "72aabce3f52cb8f16245692a69fd35951e165af0", + "bugs": { + "url": "https://github.com/mikolalysenko/murmurhash-js/issues" + } +} diff --git a/node_modules/nanoid/LICENSE b/node_modules/nanoid/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..37f56aa49f8e009ed7e582cb3e905a1e0d1666fd --- /dev/null +++ b/node_modules/nanoid/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2017 Andrey Sitnik + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/nanoid/README.md b/node_modules/nanoid/README.md new file mode 100644 index 0000000000000000000000000000000000000000..35abb57d88a7613ff9c47a84cfb3ba4afbedea84 --- /dev/null +++ b/node_modules/nanoid/README.md @@ -0,0 +1,39 @@ +# Nano ID + +Nano ID logo by Anton Lovchikov + +**English** | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md) + +A tiny, secure, URL-friendly, unique string ID generator for JavaScript. + +> “An amazing level of senseless perfectionism, +> which is simply impossible not to respect.” + +* **Small.** 130 bytes (minified and gzipped). No dependencies. + [Size Limit] controls the size. +* **Fast.** It is 2 times faster than UUID. +* **Safe.** It uses hardware random generator. Can be used in clusters. +* **Short IDs.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`). + So ID size was reduced from 36 to 21 symbols. +* **Portable.** Nano ID was ported + to [20 programming languages](#other-programming-languages). + +```js +import { nanoid } from 'nanoid' +model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT" +``` + +Supports modern browsers, IE [with Babel], Node.js and React Native. + +[online tool]: https://gitpod.io/#https://github.com/ai/nanoid/ +[with Babel]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/ +[Size Limit]: https://github.com/ai/size-limit + + + Sponsored by Evil Martians + + +## Docs +Read full docs **[here](https://github.com/ai/nanoid#readme)**. diff --git a/node_modules/nanoid/async/index.browser.cjs b/node_modules/nanoid/async/index.browser.cjs new file mode 100644 index 0000000000000000000000000000000000000000..80d18716feaad2c0afca754745dda540d47bacec --- /dev/null +++ b/node_modules/nanoid/async/index.browser.cjs @@ -0,0 +1,69 @@ +let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes)) + +let customAlphabet = (alphabet, defaultSize = 21) => { + // First, a bitmask is necessary to generate the ID. The bitmask makes bytes + // values closer to the alphabet size. The bitmask calculates the closest + // `2^31 - 1` number, which exceeds the alphabet size. + // For example, the bitmask for the alphabet size 30 is 31 (00011111). + // `Math.clz32` is not used, because it is not available in browsers. + let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 + // Though, the bitmask solution is not perfect since the bytes exceeding + // the alphabet size are refused. Therefore, to reliably generate the ID, + // the random bytes redundancy has to be satisfied. + + // Note: every hardware random generator call is performance expensive, + // because the system call for entropy collection takes a lot of time. + // So, to avoid additional system calls, extra bytes are requested in advance. + + // Next, a step determines how many random bytes to generate. + // The number of random bytes gets decided upon the ID size, mask, + // alphabet size, and magic number 1.6 (using 1.6 peaks at performance + // according to benchmarks). + + // `-~f => Math.ceil(f)` if f is a float + // `-~i => i + 1` if i is an integer + let step = -~((1.6 * mask * defaultSize) / alphabet.length) + + return async (size = defaultSize) => { + let id = '' + while (true) { + let bytes = crypto.getRandomValues(new Uint8Array(step)) + // A compact alternative for `for (var i = 0; i < step; i++)`. + let i = step | 0 + while (i--) { + // Adding `|| ''` refuses a random byte that exceeds the alphabet size. + id += alphabet[bytes[i] & mask] || '' + if (id.length === size) return id + } + } + } +} + +let nanoid = async (size = 21) => { + let id = '' + let bytes = crypto.getRandomValues(new Uint8Array((size |= 0))) + + // A compact alternative for `for (var i = 0; i < step; i++)`. + while (size--) { + // It is incorrect to use bytes exceeding the alphabet size. + // The following mask reduces the random byte in the 0-255 value + // range to the 0-63 value range. Therefore, adding hacks, such + // as empty string fallback or magic numbers, is unneccessary because + // the bitmask trims bytes down to the alphabet size. + let byte = bytes[size] & 63 + if (byte < 36) { + // `0-9a-z` + id += byte.toString(36) + } else if (byte < 62) { + // `A-Z` + id += (byte - 26).toString(36).toUpperCase() + } else if (byte < 63) { + id += '_' + } else { + id += '-' + } + } + return id +} + +module.exports = { nanoid, customAlphabet, random } diff --git a/node_modules/nanoid/async/index.browser.js b/node_modules/nanoid/async/index.browser.js new file mode 100644 index 0000000000000000000000000000000000000000..fbaa23005cdf3cb9b1e8dada338ec2854df6e9fa --- /dev/null +++ b/node_modules/nanoid/async/index.browser.js @@ -0,0 +1,34 @@ +let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes)) +let customAlphabet = (alphabet, defaultSize = 21) => { + let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 + let step = -~((1.6 * mask * defaultSize) / alphabet.length) + return async (size = defaultSize) => { + let id = '' + while (true) { + let bytes = crypto.getRandomValues(new Uint8Array(step)) + let i = step | 0 + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length === size) return id + } + } + } +} +let nanoid = async (size = 21) => { + let id = '' + let bytes = crypto.getRandomValues(new Uint8Array((size |= 0))) + while (size--) { + let byte = bytes[size] & 63 + if (byte < 36) { + id += byte.toString(36) + } else if (byte < 62) { + id += (byte - 26).toString(36).toUpperCase() + } else if (byte < 63) { + id += '_' + } else { + id += '-' + } + } + return id +} +export { nanoid, customAlphabet, random } diff --git a/node_modules/nanoid/async/index.cjs b/node_modules/nanoid/async/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..f1b0ad0267aa71bc29b00e869276ab7bd51b4f32 --- /dev/null +++ b/node_modules/nanoid/async/index.cjs @@ -0,0 +1,71 @@ +let crypto = require('crypto') + +let { urlAlphabet } = require('../url-alphabet/index.cjs') + +// `crypto.randomFill()` is a little faster than `crypto.randomBytes()`, +// because it is possible to use in combination with `Buffer.allocUnsafe()`. +let random = bytes => + new Promise((resolve, reject) => { + // `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory. + // Memory flushing is unnecessary since the buffer allocation itself resets + // the memory with the new bytes. + crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => { + if (err) { + reject(err) + } else { + resolve(buf) + } + }) + }) + +let customAlphabet = (alphabet, defaultSize = 21) => { + // First, a bitmask is necessary to generate the ID. The bitmask makes bytes + // values closer to the alphabet size. The bitmask calculates the closest + // `2^31 - 1` number, which exceeds the alphabet size. + // For example, the bitmask for the alphabet size 30 is 31 (00011111). + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + // Though, the bitmask solution is not perfect since the bytes exceeding + // the alphabet size are refused. Therefore, to reliably generate the ID, + // the random bytes redundancy has to be satisfied. + + // Note: every hardware random generator call is performance expensive, + // because the system call for entropy collection takes a lot of time. + // So, to avoid additional system calls, extra bytes are requested in advance. + + // Next, a step determines how many random bytes to generate. + // The number of random bytes gets decided upon the ID size, mask, + // alphabet size, and magic number 1.6 (using 1.6 peaks at performance + // according to benchmarks). + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + + let tick = (id, size = defaultSize) => + random(step).then(bytes => { + // A compact alternative for `for (var i = 0; i < step; i++)`. + let i = step + while (i--) { + // Adding `|| ''` refuses a random byte that exceeds the alphabet size. + id += alphabet[bytes[i] & mask] || '' + if (id.length >= size) return id + } + return tick(id, size) + }) + + return size => tick('', size) +} + +let nanoid = (size = 21) => + random((size |= 0)).then(bytes => { + let id = '' + // A compact alternative for `for (var i = 0; i < step; i++)`. + while (size--) { + // It is incorrect to use bytes exceeding the alphabet size. + // The following mask reduces the random byte in the 0-255 value + // range to the 0-63 value range. Therefore, adding hacks, such + // as empty string fallback or magic numbers, is unneccessary because + // the bitmask trims bytes down to the alphabet size. + id += urlAlphabet[bytes[size] & 63] + } + return id + }) + +module.exports = { nanoid, customAlphabet, random } diff --git a/node_modules/nanoid/async/index.d.ts b/node_modules/nanoid/async/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e919658b82e66e3bd39800232da5a469c8d13a8 --- /dev/null +++ b/node_modules/nanoid/async/index.d.ts @@ -0,0 +1,56 @@ +/** + * Generate secure URL-friendly unique ID. The non-blocking version. + * + * By default, the ID will have 21 symbols to have a collision probability + * similar to UUID v4. + * + * ```js + * import { nanoid } from 'nanoid/async' + * nanoid().then(id => { + * model.id = id + * }) + * ``` + * + * @param size Size of the ID. The default size is 21. + * @returns A promise with a random string. + */ +export function nanoid(size?: number): Promise + +/** + * A low-level function. + * Generate secure unique ID with custom alphabet. The non-blocking version. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * @param alphabet Alphabet used to generate the ID. + * @param defaultSize Size of the ID. The default size is 21. + * @returns A function that returns a promise with a random string. + * + * ```js + * import { customAlphabet } from 'nanoid/async' + * const nanoid = customAlphabet('0123456789абвгдеё', 5) + * nanoid().then(id => { + * model.id = id //=> "8ё56а" + * }) + * ``` + */ +export function customAlphabet( + alphabet: string, + defaultSize?: number +): (size?: number) => Promise + +/** + * Generate an array of random bytes collected from hardware noise. + * + * ```js + * import { random } from 'nanoid/async' + * random(5).then(bytes => { + * bytes //=> [10, 67, 212, 67, 89] + * }) + * ``` + * + * @param bytes Size of the array. + * @returns A promise with a random bytes array. + */ +export function random(bytes: number): Promise diff --git a/node_modules/nanoid/async/index.js b/node_modules/nanoid/async/index.js new file mode 100644 index 0000000000000000000000000000000000000000..cec454a2a1986932acb22141113ec0c852a59f9b --- /dev/null +++ b/node_modules/nanoid/async/index.js @@ -0,0 +1,35 @@ +import crypto from 'crypto' +import { urlAlphabet } from '../url-alphabet/index.js' +let random = bytes => + new Promise((resolve, reject) => { + crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => { + if (err) { + reject(err) + } else { + resolve(buf) + } + }) + }) +let customAlphabet = (alphabet, defaultSize = 21) => { + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + let tick = (id, size = defaultSize) => + random(step).then(bytes => { + let i = step + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length >= size) return id + } + return tick(id, size) + }) + return size => tick('', size) +} +let nanoid = (size = 21) => + random((size |= 0)).then(bytes => { + let id = '' + while (size--) { + id += urlAlphabet[bytes[size] & 63] + } + return id + }) +export { nanoid, customAlphabet, random } diff --git a/node_modules/nanoid/async/index.native.js b/node_modules/nanoid/async/index.native.js new file mode 100644 index 0000000000000000000000000000000000000000..7c1d6f39e34d731715f551fa8a6c7520b04cda82 --- /dev/null +++ b/node_modules/nanoid/async/index.native.js @@ -0,0 +1,26 @@ +import { getRandomBytesAsync } from 'expo-random' +import { urlAlphabet } from '../url-alphabet/index.js' +let random = getRandomBytesAsync +let customAlphabet = (alphabet, defaultSize = 21) => { + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + let tick = (id, size = defaultSize) => + random(step).then(bytes => { + let i = step + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length >= size) return id + } + return tick(id, size) + }) + return size => tick('', size) +} +let nanoid = (size = 21) => + random((size |= 0)).then(bytes => { + let id = '' + while (size--) { + id += urlAlphabet[bytes[size] & 63] + } + return id + }) +export { nanoid, customAlphabet, random } diff --git a/node_modules/nanoid/async/package.json b/node_modules/nanoid/async/package.json new file mode 100644 index 0000000000000000000000000000000000000000..578cdb4cb9babb17e4e08b4f6a30c2e195d2afed --- /dev/null +++ b/node_modules/nanoid/async/package.json @@ -0,0 +1,12 @@ +{ + "type": "module", + "main": "index.cjs", + "module": "index.js", + "react-native": { + "./index.js": "./index.native.js" + }, + "browser": { + "./index.js": "./index.browser.js", + "./index.cjs": "./index.browser.cjs" + } +} \ No newline at end of file diff --git a/node_modules/nanoid/bin/nanoid.cjs b/node_modules/nanoid/bin/nanoid.cjs new file mode 100644 index 0000000000000000000000000000000000000000..c76db0faa81f6d683c4a18a212f804fb70cf8143 --- /dev/null +++ b/node_modules/nanoid/bin/nanoid.cjs @@ -0,0 +1,55 @@ +#!/usr/bin/env node + +let { nanoid, customAlphabet } = require('..') + +function print(msg) { + process.stdout.write(msg + '\n') +} + +function error(msg) { + process.stderr.write(msg + '\n') + process.exit(1) +} + +if (process.argv.includes('--help') || process.argv.includes('-h')) { + print(` + Usage + $ nanoid [options] + + Options + -s, --size Generated ID size + -a, --alphabet Alphabet to use + -h, --help Show this help + + Examples + $ nanoid --s 15 + S9sBF77U6sDB8Yg + + $ nanoid --size 10 --alphabet abc + bcabababca`) + process.exit() +} + +let alphabet, size +for (let i = 2; i < process.argv.length; i++) { + let arg = process.argv[i] + if (arg === '--size' || arg === '-s') { + size = Number(process.argv[i + 1]) + i += 1 + if (Number.isNaN(size) || size <= 0) { + error('Size must be positive integer') + } + } else if (arg === '--alphabet' || arg === '-a') { + alphabet = process.argv[i + 1] + i += 1 + } else { + error('Unknown argument ' + arg) + } +} + +if (alphabet) { + let customNanoid = customAlphabet(alphabet, size) + print(customNanoid()) +} else { + print(nanoid(size)) +} diff --git a/node_modules/nanoid/index.browser.cjs b/node_modules/nanoid/index.browser.cjs new file mode 100644 index 0000000000000000000000000000000000000000..d21a91fcf3d4fb63515c79b3a47f0433c3ca1e4b --- /dev/null +++ b/node_modules/nanoid/index.browser.cjs @@ -0,0 +1,72 @@ +// This file replaces `index.js` in bundlers like webpack or Rollup, +// according to `browser` config in `package.json`. + +let { urlAlphabet } = require('./url-alphabet/index.cjs') + +let random = bytes => crypto.getRandomValues(new Uint8Array(bytes)) + +let customRandom = (alphabet, defaultSize, getRandom) => { + // First, a bitmask is necessary to generate the ID. The bitmask makes bytes + // values closer to the alphabet size. The bitmask calculates the closest + // `2^31 - 1` number, which exceeds the alphabet size. + // For example, the bitmask for the alphabet size 30 is 31 (00011111). + // `Math.clz32` is not used, because it is not available in browsers. + let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 + // Though, the bitmask solution is not perfect since the bytes exceeding + // the alphabet size are refused. Therefore, to reliably generate the ID, + // the random bytes redundancy has to be satisfied. + + // Note: every hardware random generator call is performance expensive, + // because the system call for entropy collection takes a lot of time. + // So, to avoid additional system calls, extra bytes are requested in advance. + + // Next, a step determines how many random bytes to generate. + // The number of random bytes gets decided upon the ID size, mask, + // alphabet size, and magic number 1.6 (using 1.6 peaks at performance + // according to benchmarks). + + // `-~f => Math.ceil(f)` if f is a float + // `-~i => i + 1` if i is an integer + let step = -~((1.6 * mask * defaultSize) / alphabet.length) + + return (size = defaultSize) => { + let id = '' + while (true) { + let bytes = getRandom(step) + // A compact alternative for `for (var i = 0; i < step; i++)`. + let j = step | 0 + while (j--) { + // Adding `|| ''` refuses a random byte that exceeds the alphabet size. + id += alphabet[bytes[j] & mask] || '' + if (id.length === size) return id + } + } + } +} + +let customAlphabet = (alphabet, size = 21) => + customRandom(alphabet, size, random) + +let nanoid = (size = 21) => + crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => { + // It is incorrect to use bytes exceeding the alphabet size. + // The following mask reduces the random byte in the 0-255 value + // range to the 0-63 value range. Therefore, adding hacks, such + // as empty string fallback or magic numbers, is unneccessary because + // the bitmask trims bytes down to the alphabet size. + byte &= 63 + if (byte < 36) { + // `0-9a-z` + id += byte.toString(36) + } else if (byte < 62) { + // `A-Z` + id += (byte - 26).toString(36).toUpperCase() + } else if (byte > 62) { + id += '-' + } else { + id += '_' + } + return id + }, '') + +module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/nanoid/index.browser.js b/node_modules/nanoid/index.browser.js new file mode 100644 index 0000000000000000000000000000000000000000..7d3b876caefe8df0d4856199d0de5ff1ddf45cae --- /dev/null +++ b/node_modules/nanoid/index.browser.js @@ -0,0 +1,34 @@ +import { urlAlphabet } from './url-alphabet/index.js' +let random = bytes => crypto.getRandomValues(new Uint8Array(bytes)) +let customRandom = (alphabet, defaultSize, getRandom) => { + let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 + let step = -~((1.6 * mask * defaultSize) / alphabet.length) + return (size = defaultSize) => { + let id = '' + while (true) { + let bytes = getRandom(step) + let j = step | 0 + while (j--) { + id += alphabet[bytes[j] & mask] || '' + if (id.length === size) return id + } + } + } +} +let customAlphabet = (alphabet, size = 21) => + customRandom(alphabet, size, random) +let nanoid = (size = 21) => + crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => { + byte &= 63 + if (byte < 36) { + id += byte.toString(36) + } else if (byte < 62) { + id += (byte - 26).toString(36).toUpperCase() + } else if (byte > 62) { + id += '-' + } else { + id += '_' + } + return id + }, '') +export { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/nanoid/index.cjs b/node_modules/nanoid/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..c20e3744d255e86a49081aea08c2e65bed1decb7 --- /dev/null +++ b/node_modules/nanoid/index.cjs @@ -0,0 +1,85 @@ +let crypto = require('crypto') + +let { urlAlphabet } = require('./url-alphabet/index.cjs') + +// It is best to make fewer, larger requests to the crypto module to +// avoid system call overhead. So, random numbers are generated in a +// pool. The pool is a Buffer that is larger than the initial random +// request size by this multiplier. The pool is enlarged if subsequent +// requests exceed the maximum buffer size. +const POOL_SIZE_MULTIPLIER = 128 +let pool, poolOffset + +let fillPool = bytes => { + if (!pool || pool.length < bytes) { + pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER) + crypto.randomFillSync(pool) + poolOffset = 0 + } else if (poolOffset + bytes > pool.length) { + crypto.randomFillSync(pool) + poolOffset = 0 + } + poolOffset += bytes +} + +let random = bytes => { + // `|=` convert `bytes` to number to prevent `valueOf` abusing and pool pollution + fillPool((bytes |= 0)) + return pool.subarray(poolOffset - bytes, poolOffset) +} + +let customRandom = (alphabet, defaultSize, getRandom) => { + // First, a bitmask is necessary to generate the ID. The bitmask makes bytes + // values closer to the alphabet size. The bitmask calculates the closest + // `2^31 - 1` number, which exceeds the alphabet size. + // For example, the bitmask for the alphabet size 30 is 31 (00011111). + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + // Though, the bitmask solution is not perfect since the bytes exceeding + // the alphabet size are refused. Therefore, to reliably generate the ID, + // the random bytes redundancy has to be satisfied. + + // Note: every hardware random generator call is performance expensive, + // because the system call for entropy collection takes a lot of time. + // So, to avoid additional system calls, extra bytes are requested in advance. + + // Next, a step determines how many random bytes to generate. + // The number of random bytes gets decided upon the ID size, mask, + // alphabet size, and magic number 1.6 (using 1.6 peaks at performance + // according to benchmarks). + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + + return (size = defaultSize) => { + let id = '' + while (true) { + let bytes = getRandom(step) + // A compact alternative for `for (let i = 0; i < step; i++)`. + let i = step + while (i--) { + // Adding `|| ''` refuses a random byte that exceeds the alphabet size. + id += alphabet[bytes[i] & mask] || '' + if (id.length === size) return id + } + } + } +} + +let customAlphabet = (alphabet, size = 21) => + customRandom(alphabet, size, random) + +let nanoid = (size = 21) => { + // `|=` convert `size` to number to prevent `valueOf` abusing and pool pollution + fillPool((size |= 0)) + let id = '' + // We are reading directly from the random pool to avoid creating new array + for (let i = poolOffset - size; i < poolOffset; i++) { + // It is incorrect to use bytes exceeding the alphabet size. + // The following mask reduces the random byte in the 0-255 value + // range to the 0-63 value range. Therefore, adding hacks, such + // as empty string fallback or magic numbers, is unneccessary because + // the bitmask trims bytes down to the alphabet size. + id += urlAlphabet[pool[i] & 63] + } + return id +} + +module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/nanoid/index.d.cts b/node_modules/nanoid/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..3e111a39de010f548d397f06f8f964191834b869 --- /dev/null +++ b/node_modules/nanoid/index.d.cts @@ -0,0 +1,91 @@ +/** + * Generate secure URL-friendly unique ID. + * + * By default, the ID will have 21 symbols to have a collision probability + * similar to UUID v4. + * + * ```js + * import { nanoid } from 'nanoid' + * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" + * ``` + * + * @param size Size of the ID. The default size is 21. + * @returns A random string. + */ +export function nanoid(size?: number): string + +/** + * Generate secure unique ID with custom alphabet. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * @param alphabet Alphabet used to generate the ID. + * @param defaultSize Size of the ID. The default size is 21. + * @returns A random string generator. + * + * ```js + * const { customAlphabet } = require('nanoid') + * const nanoid = customAlphabet('0123456789абвгдеё', 5) + * nanoid() //=> "8ё56а" + * ``` + */ +export function customAlphabet( + alphabet: string, + defaultSize?: number +): (size?: number) => string + +/** + * Generate unique ID with custom random generator and alphabet. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * ```js + * import { customRandom } from 'nanoid/format' + * + * const nanoid = customRandom('abcdef', 5, size => { + * const random = [] + * for (let i = 0; i < size; i++) { + * random.push(randomByte()) + * } + * return random + * }) + * + * nanoid() //=> "fbaef" + * ``` + * + * @param alphabet Alphabet used to generate a random string. + * @param size Size of the random string. + * @param random A random bytes generator. + * @returns A random string generator. + */ +export function customRandom( + alphabet: string, + size: number, + random: (bytes: number) => Uint8Array +): () => string + +/** + * URL safe symbols. + * + * ```js + * import { urlAlphabet } from 'nanoid' + * const nanoid = customAlphabet(urlAlphabet, 10) + * nanoid() //=> "Uakgb_J5m9" + * ``` + */ +export const urlAlphabet: string + +/** + * Generate an array of random bytes collected from hardware noise. + * + * ```js + * import { customRandom, random } from 'nanoid' + * const nanoid = customRandom("abcdef", 5, random) + * ``` + * + * @param bytes Size of the array. + * @returns An array of random bytes. + */ +export function random(bytes: number): Uint8Array diff --git a/node_modules/nanoid/index.d.ts b/node_modules/nanoid/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e111a39de010f548d397f06f8f964191834b869 --- /dev/null +++ b/node_modules/nanoid/index.d.ts @@ -0,0 +1,91 @@ +/** + * Generate secure URL-friendly unique ID. + * + * By default, the ID will have 21 symbols to have a collision probability + * similar to UUID v4. + * + * ```js + * import { nanoid } from 'nanoid' + * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" + * ``` + * + * @param size Size of the ID. The default size is 21. + * @returns A random string. + */ +export function nanoid(size?: number): string + +/** + * Generate secure unique ID with custom alphabet. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * @param alphabet Alphabet used to generate the ID. + * @param defaultSize Size of the ID. The default size is 21. + * @returns A random string generator. + * + * ```js + * const { customAlphabet } = require('nanoid') + * const nanoid = customAlphabet('0123456789абвгдеё', 5) + * nanoid() //=> "8ё56а" + * ``` + */ +export function customAlphabet( + alphabet: string, + defaultSize?: number +): (size?: number) => string + +/** + * Generate unique ID with custom random generator and alphabet. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * ```js + * import { customRandom } from 'nanoid/format' + * + * const nanoid = customRandom('abcdef', 5, size => { + * const random = [] + * for (let i = 0; i < size; i++) { + * random.push(randomByte()) + * } + * return random + * }) + * + * nanoid() //=> "fbaef" + * ``` + * + * @param alphabet Alphabet used to generate a random string. + * @param size Size of the random string. + * @param random A random bytes generator. + * @returns A random string generator. + */ +export function customRandom( + alphabet: string, + size: number, + random: (bytes: number) => Uint8Array +): () => string + +/** + * URL safe symbols. + * + * ```js + * import { urlAlphabet } from 'nanoid' + * const nanoid = customAlphabet(urlAlphabet, 10) + * nanoid() //=> "Uakgb_J5m9" + * ``` + */ +export const urlAlphabet: string + +/** + * Generate an array of random bytes collected from hardware noise. + * + * ```js + * import { customRandom, random } from 'nanoid' + * const nanoid = customRandom("abcdef", 5, random) + * ``` + * + * @param bytes Size of the array. + * @returns An array of random bytes. + */ +export function random(bytes: number): Uint8Array diff --git a/node_modules/nanoid/index.js b/node_modules/nanoid/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9bc909d90c9b6c56c14e7e9fadbfc7fb0a0cd9ba --- /dev/null +++ b/node_modules/nanoid/index.js @@ -0,0 +1,45 @@ +import crypto from 'crypto' +import { urlAlphabet } from './url-alphabet/index.js' +const POOL_SIZE_MULTIPLIER = 128 +let pool, poolOffset +let fillPool = bytes => { + if (!pool || pool.length < bytes) { + pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER) + crypto.randomFillSync(pool) + poolOffset = 0 + } else if (poolOffset + bytes > pool.length) { + crypto.randomFillSync(pool) + poolOffset = 0 + } + poolOffset += bytes +} +let random = bytes => { + fillPool((bytes |= 0)) + return pool.subarray(poolOffset - bytes, poolOffset) +} +let customRandom = (alphabet, defaultSize, getRandom) => { + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + return (size = defaultSize) => { + let id = '' + while (true) { + let bytes = getRandom(step) + let i = step + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length === size) return id + } + } + } +} +let customAlphabet = (alphabet, size = 21) => + customRandom(alphabet, size, random) +let nanoid = (size = 21) => { + fillPool((size |= 0)) + let id = '' + for (let i = poolOffset - size; i < poolOffset; i++) { + id += urlAlphabet[pool[i] & 63] + } + return id +} +export { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/nanoid/nanoid.js b/node_modules/nanoid/nanoid.js new file mode 100644 index 0000000000000000000000000000000000000000..ec242eadc85e4b0ef546c8fdc771f7e9d7d2f081 --- /dev/null +++ b/node_modules/nanoid/nanoid.js @@ -0,0 +1 @@ +export let nanoid=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce(((t,e)=>t+=(e&=63)<36?e.toString(36):e<62?(e-26).toString(36).toUpperCase():e<63?"_":"-"),""); \ No newline at end of file diff --git a/node_modules/nanoid/non-secure/index.cjs b/node_modules/nanoid/non-secure/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..d51fcb6cedb809967ece5cc568f658245fe95f58 --- /dev/null +++ b/node_modules/nanoid/non-secure/index.cjs @@ -0,0 +1,34 @@ +// This alphabet uses `A-Za-z0-9_-` symbols. +// The order of characters is optimized for better gzip and brotli compression. +// References to the same file (works both for gzip and brotli): +// `'use`, `andom`, and `rict'` +// References to the brotli default dictionary: +// `-26T`, `1983`, `40px`, `75px`, `bush`, `jack`, `mind`, `very`, and `wolf` +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' + +let customAlphabet = (alphabet, defaultSize = 21) => { + return (size = defaultSize) => { + let id = '' + // A compact alternative for `for (var i = 0; i < step; i++)`. + let i = size | 0 + while (i--) { + // `| 0` is more compact and faster than `Math.floor()`. + id += alphabet[(Math.random() * alphabet.length) | 0] + } + return id + } +} + +let nanoid = (size = 21) => { + let id = '' + // A compact alternative for `for (var i = 0; i < step; i++)`. + let i = size | 0 + while (i--) { + // `| 0` is more compact and faster than `Math.floor()`. + id += urlAlphabet[(Math.random() * 64) | 0] + } + return id +} + +module.exports = { nanoid, customAlphabet } diff --git a/node_modules/nanoid/non-secure/index.d.ts b/node_modules/nanoid/non-secure/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4965322d636016d678fccdd94c3aacdf1fc50075 --- /dev/null +++ b/node_modules/nanoid/non-secure/index.d.ts @@ -0,0 +1,33 @@ +/** + * Generate URL-friendly unique ID. This method uses the non-secure + * predictable random generator with bigger collision probability. + * + * ```js + * import { nanoid } from 'nanoid/non-secure' + * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" + * ``` + * + * @param size Size of the ID. The default size is 21. + * @returns A random string. + */ +export function nanoid(size?: number): string + +/** + * Generate a unique ID based on a custom alphabet. + * This method uses the non-secure predictable random generator + * with bigger collision probability. + * + * @param alphabet Alphabet used to generate the ID. + * @param defaultSize Size of the ID. The default size is 21. + * @returns A random string generator. + * + * ```js + * import { customAlphabet } from 'nanoid/non-secure' + * const nanoid = customAlphabet('0123456789абвгдеё', 5) + * model.id = //=> "8ё56а" + * ``` + */ +export function customAlphabet( + alphabet: string, + defaultSize?: number +): (size?: number) => string diff --git a/node_modules/nanoid/non-secure/index.js b/node_modules/nanoid/non-secure/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2ea5827c627331d5d7a2e38e0acca3b9824a668d --- /dev/null +++ b/node_modules/nanoid/non-secure/index.js @@ -0,0 +1,21 @@ +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' +let customAlphabet = (alphabet, defaultSize = 21) => { + return (size = defaultSize) => { + let id = '' + let i = size | 0 + while (i--) { + id += alphabet[(Math.random() * alphabet.length) | 0] + } + return id + } +} +let nanoid = (size = 21) => { + let id = '' + let i = size | 0 + while (i--) { + id += urlAlphabet[(Math.random() * 64) | 0] + } + return id +} +export { nanoid, customAlphabet } diff --git a/node_modules/nanoid/non-secure/package.json b/node_modules/nanoid/non-secure/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9930d6ad1671e19bfddbdeeb9bbcdeab83dc00ba --- /dev/null +++ b/node_modules/nanoid/non-secure/package.json @@ -0,0 +1,6 @@ +{ + "type": "module", + "main": "index.cjs", + "module": "index.js", + "react-native": "index.js" +} \ No newline at end of file diff --git a/node_modules/nanoid/package.json b/node_modules/nanoid/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a3d3f445260bd2c0364de42401465f1bf01cf6b6 --- /dev/null +++ b/node_modules/nanoid/package.json @@ -0,0 +1,89 @@ +{ + "name": "nanoid", + "version": "3.3.11", + "description": "A tiny (116 bytes), secure URL-friendly unique string ID generator", + "keywords": [ + "uuid", + "random", + "id", + "url" + ], + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "author": "Andrey Sitnik ", + "license": "MIT", + "repository": "ai/nanoid", + "browser": { + "./index.js": "./index.browser.js", + "./async/index.js": "./async/index.browser.js", + "./async/index.cjs": "./async/index.browser.cjs", + "./index.cjs": "./index.browser.cjs" + }, + "react-native": "index.js", + "bin": "./bin/nanoid.cjs", + "sideEffects": false, + "types": "./index.d.ts", + "type": "module", + "main": "index.cjs", + "module": "index.js", + "exports": { + ".": { + "react-native": "./index.browser.js", + "browser": "./index.browser.js", + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + }, + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "default": "./index.js" + }, + "./package.json": "./package.json", + "./async/package.json": "./async/package.json", + "./async": { + "browser": "./async/index.browser.js", + "require": { + "types": "./index.d.cts", + "default": "./async/index.cjs" + }, + "import": { + "types": "./index.d.ts", + "default": "./async/index.js" + }, + "default": "./async/index.js" + }, + "./non-secure/package.json": "./non-secure/package.json", + "./non-secure": { + "require": { + "types": "./index.d.cts", + "default": "./non-secure/index.cjs" + }, + "import": { + "types": "./index.d.ts", + "default": "./non-secure/index.js" + }, + "default": "./non-secure/index.js" + }, + "./url-alphabet/package.json": "./url-alphabet/package.json", + "./url-alphabet": { + "require": { + "types": "./index.d.cts", + "default": "./url-alphabet/index.cjs" + }, + "import": { + "types": "./index.d.ts", + "default": "./url-alphabet/index.js" + }, + "default": "./url-alphabet/index.js" + } + } +} diff --git a/node_modules/nanoid/url-alphabet/index.cjs b/node_modules/nanoid/url-alphabet/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..a332f0bff69ed88326a611860a8e5a8cdb881dc4 --- /dev/null +++ b/node_modules/nanoid/url-alphabet/index.cjs @@ -0,0 +1,7 @@ +// This alphabet uses `A-Za-z0-9_-` symbols. +// The order of characters is optimized for better gzip and brotli compression. +// Same as in non-secure/index.js +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' + +module.exports = { urlAlphabet } diff --git a/node_modules/nanoid/url-alphabet/index.js b/node_modules/nanoid/url-alphabet/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c2782e592e541a8ec8bd07038e997e63a16beb70 --- /dev/null +++ b/node_modules/nanoid/url-alphabet/index.js @@ -0,0 +1,3 @@ +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' +export { urlAlphabet } diff --git a/node_modules/nanoid/url-alphabet/package.json b/node_modules/nanoid/url-alphabet/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9930d6ad1671e19bfddbdeeb9bbcdeab83dc00ba --- /dev/null +++ b/node_modules/nanoid/url-alphabet/package.json @@ -0,0 +1,6 @@ +{ + "type": "module", + "main": "index.cjs", + "module": "index.js", + "react-native": "index.js" +} \ No newline at end of file diff --git a/node_modules/native-promise-only/.npmignore b/node_modules/native-promise-only/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..859204df5e865b00a1c965668448d3b8ebc68c21 --- /dev/null +++ b/node_modules/native-promise-only/.npmignore @@ -0,0 +1,2 @@ +node_modules +.gitignore diff --git a/node_modules/native-promise-only/README.md b/node_modules/native-promise-only/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4530347b73744636ce3d1ee1fc432fda1fac45dd --- /dev/null +++ b/node_modules/native-promise-only/README.md @@ -0,0 +1,137 @@ +# Native Promise Only (NPO) + +A polyfill for native ES6 Promises as close as possible (no extensions) to the strict spec definitions. + +## Intent + +The aim of this project is to be the smallest polyfill for Promises, staying as close as possible to what's specified in both [Promises/A+](http://promisesaplus.com) and the [upcoming ES6 specification](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-objects). + +An equally important goal is to avoid exposing any capability for promise-state to be mutated externally. The [Known Limitations](#known-limitations) section below explains the trade-offs of that balance. + +## Usage + +To use this polyfill in the browser, include the "npo.js" file (see the instructions in [Tests/Compliance section](#testscompliance) below for how to build "npo.js" if you don't have it already) with your site's scripts. It's a polyfill, which means it will not overwrite `Promise` if it exists as a global already, so it's safe to include unconditionally. + +To use with AMD, import the "npo.js" file module. + +To install the polyfill via bower, run: + +``` +bower install native-promise-only +``` + +To install the polyfill via npm, run: + +``` +npm install native-promise-only +``` + +Then require the module into your node code: + +```js +require("native-promise-only"); +``` + +Notice that using the module in this way, we don't assign the module's public API to any variable. **We don't need to**, because it's a polyfill that intentionally patches the global environment (in this case to the `Promise` name) once included. + +If you *want* to also have a reference pointing to the same `Promise` global, you *can also* assign the return value from the `require(..)` statement, but it's strongly recommended that you use the same `Promise` name so as to not create confusion: + +```js +var Promise = require("native-promise-only"); + +// Promise === global.Promise; // true! +``` + +Other than the below [Known Limitations](#known-limitations) discussion and some browser bugs (such as [these](https://gist.github.com/getify/bd11ccf1eff2efdac0fb)) which **this polyfill doesn't suffer from**, your promises should operate the same in all JS environments. + +Exactly like native promises, here's a quick example of how you create and use the polyfilled promises: + +```js +var p = new Promise(function(resolve,reject){ + setTimeout(function(){ + resolve("Yay!"); + },100); +}); + +p.then(function(msg){ + console.log(msg); // Yay! +}); +``` + +For more on promises, check these blog posts out: + +1. Back-story on the hows and whys behind promises (chaining, errors, etc): [multi-part blog post series "Promises"](http://blog.getify.com/promises-part-1/) by [getify](http://twitter.com/getify) (me). +2. Using and enjoying native promises: [JavaScript Promises](http://www.html5rocks.com/en/tutorials/es6/promises/) by [Jake Archibald](http://twitter.com/jaffathecake). + +## Known Limitations + +A promise object from this polyfill **will be** an instance of the `Promise` constructor, which makes identification of genuine promises easier: + +```js +var p = new Promise(..); + +p instanceof Promise; // true +``` + +However, these promise instances don't inherit (delegate to) a *meaningful* `Promise.prototype` object for their methods (there is one, it's just mostly empty). + +Consider: + +```js +var p = new Promise(..); + +Object.getOwnPropertyNames( p ); // [ then, catch ] +Object.getOwnPropertyNames( Promise.prototype ); // [ constructor ] +``` + +As such, these promises are not really "sub-classable" in the ES6 `class` / `extends` sense, though theoretically you should be able to do that in ES6 with the built-in Promises. + +To read a full explanation of why, read [Part 3: The Trust Problem](http://blog.getify.com/promises-part-3/) of my blog post series on Promises. + +Briefly, the reason for this deviation is that there's a choice between having delegated methods on the `.prototype` or having private state. Since **the spirit of promises was always to ensure trustability** -- that promises were immutable (from the outside) to everyone except the initial resolver/deferred -- private state is a critically important feature to preserve. + +Many other ES6 promise shims/libs seem to have forgotten that important point, as many of them either expose the state publicly on the object instance or provide public accessor methods which can externally mutate a promise's state. Both of these deviations are **intolerable** in my opinion, so this library chose the opposite trade-off: *no ES6 sub-classing*. + +Any trade-off is a shame, but this one is the least of a few evils, and probably won't prove to limit very many, as there are only a limited number of use-cases for `extend`ing `Promise` in the ES6 sub-class sense. + +## Still Want More? + +This project intentionally adheres pretty strictly to the narrow core of [Promises/A+](http://promisesaplus.com) as adopted/implemented by ES6 into the native `Promise()` mechanism. + +But it's quite likely that you will [experience a variety of scenarios](http://blog.getify.com/promises-part-5/) in which using *only* native promises might be tedious, limiting, or more trouble than it's worth. There's good reason why most other **Promises/A+** "compliant" libs are actually superset extensions on the narrow core: **because async flow-control is often quite complex in the real world.** + +*Native Promise Only* will **NOT** add any of these extra flourishes. Sorry. + +**However, I have another project**: [asynquence](http://github.com/getify/asynquence) (async + sequence). It's an abstraction on top of the promises concept (promises are hidden inside), designed to drastically improve the readability and expressiveness of your async flow-control code. + +You simply express your async flow-control and *asynquence* creates and chains all the promises for you underneath. **Super simple.** + +*asynquence* has a custom implementation for the internal "promises" it uses, and as such does not need native `Promises`, nor does it need/include this polyfill. + +Get your feet wet with native promises first, but then when you go looking for something more, consider [asynquence](http://github.com/getify/asynquence) (which is [vastly more powerful](http://davidwalsh.name/asynquence-part-1) and is still only ~2k!). + +## Tests/Compliance + + + Promises/A+ logo + + +*Native Promise Only* is "spec compliant" in the sense of passing all tests in the [Promises/A+ Test Suite](https://github.com/promises-aplus/promises-tests). + +To run all tests: + +1. Either git-clone this repo or run `npm install native-promise-only`, and then switch into that project root. +2. Run `npm install` in the project root to install the dev-dependencies. +3. If you didn't get *native-promise-only* from npm, then from the project root, run `./build.js` or `node build.js` or `npm run build` to generate the minified "npo.js" in the project root. +4. Finally, run `npm test`. + +**Note:** Other tests need to be added, such as testing the `Promise()` constructor's behavior, as well as the `Promise.*` static helpers (`resolve(..)`, `reject(..)`, `all(..)`, and `race(..)`), none of which are covered by the Promises/A+ test suite. + +Developing a more comprehensive test-suite to augment the Promises/A+ test suite **is now another primary goal** of this project. + +## License + +The code and all the documentation are released under the MIT license. + +http://getify.mit-license.org/ diff --git a/node_modules/native-promise-only/build.js b/node_modules/native-promise-only/build.js new file mode 100644 index 0000000000000000000000000000000000000000..7cf2ad9e3e7cd0036a25eaa8c539cf089b3a4958 --- /dev/null +++ b/node_modules/native-promise-only/build.js @@ -0,0 +1,34 @@ +#!/usr/bin/env node + +var fs = require("fs"), + path = require("path"), + exec = require("child_process").exec, + ugly = require("uglify-js"), + + result +; + +console.log("*** Building ***"); +console.log("Minifying to npo.js."); + +try { + result = ugly.minify(path.join(__dirname,"lib","npo.src.js"),{ + mangle: true, + compress: true, + output: { + comments: /^!/ + } + }); + + fs.writeFileSync( + path.join(__dirname,"npo.js"), + result.code + "\n", + { encoding: "utf8" } + ); + + console.log("Complete."); +} +catch (err) { + console.error(err); + process.exit(1); +} diff --git a/node_modules/native-promise-only/lib/npo.src.js b/node_modules/native-promise-only/lib/npo.src.js new file mode 100644 index 0000000000000000000000000000000000000000..50e24ae6c842b1c9ce3f0e00ee80287e48179011 --- /dev/null +++ b/node_modules/native-promise-only/lib/npo.src.js @@ -0,0 +1,373 @@ +/*! Native Promise Only + v0.8.1 (c) Kyle Simpson + MIT License: http://getify.mit-license.org +*/ + +(function UMD(name,context,definition){ + // special form of UMD for polyfilling across evironments + context[name] = context[name] || definition(); + if (typeof module != "undefined" && module.exports) { module.exports = context[name]; } + else if (typeof define == "function" && define.amd) { define(function $AMD$(){ return context[name]; }); } +})("Promise",typeof global != "undefined" ? global : this,function DEF(){ + /*jshint validthis:true */ + "use strict"; + + var builtInProp, cycle, scheduling_queue, + ToString = Object.prototype.toString, + timer = (typeof setImmediate != "undefined") ? + function timer(fn) { return setImmediate(fn); } : + setTimeout + ; + + // dammit, IE8. + try { + Object.defineProperty({},"x",{}); + builtInProp = function builtInProp(obj,name,val,config) { + return Object.defineProperty(obj,name,{ + value: val, + writable: true, + configurable: config !== false + }); + }; + } + catch (err) { + builtInProp = function builtInProp(obj,name,val) { + obj[name] = val; + return obj; + }; + } + + // Note: using a queue instead of array for efficiency + scheduling_queue = (function Queue() { + var first, last, item; + + function Item(fn,self) { + this.fn = fn; + this.self = self; + this.next = void 0; + } + + return { + add: function add(fn,self) { + item = new Item(fn,self); + if (last) { + last.next = item; + } + else { + first = item; + } + last = item; + item = void 0; + }, + drain: function drain() { + var f = first; + first = last = cycle = void 0; + + while (f) { + f.fn.call(f.self); + f = f.next; + } + } + }; + })(); + + function schedule(fn,self) { + scheduling_queue.add(fn,self); + if (!cycle) { + cycle = timer(scheduling_queue.drain); + } + } + + // promise duck typing + function isThenable(o) { + var _then, o_type = typeof o; + + if (o != null && + ( + o_type == "object" || o_type == "function" + ) + ) { + _then = o.then; + } + return typeof _then == "function" ? _then : false; + } + + function notify() { + for (var i=0; i 0) { + schedule(notify,self); + } + } + } + catch (err) { + reject.call(new MakeDefWrapper(self),err); + } + } + + function reject(msg) { + var self = this; + + // already triggered? + if (self.triggered) { return; } + + self.triggered = true; + + // unwrap + if (self.def) { + self = self.def; + } + + self.msg = msg; + self.state = 2; + if (self.chain.length > 0) { + schedule(notify,self); + } + } + + function iteratePromises(Constructor,arr,resolver,rejecter) { + for (var idx=0; idx0&&t(e,u))}catch(a){i.call(new f(u),a)}}}function i(n){var o=this;o.triggered||(o.triggered=!0,o.def&&(o=o.def),o.msg=n,o.state=2,o.chain.length>0&&t(e,o))}function c(t,n,e,o){for(var r=0;r", + "license": "MIT" +} diff --git a/node_modules/native-promise-only/test_adapter.js b/node_modules/native-promise-only/test_adapter.js new file mode 100644 index 0000000000000000000000000000000000000000..ece6b8e3ea7ff9fd365c64b7a81db6d37f5daadd --- /dev/null +++ b/node_modules/native-promise-only/test_adapter.js @@ -0,0 +1,21 @@ +// Adapter for "promises-aplus-tests" test runner + +var path = require("path"); +var Promise = require(path.join(__dirname,"lib","npo.src.js")); + +module.exports.deferred = function __deferred__() { + var o = {}; + o.promise = new Promise(function __Promise__(resolve,reject){ + o.resolve = resolve; + o.reject = reject; + }); + return o; +}; + +module.exports.resolved = function __resolved__(val) { + return Promise.resolve(val); +}; + +module.exports.rejected = function __rejected__(reason) { + return Promise.reject(reason); +}; diff --git a/node_modules/needle/.github/workflows/nodejs.yml b/node_modules/needle/.github/workflows/nodejs.yml new file mode 100644 index 0000000000000000000000000000000000000000..7b255974eef988f390493708f013c0232c49c949 --- /dev/null +++ b/node_modules/needle/.github/workflows/nodejs.yml @@ -0,0 +1,27 @@ +name: Node CI +on: [push] + +jobs: + build: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [4.x, 6.x, 8.x, 10.x, 12.x] + + steps: + - uses: actions/checkout@v1 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: npm install, build, and test + run: | + npm install + mkdir -p test/keys + openssl genrsa -out test/keys/ssl.key 2048 + openssl req -new -key test/keys/ssl.key -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -x509 -days 999 -out test/keys/ssl.cert + npm run build --if-present + npm test + env: + CI: true diff --git a/node_modules/needle/README.md b/node_modules/needle/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b9689f9dc81fc56d571a34f88c6ed855eb92cda9 --- /dev/null +++ b/node_modules/needle/README.md @@ -0,0 +1,612 @@ +Needle +====== + +[![NPM](https://nodei.co/npm/needle.png)](https://nodei.co/npm/needle/) + +The leanest and most handsome HTTP client in the Nodelands. + +```js +var needle = require('needle'); + +needle.get('http://www.google.com', function(error, response) { + if (!error && response.statusCode == 200) + console.log(response.body); +}); +``` + +Callbacks not floating your boat? Needle got your back. + +``` js +var data = { + file: '/home/johnlennon/walrus.png', + content_type: 'image/png' +}; + +// the callback is optional, and needle returns a `readableStream` object +// that triggers a 'done' event when the request/response process is complete. +needle + .post('https://my.server.com/foo', data, { multipart: true }) + .on('readable', function() { /* eat your chunks */ }) + .on('done', function(err) { + console.log('Ready-o!'); + }) +``` + +From version 2.0.x up, Promises are also supported. Just call `needle()` directly and you'll get a native Promise object. + +```js +needle('put', 'https://hacking.the.gibson/login', { password: 'god' }, { json: true }) + .then(function(response) { + return doSomethingWith(response) + }) + .catch(function(err) { + console.log('Call the locksmith!') + }) +``` + +With only two real dependencies, Needle supports: + + - HTTP/HTTPS requests, with the usual verbs you would expect + - All of Node's native TLS options, such as 'rejectUnauthorized' (see below) + - Basic & Digest authentication with auto-detection + - Multipart form-data (e.g. file uploads) + - HTTP Proxy forwarding, optionally with authentication + - Streaming gzip, deflate, and brotli decompression + - Automatic XML & JSON parsing + - 301/302/303 redirect following, with fine-grained tuning, and + - Streaming non-UTF-8 charset decoding, via `iconv-lite` + +And yes, Mr. Wayne, it does come in black. + +This makes Needle an ideal alternative for performing quick HTTP requests in Node, either for API interaction, downloading or uploading streams of data, and so on. If you need OAuth, AWS support or anything fancier, you should check out mikeal's request module. + +Install +------- + +``` +$ npm install needle +``` + +Usage +----- + +```js +// using promises +needle('get', 'https://server.com/posts/123') + .then(function(resp) { + // ... + }) + .catch(function(err) { + // ... + }); + +// with callback +needle.get('ifconfig.me/all.json', function(error, response, body) { + if (error) throw error; + + // body is an alias for `response.body`, + // that in this case holds a JSON-decoded object. + console.log(body.ip_addr); +}); + +// no callback, using streams +needle.get('https://google.com/images/logo.png') + .pipe(fs.createWriteStream('logo.png')) + .on('done', function(err) { + console.log('Pipe finished!'); + }); +``` + +As you can see, you can use Needle with Promises or without them. When using Promises or when a callback is passed, the response's body will be buffered and written to `response.body`, and the callback will be fired when all of the data has been collected and processed (e.g. decompressed, decoded and/or parsed). + +When no callback is passed, however, the buffering logic will be skipped but the response stream will still go through Needle's processing pipeline, so you get all the benefits of post-processing while keeping the streamishness we all love from Node. + +Response pipeline +----------------- + +Depending on the response's Content-Type, Needle will either attempt to parse JSON or XML streams, or, if a text response was received, will ensure that the final encoding you get is UTF-8. + +You can also request a gzip/deflated/brotli response, which, if sent by the server, will be processed before parsing or decoding is performed. (Note: brotli is only supported on Node 10.16.0 or above, and will not be requested or processed on earlier versions.) + +```js +needle.get('http://stackoverflow.com/feeds', { compressed: true }, function(err, resp) { + console.log(resp.body); // this little guy won't be a Gzipped binary blob + // but a nice object containing all the latest entries +}); +``` + +Or in anti-callback mode, using a few other options: + +```js +var options = { + compressed : true, // sets 'Accept-Encoding' to 'gzip, deflate, br' + follow_max : 5, // follow up to five redirects + rejectUnauthorized : true // verify SSL certificate +} + +var stream = needle.get('https://backend.server.com/everything.html', options); + +// read the chunks from the 'readable' event, so the stream gets consumed. +stream.on('readable', function() { + while (data = this.read()) { + console.log(data.toString()); + } +}) + +stream.on('done', function(err) { + // if our request had an error, our 'done' event will tell us. + if (!err) console.log('Great success!'); +}) +``` + +API +--- + +### needle(method, url[, data][, options][, callback]) `(> 2.0.x)` + +Calling `needle()` directly returns a Promise. Besides `method` and `url`, all parameters are optional, although when sending a `post`, `put` or `patch` request you will get an error if `data` is not present. + +```js +needle('get', 'http://some.url.com') + .then(function(resp) { console.log(resp.body) }) + .catch(function(err) { console.error(err) }) +``` + +Except from the above, all of Needle's request methods return a Readable stream, and both `options` and `callback` are optional. If passed, the callback will return three arguments: `error`, `response` and `body`, which is basically an alias for `response.body`. + +### needle.head(url[, options][, callback]) + +```js +needle.head('https://my.backend.server.com', { + open_timeout: 5000 // if we're not able to open a connection in 5 seconds, boom. +}, function(err, resp) { + if (err) + console.log('Shoot! Something is wrong: ' + err.message) + else + console.log('Yup, still alive.') +}) +``` + +### needle.get(url[, options][, callback]) + +```js +needle.get('google.com/search?q=syd+barrett', function(err, resp) { + // if no http:// is found, Needle will automagically prepend it. +}); +``` + +### needle.post(url, data[, options][, callback]) + +```js +var options = { + headers: { 'X-Custom-Header': 'Bumbaway atuna' } +} + +needle.post('https://my.app.com/endpoint', 'foo=bar', options, function(err, resp) { + // you can pass params as a string or as an object. +}); +``` + +### needle.put(url, data[, options][, callback]) + +```js +var nested = { + params: { + are: { + also: 'supported' + } + } +} + +needle.put('https://api.app.com/v2', nested, function(err, resp) { + console.log('Got ' + resp.bytes + ' bytes.') // another nice treat from this handsome fella. +}); +``` + +### needle.patch(url, data[, options][, callback]) + +Same behaviour as PUT. + +### needle.delete(url, data[, options][, callback]) + +```js +var options = { + username: 'fidelio', + password: 'x' +} + +needle.delete('https://api.app.com/messages/123', null, options, function(err, resp) { + // in this case, data may be null, but you need to explicity pass it. +}); +``` + +### needle.request(method, url, data[, options][, callback]) + +Generic request. This not only allows for flexibility, but also lets you perform a GET request with data, in which case will be appended to the request as a query string, unless you pass a `json: true` option (read below). + +```js +var params = { + q : 'a very smart query', + page : 2 +} + +needle.request('get', 'forum.com/search', params, function(err, resp) { + if (!err && resp.statusCode == 200) + console.log(resp.body); // here you go, mister. +}); +``` + +Now, if you set pass `json: true` among the options, Needle won't set your params as a querystring but instead send a JSON representation of your data through the request's body, as well as set the `Content-Type` and `Accept` headers to `application/json`. + +```js +needle.request('get', 'forum.com/search', params, { json: true }, function(err, resp) { + if (resp.statusCode == 200) console.log('It worked!'); +}); +``` + +Events +------ + +The [Readable stream](https://nodejs.org/api/stream.html#stream_class_stream_readable) object returned by the above request methods emits the following events, in addition to the regular ones (e.g. `end`, `close`, `data`, `pipe`, `readable`). + +### Event: `'response'` + + - `response ` + +Emitted when the underlying [http.ClientRequest](https://nodejs.org/api/http.html#http_class_http_clientrequest) emits a response event. This is after the connection is established and the header received, but before any of it is processed (e.g. authorization required or redirect to be followed). No data has been consumed at this point. + +### Event: `'redirect'` + + - `location ` + +Indicates that the a redirect is being followed. This means that the response code was a redirect (`301`, `302`, `303`, `307`) and the given [redirect options](#redirect-options) allowed following the URL received in the `Location` header. + +### Event: `'header'` + + - `statusCode ` + - `headers ` + +Triggered after the header has been processed, and just before the data is to be consumed. This implies that no redirect was followed and/or authentication header was received. In other words, we got a "valid" response. + +### Event: `'done'` (previously 'end') + + - `exception ` (optional) + +Emitted when the request/response process has finished, either because all data was consumed or an error ocurred somewhere in between. Unlike a regular stream's `end` event, Needle's `done` will be fired either on success or on failure, which is why the first argument may be an Error object. In other words: + +```js +var resp = needle.get('something.worthy/of/being/streamed/by/needle'); +resp.pipe(someWritableStream); + +resp.on('done', function(err) { + if (err) console.log('An error ocurred: ' + err.message); + else console.log('Great success!'); +}) +``` + +### Event: `'err'` + + - `exception ` + +Emitted when an error ocurrs. This should only happen once in the lifecycle of a Needle request. + +### Event: `'timeout'` + + - `type ` + +Emitted when an timeout error occurs. Type can be either 'open', 'response', or 'read'. This will called right before aborting the request, which will also trigger an `err` event, a described above, with an `ECONNRESET` (Socket hang up) exception. + +Request options +--------------- + +For information about options that've changed, there's always [the changelog](https://github.com/tomas/needle/releases). + + - `agent` : Uses an [http.Agent](https://nodejs.org/api/http.html#http_class_http_agent) of your choice, instead of the global, default one. Useful for tweaking the behaviour at the connection level, such as when doing tunneling (see below for an example). + - `json` : When `true`, sets content type to `application/json` and sends request body as JSON string, instead of a query string. + - `open_timeout`: (or `timeout`) Returns error if connection takes longer than X milisecs to establish. Defaults to `10000` (10 secs). `0` means no timeout. + - `response_timeout`: Returns error if no response headers are received in X milisecs, counting from when the connection is opened. Defaults to `0` (no response timeout). + - `read_timeout`: Returns error if data transfer takes longer than X milisecs, once response headers are received. Defaults to `0` (no timeout). + - `follow_max` : (or `follow`) Number of redirects to follow. Defaults to `0`. See below for more redirect options. + - `multipart` : Enables multipart/form-data encoding. Defaults to `false`. Use it when uploading files. + - `proxy` : Forwards request through HTTP(s) proxy. Eg. `proxy: 'http://user:pass@proxy.server.com:3128'`. For more advanced proxying/tunneling use a custom `agent`, as described below. + - `headers` : Object containing custom HTTP headers for request. Overrides defaults described below. + - `auth` : Determines what to do with provided username/password. Options are `auto`, `digest` or `basic` (default). `auto` will detect the type of authentication depending on the response headers. + - `stream_length`: When sending streams, this lets you manually set the Content-Length header --if the stream's bytecount is known beforehand--, preventing ECONNRESET (socket hang up) errors on some servers that misbehave when receiving payloads of unknown size. Set it to `0` and Needle will get and set the stream's length for you, or leave unset for the default behaviour, which is no Content-Length header for stream payloads. + - `localAddress`: , IP address. Passed to http/https request. Local interface from which the request should be emitted. + - `uri_modifier`: Anonymous function taking request (or redirect location if following redirects) URI as an argument and modifying it given logic. It has to return a valid URI string for successful request. + +Response options +---------------- + + - `decode_response` : (or `decode`) Whether to decode the text responses to UTF-8, if Content-Type header shows a different charset. Defaults to `true`. + - `parse_response` : (or `parse`) Whether to parse XML or JSON response bodies automagically. Defaults to `true`. You can also set this to 'xml' or 'json' in which case Needle will *only* parse the response if the content type matches. + - `output` : Dump response output to file. This occurs after parsing and charset decoding is done. + - `parse_cookies` : Whether to parse response’s `Set-Cookie` header. Defaults to `true`. If parsed, response cookies will be available at `resp.cookies`. + +HTTP Header options +------------------- + +These are basically shortcuts to the `headers` option described above. + + - `cookies` : Builds and sets a Cookie header from a `{ key: 'value' }` object. + - `compressed`: If `true`, sets 'Accept-Encoding' header to 'gzip,deflate', and inflates content if zipped. Defaults to `false`. + - `username` : For HTTP basic auth. + - `password` : For HTTP basic auth. Requires username to be passed, but is optional. + - `accept` : Sets 'Accept' HTTP header. Defaults to `*/*`. + - `connection`: Sets 'Connection' HTTP header. Not set by default, unless running Node < 0.11.4 in which case it defaults to `close`. More info about this below. + - `user_agent`: Sets the 'User-Agent' HTTP header. Defaults to `Needle/{version} (Node.js {node_version})`. + - `content_type`: Sets the 'Content-Type' header. Unset by default, unless you're sending data in which case it's set accordingly to whatever is being sent (`application/x-www-form-urlencoded`, `application/json` or `multipart/form-data`). That is, of course, unless the option is passed, either here or through `options.headers`. You're the boss. + +Node.js TLS Options +------------------- + +These options are passed directly to `https.request` if present. Taken from the [original documentation](http://nodejs.org/docs/latest/api/https.html): + + - `pfx` : Certificate, Private key and CA certificates to use for SSL. + - `key` : Private key to use for SSL. + - `passphrase` : A string of passphrase for the private key or pfx. + - `cert` : Public x509 certificate to use. + - `ca` : An authority certificate or array of authority certificates to check the remote host against. + - `ciphers` : A string describing the ciphers to use or exclude. + - `rejectUnauthorized` : If true, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. + - `secureProtocol` : The SSL method to use, e.g. SSLv3_method to force SSL version 3. + - `family` : IP address family to use when resolving host and hostname. Valid values are 4 or 6. When unspecified, both IP v4 and v6 will be used. + +Redirect options +---------------- + +These options only apply if the `follow_max` (or `follow`) option is higher than 0. + + - `follow_set_cookies` : Sends the cookies received in the `set-cookie` header as part of the following request. `false` by default. + - `follow_set_referer` : Sets the 'Referer' header to the requested URI when following a redirect. `false` by default. + - `follow_keep_method` : If enabled, resends the request using the original verb instead of being rewritten to `get` with no data. `false` by default. + - `follow_if_same_host` : When true, Needle will only follow redirects that point to the same host as the original request. `false` by default. + - `follow_if_same_protocol` : When true, Needle will only follow redirects that point to the same protocol as the original request. `false` by default. + - `follow_if_same_location` : Unless true, Needle will not follow redirects that point to same location (as set in the response header) as the original request URL. `false` by default. + +Overriding Defaults +------------------- + +Yes sir, we have it. Needle includes a `defaults()` method, that lets you override some of the defaults for all future requests. Like this: + +```js +needle.defaults({ + open_timeout: 60000, + user_agent: 'MyApp/1.2.3', + parse_response: false }); +``` + +This will override Needle's default user agent and 10-second timeout, and disable response parsing, so you don't need to pass those options in every other request. + +More advanced Proxy support +--------------------------- + +Since you can pass a custom HTTPAgent to Needle you can do all sorts of neat stuff. For example, if you want to use the [`tunnel`](https://github.com/koichik/node-tunnel) module for HTTPS proxying, you can do this: + +```js +var tunnel = require('tunnel'); +var myAgent = tunnel.httpOverHttp({ + proxy: { host: 'localhost' } +}); + +needle.get('foobar.com', { agent: myAgent }); +``` + +Otherwise, you can use the [`hpagent`](https://github.com/delvedor/hpagent) package, which keeps the internal sockets alive to be reused. + +```js +const { HttpsProxyAgent } = require('hpagent'); +needle('get', 'https://localhost:9200', { + agent: new HttpsProxyAgent({ + keepAlive: true, + keepAliveMsecs: 1000, + maxSockets: 256, + maxFreeSockets: 256, + scheduling: 'lifo', + proxy: 'https://localhost:8080' + }) +}); +``` + +Regarding the 'Connection' header +--------------------------------- + +Unless you're running an old version of Node (< 0.11.4), by default Needle won't set the Connection header on requests, yielding Node's default behaviour of keeping the connection alive with the target server. This speeds up immensely the process of sending several requests to the same host. + +On older versions, however, this has the unwanted behaviour of preventing the runtime from exiting, either because of a bug or 'feature' that was changed on 0.11.4. To overcome this Needle does set the 'Connection' header to 'close' on those versions, however this also means that making new requests to the same host doesn't benefit from Keep-Alive. + +So if you're stuck on 0.10 or even lower and want full speed, you can simply set the Connection header to 'Keep-Alive' by using `{ connection: 'Keep-Alive' }`. Please note, though, that an event loop handler will prevent the runtime from exiting so you'll need to manually call `process.exit()` or the universe will collapse. + +Examples Galore +--------------- + +### HTTPS GET with Basic Auth + +```js +needle.get('https://api.server.com', { username: 'you', password: 'secret' }, + function(err, resp) { + // used HTTP auth +}); +``` + +Or use [RFC-1738](http://tools.ietf.org/html/rfc1738#section-3.1) basic auth URL syntax: + +```js +needle.get('https://username:password@api.server.com', function(err, resp) { + // used HTTP auth from URL +}); +``` + +### Digest Auth + +```js +needle.get('other.server.com', { username: 'you', password: 'secret', auth: 'digest' }, + function(err, resp, body) { + // needle prepends 'http://' to your URL, if missing +}); +``` + +### Custom Accept header, deflate + +```js +var options = { + compressed : true, + follow : 10, + accept : 'application/vnd.github.full+json' +} + +needle.get('api.github.com/users/tomas', options, function(err, resp, body) { + // body will contain a JSON.parse(d) object + // if parsing fails, you'll simply get the original body +}); +``` + +### GET XML object + +```js +needle.get('https://news.ycombinator.com/rss', function(err, resp, body) { + // you'll get a nice object containing the nodes in the RSS +}); +``` + +### GET binary, output to file + +```js +needle.get('http://upload.server.com/tux.png', { output: '/tmp/tux.png' }, function(err, resp, body) { + // you can dump any response to a file, not only binaries. +}); +``` + +### GET through proxy + +```js +needle.get('http://search.npmjs.org', { proxy: 'http://localhost:1234' }, function(err, resp, body) { + // request passed through proxy +}); +``` + +### GET a very large document in a stream (from 0.7+) + +```js +var stream = needle.get('http://www.as35662.net/100.log'); + +stream.on('readable', function() { + var chunk; + while (chunk = this.read()) { + console.log('got data: ', chunk); + } +}); +``` + +### GET JSON object in a stream (from 0.7+) + +```js +var stream = needle.get('http://jsonplaceholder.typicode.com/db', { parse: true }); + +stream.on('readable', function() { + var node; + + // our stream will only emit a single JSON root node. + while (node = this.read()) { + console.log('got data: ', node); + } +}); +``` + +### GET JSONStream flexible parser with search query (from 0.7+) + +```js + + // The 'data' element of this stream will be the string representation + // of the titles of all posts. + +needle.get('http://jsonplaceholder.typicode.com/db', { parse: true }) + .pipe(new JSONStream.parse('posts.*.title')); + .on('data', function (obj) { + console.log('got post title: %s', obj); + }); +``` + +### File upload using multipart, passing file path + +```js +var data = { + foo: 'bar', + image: { file: '/home/tomas/linux.png', content_type: 'image/png' } +} + +needle.post('http://my.other.app.com', data, { multipart: true }, function(err, resp, body) { + // needle will read the file and include it in the form-data as binary +}); +``` + +### Stream upload, PUT or POST + +``` js +needle.put('https://api.app.com/v2', fs.createReadStream('myfile.txt'), function(err, resp, body) { + // stream content is uploaded verbatim +}); +``` + +### Multipart POST, passing data buffer + +```js +var buffer = fs.readFileSync('/path/to/package.zip'); + +var data = { + zip_file: { + buffer : buffer, + filename : 'mypackage.zip', + content_type : 'application/octet-stream' + } +} + +needle.post('http://somewhere.com/over/the/rainbow', data, { multipart: true }, function(err, resp, body) { + // if you see, when using buffers we need to pass the filename for the multipart body. + // you can also pass a filename when using the file path method, in case you want to override + // the default filename to be received on the other end. +}); +``` + +### Multipart with custom Content-Type + +```js +var data = { + token: 'verysecret', + payload: { + value: JSON.stringify({ title: 'test', version: 1 }), + content_type: 'application/json' + } +} + +needle.post('http://test.com/', data, { timeout: 5000, multipart: true }, function(err, resp, body) { + // in this case, if the request takes more than 5 seconds + // the callback will return a [Socket closed] error +}); +``` + +For even more examples, check out the examples directory in the repo. + +### Testing + +To run tests, you need to generate a self-signed SSL certificate in the `test` directory. After cloning the repository, run the following commands: + + $ mkdir -p test/keys + $ openssl genrsa -out test/keys/ssl.key 2048 + $ openssl req -new -key test/keys/ssl.key -x509 -days 999 -out test/keys/ssl.cert + +Then you should be able to run `npm test` once you have the dependencies in place. + +> Note: Tests currently only work on linux-based environments that have `/proc/self/fd`. They *do not* work on MacOS environments. +> You can use Docker to run tests by creating a container and mounting the needle project directory on `/app` +> `docker create --name Needle -v /app -w /app -v /app/node_modules -i node:argon` + +Credits +------- + +Written by Tomás Pollak, with the help of contributors. + +Copyright +--------- + +(c) Fork Ltd. Licensed under the MIT license. diff --git a/node_modules/needle/bin/needle b/node_modules/needle/bin/needle new file mode 100644 index 0000000000000000000000000000000000000000..baaa79b055f496d10f6994f694e6362d6abcd0f0 --- /dev/null +++ b/node_modules/needle/bin/needle @@ -0,0 +1,40 @@ +#!/usr/bin/env node +var needle = require('./../lib/needle'); + +function exit(code, str) { + console.log(str) || process.exit(code); +} + +function usage() { + var out = ['Usage: needle [get|head|post|put|delete] url [query]']; + out.push('Examples: \n needle get google.com\n needle post server.com/api foo=bar'); + exit(1, out.join('\n')) +} + +if (process.argv[2] == '-v' || process.argv[2] == '--version') + exit(0, needle.version); +else if (process.argv[2] == null) + usage(); + +var method = process.argv[2], + url = process.argv[3], + options = { compressed: true, parse_response: true, follow_max: 5, timeout: 10000 }; + +if (!needle[method]) { + url = method; + method = 'get'; +} + +var callback = function(err, resp) { + if (err) return exit(1, "Error: " + err.message); + + if (process.argv.indexOf('-i') != -1) + console.log(resp.headers) || console.log(''); + + console.log(resp.body.toString()); +}; + +if (method == 'post' || method == 'put') + needle[method](url, process.argv[4], options, callback); +else + needle[method](url, options, callback); diff --git a/node_modules/needle/examples/deflated-stream.js b/node_modules/needle/examples/deflated-stream.js new file mode 100644 index 0000000000000000000000000000000000000000..4e771b743085d5ba2854bee3a3959b5380b59ba2 --- /dev/null +++ b/node_modules/needle/examples/deflated-stream.js @@ -0,0 +1,22 @@ +var fs = require('fs'), + stream = require('stream'), + needle = require('./../'); + +var url = 'http://ibl.gamechaser.net/f/tagqfxtteucbuldhezkz/bt_level1.gz'; + +var resp = needle.get(url, { compressed: true, follow_max: 10 }); +console.log('Downloading...'); + +resp.on('readable', function() { + + while (data = this.read()) { + var lines = data.toString().split('\n'); + console.log('Got ' + lines.length + ' items.'); + // console.log(lines); + } + +}) + +resp.on('done', function(data) { + console.log('Done'); +}) diff --git a/node_modules/needle/examples/digest-auth.js b/node_modules/needle/examples/digest-auth.js new file mode 100644 index 0000000000000000000000000000000000000000..5b8e5d5e78aec3129337eb371e20a3ef896df44c --- /dev/null +++ b/node_modules/needle/examples/digest-auth.js @@ -0,0 +1,16 @@ +var needle = require('./..'); + +var opts = { + username: 'user3', + password: 'user3', + auth: 'digest' +} + +needle.get('http://test.webdav.org/auth-digest/', opts, function(err, resp, body) { + console.log(resp.headers); + + if (resp.statusCode == 401) + console.log('\nIt failed.') + else + console.log('\nIt worked!') +}); diff --git a/node_modules/needle/examples/download-to-file.js b/node_modules/needle/examples/download-to-file.js new file mode 100644 index 0000000000000000000000000000000000000000..39d5af97d4482333a842f3b292783e42dad59b05 --- /dev/null +++ b/node_modules/needle/examples/download-to-file.js @@ -0,0 +1,18 @@ +var fs = require('fs'), + needle = require('./..'), + path = require('path'); + +var url = process.argv[2] || 'https://upload.wikimedia.org/wikipedia/commons/a/af/Tux.png'; +var file = path.basename(url); + +console.log('Downloading ' + file); + +needle.get(url, { output: file, follow: 3 }, function(err, resp, data){ + console.log('File saved: ' + process.cwd() + '/' + file); + + var size = fs.statSync(file).size; + if (size == resp.bytes) + console.log(resp.bytes + ' bytes written to file.'); + else + throw new Error('File size mismatch: ' + size + ' != ' + resp.bytes); +}); diff --git a/node_modules/needle/examples/multipart-stream.js b/node_modules/needle/examples/multipart-stream.js new file mode 100644 index 0000000000000000000000000000000000000000..df1ada6e25c42d28ecd14aee8d48e6736b312e0d --- /dev/null +++ b/node_modules/needle/examples/multipart-stream.js @@ -0,0 +1,25 @@ +var needle = require('./../'); + +var url = 'http://posttestserver.com/post.php?dir=needle'; + +var black_pixel = Buffer.from("R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=", 'base64'); + +var data = { + foo: 'bar', + nested: { + test: 123 + }, + image: { buffer: black_pixel, content_type: 'image/gif' } +} + +var resp = needle.post(url, data, { multipart: true }); + +resp.on('readable', function() { + while (data = this.read()) { + console.log(data.toString()); + } +}) + +resp.on('done', function(data) { + console.log('Done.'); +}) diff --git a/node_modules/needle/examples/parsed-stream.js b/node_modules/needle/examples/parsed-stream.js new file mode 100644 index 0000000000000000000000000000000000000000..89c22c666ff7114d76e4b1a21acc9ab9fa0f8e73 --- /dev/null +++ b/node_modules/needle/examples/parsed-stream.js @@ -0,0 +1,23 @@ +////////////////////////////////////////// +// This example demonstrates what happends +// when you use the built-in JSON parser. +////////////////////////////////////////// + +var fs = require('fs'), + stream = require('stream'), + needle = require('./../'); + +var url = 'http://ip.jsontest.com/', + resp = needle.get(url, { parse: true }); + +resp.on('readable', function(obj) { + var chunk; + + while (chunk = this.read()) { + console.log('root = ', chunk); + } +}); + +resp.on('done', function() { + console.log('Done.'); +}); diff --git a/node_modules/needle/examples/parsed-stream2.js b/node_modules/needle/examples/parsed-stream2.js new file mode 100644 index 0000000000000000000000000000000000000000..5d9b79afe1dbc11d2002ac6b1efd91b209bf6b24 --- /dev/null +++ b/node_modules/needle/examples/parsed-stream2.js @@ -0,0 +1,21 @@ +////////////////////////////////////////// +// This example illustrates a more complex +// example of parsing a JSON stream. +////////////////////////////////////////// + +var needle = require('./../'), + JSONStream = require('JSONStream'); + +var url = 'http://jsonplaceholder.typicode.com/db'; + +// Initialize our GET request with our default (JSON) +// parsers disabled. + +var json = new needle.get(url, {parse: false}) + // And now interpret the stream as JSON, returning only the + // title of all the posts. + .pipe(new JSONStream.parse('posts.*.title')); + +json.on('data', function (obj) { + console.log('got title: \'' + obj + '\''); +}) diff --git a/node_modules/needle/examples/stream-events.js b/node_modules/needle/examples/stream-events.js new file mode 100644 index 0000000000000000000000000000000000000000..6230993809964b5c2041010558ef8314525eb969 --- /dev/null +++ b/node_modules/needle/examples/stream-events.js @@ -0,0 +1,23 @@ +var needle = require('./..'); + +var resp = needle.get('google.com', { follow_max: 10, timeout: 5000 }); + +resp.on('readable', function() { + var chunk; + while (chunk = this.read()) { + console.log('Got ' + chunk.length + ' bytes'); + } +}) + +resp.on('headers', function(headers) { + console.log('Got headers', headers); +}) + +resp.on('redirect', function(url) { + console.log('Redirected to url ' + url); +}) + +resp.on('done', function(err) { + console.log('Finished. No more data to receive.'); + if (err) console.log('With error', err) +}) diff --git a/node_modules/needle/examples/stream-to-file.js b/node_modules/needle/examples/stream-to-file.js new file mode 100644 index 0000000000000000000000000000000000000000..d261bee9f66fbc23c27b6e4cd854741456173016 --- /dev/null +++ b/node_modules/needle/examples/stream-to-file.js @@ -0,0 +1,14 @@ +var fs = require('fs'), + needle = require('./..'), + path = require('path'); + +var url = process.argv[2] || 'http://www.google.com/images/errors/robot.png'; +var file = path.basename(url); + +console.log('Downloading ' + file + '...'); +needle + .get(url) + .pipe(fs.createWriteStream(file)) + .on('done', function() { + console.log('Done!') + }) diff --git a/node_modules/needle/examples/upload-image.js b/node_modules/needle/examples/upload-image.js new file mode 100644 index 0000000000000000000000000000000000000000..090e3e3fc16ec61e255bbf1eba5647a107a3f47e --- /dev/null +++ b/node_modules/needle/examples/upload-image.js @@ -0,0 +1,51 @@ +var needle = require('../'), + path = require('path'); + +var image = 'https://upload.wikimedia.org/wikipedia/commons/a/af/Tux.png'; + +function upload(obj, cb) { + console.log('Uploading image...'); + + var url = 'http://deviantsart.com'; + + var opts = { + timeout: 10000, + follow: 3, + multipart: true + }; + + var params = { + file: obj + } + + needle.post(url, params, opts, function(err, resp) { + if (err || !resp.body.match('url')) + return cb(err || new Error('No image URL found.')) + + cb(null, JSON.parse(resp.body).url) + }) +} + +function download(url, cb) { + console.log('Getting ' + url); + needle.get(url, function(err, resp) { + if (err) throw err; + + cb(null, resp.body); + }) +} + +//////////////////////////////////////// +// ok, now go. + +download(image, function(err, buffer) { + if (err) throw err; + + var obj = { buffer: buffer, content_type: 'image/png' }; + + upload(obj, function(err, url) { + if (err) throw err; + + console.log('Image uploaded to ' + url); + }) +}) diff --git a/node_modules/needle/lib/auth.js b/node_modules/needle/lib/auth.js new file mode 100644 index 0000000000000000000000000000000000000000..66d3f5ce0a76fc994f77d5df0406563e63dd334b --- /dev/null +++ b/node_modules/needle/lib/auth.js @@ -0,0 +1,112 @@ +var createHash = require('crypto').createHash; + +function get_header(header, credentials, opts) { + var type = header.split(' ')[0], + user = credentials[0], + pass = credentials[1]; + + if (type == 'Digest') { + return digest.generate(header, user, pass, opts.method, opts.path); + } else if (type == 'Basic') { + return basic(user, pass); + } +} + +//////////////////// +// basic + +function md5(string) { + return createHash('md5').update(string).digest('hex'); +} + +function basic(user, pass) { + var str = typeof pass == 'undefined' ? user : [user, pass].join(':'); + return 'Basic ' + Buffer.from(str).toString('base64'); +} + +//////////////////// +// digest +// logic inspired from https://github.com/simme/node-http-digest-client + +var digest = {}; + +digest.parse_header = function(header) { + var challenge = {}, + matches = header.match(/([a-z0-9_-]+)="?([a-z0-9_=\/\.@\s-\+)()]+)"?/gi); + + for (var i = 0, l = matches.length; i < l; i++) { + var parts = matches[i].split('='), + key = parts.shift(), + val = parts.join('=').replace(/^"/, '').replace(/"$/, ''); + + challenge[key] = val; + } + + return challenge; +} + +digest.update_nc = function(nc) { + var max = 99999999; + nc++; + + if (nc > max) + nc = 1; + + var padding = new Array(8).join('0') + ''; + nc = nc + ''; + return padding.substr(0, 8 - nc.length) + nc; +} + +digest.generate = function(header, user, pass, method, path) { + + var nc = 1, + cnonce = null, + challenge = digest.parse_header(header); + + var ha1 = md5(user + ':' + challenge.realm + ':' + pass), + ha2 = md5(method.toUpperCase() + ':' + path), + resp = [ha1, challenge.nonce]; + + if (typeof challenge.qop === 'string') { + cnonce = md5(Math.random().toString(36)).substr(0, 8); + nc = digest.update_nc(nc); + resp = resp.concat(nc, cnonce); + resp = resp.concat(challenge.qop, ha2); + } else { + resp = resp.concat(ha2); + } + + + var params = { + uri : path, + realm : challenge.realm, + nonce : challenge.nonce, + username : user, + response : md5(resp.join(':')) + } + + if (challenge.qop) { + params.qop = challenge.qop; + } + + if (challenge.opaque) { + params.opaque = challenge.opaque; + } + + if (cnonce) { + params.nc = nc; + params.cnonce = cnonce; + } + + header = [] + for (var k in params) + header.push(k + '="' + params[k] + '"') + + return 'Digest ' + header.join(', '); +} + +module.exports = { + header : get_header, + basic : basic, + digest : digest.generate +} diff --git a/node_modules/needle/lib/cookies.js b/node_modules/needle/lib/cookies.js new file mode 100644 index 0000000000000000000000000000000000000000..0f48afcff4d88ec048fb1e16f5fcf7de9ac7b715 --- /dev/null +++ b/node_modules/needle/lib/cookies.js @@ -0,0 +1,79 @@ + +// Simple cookie handling implementation based on the standard RFC 6265. +// +// This module just has two functionalities: +// - Parse a set-cookie-header as a key value object +// - Write a cookie-string from a key value object +// +// All cookie attributes are ignored. + +var unescape = require('querystring').unescape; + +var COOKIE_PAIR = /^([^=\s]+)\s*=\s*("?)\s*(.*)\s*\2\s*$/; +var EXCLUDED_CHARS = /[\x00-\x1F\x7F\x3B\x3B\s\"\,\\"%]/g; +var TRAILING_SEMICOLON = /\x3B+$/; +var SEP_SEMICOLON = /\s*\x3B\s*/; + +// i know these should be 'const', but I'd like to keep +// supporting earlier node.js versions as long as I can. :) + +var KEY_INDEX = 1; // index of key from COOKIE_PAIR match +var VALUE_INDEX = 3; // index of value from COOKIE_PAIR match + +// Returns a copy str trimmed and without trainling semicolon. +function cleanCookieString(str) { + return str.trim().replace(/\x3B+$/, ''); +} + +function getFirstPair(str) { + var index = str.indexOf('\x3B'); + return index === -1 ? str : str.substr(0, index); +} + +// Returns a encoded copy of str based on RFC6265 S4.1.1. +function encodeCookieComponent(str) { + return str.toString().replace(EXCLUDED_CHARS, encodeURIComponent); +} + +// Parses a set-cookie-string based on the standard defined in RFC6265 S4.1.1. +function parseSetCookieString(str) { + str = cleanCookieString(str); + str = getFirstPair(str); + + var res = COOKIE_PAIR.exec(str); + if (!res || !res[VALUE_INDEX]) return null; + + return { + name : unescape(res[KEY_INDEX]), + value : unescape(res[VALUE_INDEX]) + }; +} + +// Parses a set-cookie-header and returns a key/value object. +// Each key represents the name of a cookie. +function parseSetCookieHeader(header) { + if (!header) return {}; + header = Array.isArray(header) ? header : [header]; + + return header.reduce(function(res, str) { + var cookie = parseSetCookieString(str); + if (cookie) res[cookie.name] = cookie.value; + return res; + }, {}); +} + +// Writes a set-cookie-string based on the standard definded in RFC6265 S4.1.1. +function writeCookieString(obj) { + return Object.keys(obj).reduce(function(str, name) { + var encodedName = encodeCookieComponent(name); + var encodedValue = encodeCookieComponent(obj[name]); + str += (str ? '; ' : '') + encodedName + '=' + encodedValue; + return str; + }, ''); +} + +// returns a key/val object from an array of cookie strings +exports.read = parseSetCookieHeader; + +// writes a cookie string header +exports.write = writeCookieString; diff --git a/node_modules/needle/lib/decoder.js b/node_modules/needle/lib/decoder.js new file mode 100644 index 0000000000000000000000000000000000000000..4ff6198b18c0708a3d733dfdfcf98d9a4ec5598d --- /dev/null +++ b/node_modules/needle/lib/decoder.js @@ -0,0 +1,53 @@ +var iconv, + inherits = require('util').inherits, + stream = require('stream'); + +var regex = /(?:charset|encoding)\s*=\s*['"]? *([\w\-]+)/i; + +inherits(StreamDecoder, stream.Transform); + +function StreamDecoder(charset) { + if (!(this instanceof StreamDecoder)) + return new StreamDecoder(charset); + + stream.Transform.call(this, charset); + this.charset = charset; + this.parsed_chunk = false; +} + +StreamDecoder.prototype._transform = function(chunk, encoding, done) { + var res, found; + + // try get charset from chunk, just once + if (this.charset == 'utf8' && !this.parsed_chunk) { + this.parsed_chunk = true; + + var matches = regex.exec(chunk.toString()); + if (matches) { + found = matches[1].toLowerCase(); + this.charset = found == 'utf-8' ? 'utf8' : found; + } + } + + try { + res = iconv.decode(chunk, this.charset); + } catch(e) { // something went wrong, just return original chunk + res = chunk; + } + + this.push(res); + done(); +} + +module.exports = function(charset) { + try { + if (!iconv) iconv = require('iconv-lite'); + } catch(e) { + /* iconv not found */ + } + + if (iconv) + return new StreamDecoder(charset); + else + return new stream.PassThrough; +} diff --git a/node_modules/needle/lib/multipart.js b/node_modules/needle/lib/multipart.js new file mode 100644 index 0000000000000000000000000000000000000000..d1e6e1855ad668199826e5d57f04c7f967300f3e --- /dev/null +++ b/node_modules/needle/lib/multipart.js @@ -0,0 +1,98 @@ +var readFile = require('fs').readFile, + basename = require('path').basename; + +exports.build = function(data, boundary, callback) { + + if (typeof data != 'object' || typeof data.pipe == 'function') + return callback(new Error('Multipart builder expects data as key/val object.')); + + var body = '', + object = flatten(data), + count = Object.keys(object).length; + + if (count === 0) + return callback(new Error('Empty multipart body. Invalid data.')) + + function done(err, section) { + if (err) return callback(err); + if (section) body += section; + --count || callback(null, body + '--' + boundary + '--'); + }; + + for (var key in object) { + var value = object[key]; + if (value === null || typeof value == 'undefined') { + done(); + } else if (Buffer.isBuffer(value)) { + var part = { buffer: value, content_type: 'application/octet-stream' }; + generate_part(key, part, boundary, done); + } else { + var part = (value.buffer || value.file || value.content_type) ? value : { value: value }; + generate_part(key, part, boundary, done); + } + } + +} + +function generate_part(name, part, boundary, callback) { + + var return_part = '--' + boundary + '\r\n'; + return_part += 'Content-Disposition: form-data; name="' + name + '"'; + + function append(data, filename) { + + if (data) { + var binary = part.content_type.indexOf('text') == -1; + return_part += '; filename="' + encodeURIComponent(filename) + '"\r\n'; + if (binary) return_part += 'Content-Transfer-Encoding: binary\r\n'; + return_part += 'Content-Type: ' + part.content_type + '\r\n\r\n'; + return_part += binary ? data.toString('binary') : data.toString('utf8'); + } + + callback(null, return_part + '\r\n'); + }; + + if ((part.file || part.buffer) && part.content_type) { + + var filename = part.filename ? part.filename : part.file ? basename(part.file) : name; + if (part.buffer) return append(part.buffer, filename); + + readFile(part.file, function(err, data) { + if (err) return callback(err); + append(data, filename); + }); + + } else { + + if (typeof part.value == 'object') + return callback(new Error('Object received for ' + name + ', expected string.')) + + if (part.content_type) { + return_part += '\r\n'; + return_part += 'Content-Type: ' + part.content_type; + } + + return_part += '\r\n\r\n'; + return_part += Buffer.from(String(part.value), 'utf8').toString('binary'); + append(); + + } + +} + +// flattens nested objects for multipart body +function flatten(object, into, prefix) { + into = into || {}; + + for(var key in object) { + var prefix_key = prefix ? prefix + '[' + key + ']' : key; + var prop = object[key]; + + if (prop && typeof prop === 'object' && !(prop.buffer || prop.file || prop.content_type)) + flatten(prop, into, prefix_key) + else + into[prefix_key] = prop; + } + + return into; +} diff --git a/node_modules/needle/lib/needle.js b/node_modules/needle/lib/needle.js new file mode 100644 index 0000000000000000000000000000000000000000..b56c8f66b2a09ced45bf9e57d427f197326fb0ab --- /dev/null +++ b/node_modules/needle/lib/needle.js @@ -0,0 +1,879 @@ +////////////////////////////////////////// +// Needle -- HTTP Client for Node.js +// Written by Tomás Pollak +// (c) 2012-2020 - Fork Ltd. +// MIT Licensed +////////////////////////////////////////// + +var fs = require('fs'), + http = require('http'), + https = require('https'), + url = require('url'), + stream = require('stream'), + debug = require('debug')('needle'), + stringify = require('./querystring').build, + multipart = require('./multipart'), + auth = require('./auth'), + cookies = require('./cookies'), + parsers = require('./parsers'), + decoder = require('./decoder'); + +////////////////////////////////////////// +// variabilia + +var version = require('../package.json').version; + +var user_agent = 'Needle/' + version; +user_agent += ' (Node.js ' + process.version + '; ' + process.platform + ' ' + process.arch + ')'; + +var tls_options = 'agent pfx key passphrase cert ca ciphers rejectUnauthorized secureProtocol checkServerIdentity family'; + +// older versions of node (< 0.11.4) prevent the runtime from exiting +// because of connections in keep-alive state. so if this is the case +// we'll default new requests to set a Connection: close header. +var close_by_default = !http.Agent || http.Agent.defaultMaxSockets != Infinity; + +// see if we have Object.assign. otherwise fall back to util._extend +var extend = Object.assign ? Object.assign : require('util')._extend; + +// these are the status codes that Needle interprets as redirects. +var redirect_codes = [301, 302, 303, 307, 308]; + +////////////////////////////////////////// +// decompressors for gzip/deflate/br bodies + +function bind_opts(fn, options) { + return fn.bind(null, options); +} + +var decompressors = {}; + +try { + + var zlib = require('zlib'); + + // Enable Z_SYNC_FLUSH to avoid Z_BUF_ERROR errors (Node PR #2595) + var zlib_options = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + var br_options = { + flush: zlib.BROTLI_OPERATION_FLUSH, + finishFlush: zlib.BROTLI_OPERATION_FLUSH + }; + + decompressors['x-deflate'] = bind_opts(zlib.Inflate, zlib_options); + decompressors['deflate'] = bind_opts(zlib.Inflate, zlib_options); + decompressors['x-gzip'] = bind_opts(zlib.Gunzip, zlib_options); + decompressors['gzip'] = bind_opts(zlib.Gunzip, zlib_options); + if (typeof zlib.BrotliDecompress === 'function') { + decompressors['br'] = bind_opts(zlib.BrotliDecompress, br_options); + } + +} catch(e) { /* zlib not available */ } + +////////////////////////////////////////// +// options and aliases + +var defaults = { + // data + boundary : '--------------------NODENEEDLEHTTPCLIENT', + encoding : 'utf8', + parse_response : 'all', // same as true. valid options: 'json', 'xml' or false/null + proxy : null, + + // headers + headers : {}, + accept : '*/*', + user_agent : user_agent, + + // numbers + open_timeout : 10000, + response_timeout : 0, + read_timeout : 0, + follow_max : 0, + stream_length : -1, + + // booleans + compressed : false, + decode_response : true, + parse_cookies : true, + follow_set_cookies : false, + follow_set_referer : false, + follow_keep_method : false, + follow_if_same_host : false, + follow_if_same_protocol : false, + follow_if_same_location : false +} + +var aliased = { + options: { + decode : 'decode_response', + parse : 'parse_response', + timeout : 'open_timeout', + follow : 'follow_max' + }, + inverted: {} +} + +// only once, invert aliased keys so we can get passed options. +Object.keys(aliased.options).map(function(k) { + var value = aliased.options[k]; + aliased.inverted[value] = k; +}); + +////////////////////////////////////////// +// helpers + +function keys_by_type(type) { + return Object.keys(defaults).map(function(el) { + if (defaults[el] !== null && defaults[el].constructor == type) + return el; + }).filter(function(el) { return el }) +} + +function parse_content_type(header) { + if (!header || header === '') return {}; + + var found, charset = 'utf8', arr = header.split(';'); + + if (arr.length > 1 && (found = arr[1].match(/charset=(.+)/))) + charset = found[1]; + + return { type: arr[0], charset: charset }; +} + +function is_stream(obj) { + return typeof obj.pipe === 'function'; +} + +function get_stream_length(stream, given_length, cb) { + if (given_length > 0) + return cb(given_length); + + if (stream.end !== void 0 && stream.end !== Infinity && stream.start !== void 0) + return cb((stream.end + 1) - (stream.start || 0)); + + fs.stat(stream.path, function(err, stat) { + cb(stat ? stat.size - (stream.start || 0) : null); + }); +} + +function resolve_url(href, base) { + if (url.URL) + return new url.URL(href, base); + + // older Node version (< v6.13) + return url.resolve(base, href); +} + +function pump_streams(streams, cb) { + if (stream.pipeline) + return stream.pipeline.apply(null, streams.concat(cb)); + + var tmp = streams.shift(); + while (streams.length) { + tmp = tmp.pipe(streams.shift()); + tmp.once('error', function(e) { + cb && cb(e); + cb = null; + }) + } +} + +////////////////////////////////////////// +// the main act + +function Needle(method, uri, data, options, callback) { + // if (!(this instanceof Needle)) { + // return new Needle(method, uri, data, options, callback); + // } + + if (typeof uri !== 'string') + throw new TypeError('URL must be a string, not ' + uri); + + this.method = method.toLowerCase(); + this.uri = uri; + this.data = data; + + if (typeof options == 'function') { + this.callback = options; + this.options = {}; + } else { + this.callback = callback; + this.options = options; + } + +} + +Needle.prototype.setup = function(uri, options) { + + function get_option(key, fallback) { + // if original is in options, return that value + if (typeof options[key] != 'undefined') return options[key]; + + // otherwise, return value from alias or fallback/undefined + return typeof options[aliased.inverted[key]] != 'undefined' + ? options[aliased.inverted[key]] : fallback; + } + + function check_value(expected, key) { + var value = get_option(key), + type = typeof value; + + if (type != 'undefined' && type != expected) + throw new TypeError(type + ' received for ' + key + ', but expected a ' + expected); + + return (type == expected) ? value : defaults[key]; + } + + ////////////////////////////////////////////////// + // the basics + + var config = { + http_opts : { + localAddress: get_option('localAddress', undefined), + lookup: get_option('lookup', undefined) + }, // passed later to http.request() directly + headers : {}, + output : options.output, + proxy : get_option('proxy', defaults.proxy), + parser : get_option('parse_response', defaults.parse_response), + encoding : options.encoding || (options.multipart ? 'binary' : defaults.encoding) + } + + keys_by_type(Boolean).forEach(function(key) { + config[key] = check_value('boolean', key); + }) + + keys_by_type(Number).forEach(function(key) { + config[key] = check_value('number', key); + }) + + // populate http_opts with given TLS options + tls_options.split(' ').forEach(function(key) { + if (typeof options[key] != 'undefined') { + config.http_opts[key] = options[key]; + if (typeof options.agent == 'undefined') + config.http_opts.agent = false; // otherwise tls options are skipped + } + }); + + ////////////////////////////////////////////////// + // headers, cookies + + for (var key in defaults.headers) + config.headers[key] = defaults.headers[key]; + + config.headers['accept'] = options.accept || defaults.accept; + config.headers['user-agent'] = options.user_agent || defaults.user_agent; + + if (options.content_type) + config.headers['content-type'] = options.content_type; + + // set connection header if opts.connection was passed, or if node < 0.11.4 (close) + if (options.connection || close_by_default) + config.headers['connection'] = options.connection || 'close'; + + if ((options.compressed || defaults.compressed) && typeof zlib != 'undefined') + config.headers['accept-encoding'] = decompressors['br'] ? 'gzip, deflate, br' : 'gzip, deflate'; + + if (options.cookies) + config.headers['cookie'] = cookies.write(options.cookies); + + ////////////////////////////////////////////////// + // basic/digest auth + + if (uri.match(/[^\/]@/)) { // url contains user:pass@host, so parse it. + var parts = (url.parse(uri).auth || '').split(':'); + options.username = parts[0]; + options.password = parts[1]; + } + + if (options.username) { + if (options.auth && (options.auth == 'auto' || options.auth == 'digest')) { + config.credentials = [options.username, options.password]; + } else { + config.headers['authorization'] = auth.basic(options.username, options.password); + } + } + + // if proxy is present, set auth header from either url or proxy_user option. + if (config.proxy) { + if (config.proxy.indexOf('http') === -1) + config.proxy = 'http://' + config.proxy; + + if (config.proxy.indexOf('@') !== -1) { + var proxy = (url.parse(config.proxy).auth || '').split(':'); + options.proxy_user = proxy[0]; + options.proxy_pass = proxy[1]; + } + + if (options.proxy_user) + config.headers['proxy-authorization'] = auth.basic(options.proxy_user, options.proxy_pass); + } + + // now that all our headers are set, overwrite them if instructed. + for (var h in options.headers) + config.headers[h.toLowerCase()] = options.headers[h]; + + config.uri_modifier = get_option('uri_modifier', null); + + return config; +} + +Needle.prototype.start = function() { + + var out = new stream.PassThrough({ objectMode: false }), + uri = this.uri, + data = this.data, + method = this.method, + callback = (typeof this.options == 'function') ? this.options : this.callback, + options = this.options || {}; + + // if no 'http' is found on URL, prepend it. + if (uri.indexOf('http') === -1) + uri = uri.replace(/^(\/\/)?/, 'http://'); + + var self = this, body, waiting = false, config = this.setup(uri, options); + + // unless options.json was set to false, assume boss also wants JSON if content-type matches. + var json = options.json || (options.json !== false && config.headers['content-type'] == 'application/json'); + + if (data) { + + if (options.multipart) { // boss says we do multipart. so we do it. + var boundary = options.boundary || defaults.boundary; + + waiting = true; + multipart.build(data, boundary, function(err, parts) { + if (err) throw(err); + + config.headers['content-type'] = 'multipart/form-data; boundary=' + boundary; + next(parts); + }); + + } else if (is_stream(data)) { + + if (method == 'get') + throw new Error('Refusing to pipe() a stream via GET. Did you mean .post?'); + + if (config.stream_length > 0 || (config.stream_length === 0 && data.path)) { + // ok, let's get the stream's length and set it as the content-length header. + // this prevents some servers from cutting us off before all the data is sent. + waiting = true; + get_stream_length(data, config.stream_length, function(length) { + data.length = length; + next(data); + }) + + } else { + // if the boss doesn't want us to get the stream's length, or if it doesn't + // have a file descriptor for that purpose, then just head on. + body = data; + } + + } else if (Buffer.isBuffer(data)) { + + body = data; // use the raw buffer as request body. + + } else if (method == 'get' && !json) { + + // append the data to the URI as a querystring. + uri = uri.replace(/\?.*|$/, '?' + stringify(data)); + + } else { // string or object data, no multipart. + + // if string, leave it as it is, otherwise, stringify. + body = (typeof(data) === 'string') ? data + : json ? JSON.stringify(data) : stringify(data); + + // ensure we have a buffer so bytecount is correct. + body = Buffer.from(body, config.encoding); + } + + } + + function next(body) { + if (body) { + if (body.length) config.headers['content-length'] = body.length; + + // if no content-type was passed, determine if json or not. + if (!config.headers['content-type']) { + config.headers['content-type'] = json + ? 'application/json; charset=utf-8' + : 'application/x-www-form-urlencoded'; // no charset says W3 spec. + } + } + + // unless a specific accept header was set, assume json: true wants JSON back. + if (options.json && (!options.accept && !(options.headers || {}).accept)) + config.headers['accept'] = 'application/json'; + + self.send_request(1, method, uri, config, body, out, callback); + } + + if (!waiting) next(body); + return out; +} + +Needle.prototype.get_request_opts = function(method, uri, config) { + var opts = config.http_opts, + proxy = config.proxy, + remote = proxy ? url.parse(proxy) : url.parse(uri); + + opts.protocol = remote.protocol; + opts.host = remote.hostname; + opts.port = remote.port || (remote.protocol == 'https:' ? 443 : 80); + opts.path = proxy ? uri : remote.pathname + (remote.search || ''); + opts.method = method; + opts.headers = config.headers; + + if (!opts.headers['host']) { + // if using proxy, make sure the host header shows the final destination + var target = proxy ? url.parse(uri) : remote; + opts.headers['host'] = target.hostname; + + // and if a non standard port was passed, append it to the port header + if (target.port && [80, 443].indexOf(target.port) === -1) { + opts.headers['host'] += ':' + target.port; + } + } + + return opts; +} + +Needle.prototype.should_follow = function(location, config, original) { + if (!location) return false; + + // returns true if location contains matching property (host or protocol) + function matches(property) { + var property = original[property]; + return location.indexOf(property) !== -1; + } + + // first, check whether the requested location is actually different from the original + if (!config.follow_if_same_location && location === original) + return false; + + if (config.follow_if_same_host && !matches('host')) + return false; // host does not match, so not following + + if (config.follow_if_same_protocol && !matches('protocol')) + return false; // procotol does not match, so not following + + return true; +} + +Needle.prototype.send_request = function(count, method, uri, config, post_data, out, callback) { + + if (typeof config.uri_modifier === 'function') { + var modified_uri = config.uri_modifier(uri); + debug('Modifying request URI', uri + ' => ' + modified_uri); + uri = modified_uri; + } + + var request, + timer, + returned = 0, + self = this, + request_opts = this.get_request_opts(method, uri, config), + protocol = request_opts.protocol == 'https:' ? https : http; + + function done(err, resp) { + if (returned++ > 0) + return debug('Already finished, stopping here.'); + + if (timer) clearTimeout(timer); + request.removeListener('error', had_error); + out.done = true; + + if (callback) + return callback(err, resp, resp ? resp.body : undefined); + + // NOTE: this event used to be called 'end', but the behaviour was confusing + // when errors ocurred, because the stream would still emit an 'end' event. + out.emit('done', err); + + // trigger the 'done' event on streams we're being piped to, if any + var pipes = out._readableState.pipes || []; + if (!pipes.forEach) pipes = [pipes]; + pipes.forEach(function(st) { st.emit('done', err); }) + } + + function had_error(err) { + debug('Request error', err); + out.emit('err', err); + done(err || new Error('Unknown error when making request.')); + } + + function set_timeout(type, milisecs) { + if (timer) clearTimeout(timer); + if (milisecs <= 0) return; + + timer = setTimeout(function() { + out.emit('timeout', type); + request.abort(); + // also invoke done() to terminate job on read_timeout + if (type == 'read') done(new Error(type + ' timeout')); + }, milisecs); + } + + // handle errors on the underlying socket, that may be closed while writing + // for an example case, see test/long_string_spec.js. we make sure this + // scenario ocurred by verifying the socket's writable & destroyed states. + function on_socket_end() { + if (returned && !this.writable && this.destroyed === false) { + this.destroy(); + had_error(new Error('Remote end closed socket abruptly.')) + } + } + + debug('Making request #' + count, request_opts); + request = protocol.request(request_opts, function(resp) { + + var headers = resp.headers; + debug('Got response', resp.statusCode, headers); + out.emit('response', resp); + + set_timeout('read', config.read_timeout); + + // if we got cookies, parse them unless we were instructed not to. make sure to include any + // cookies that might have been set on previous redirects. + if (config.parse_cookies && (headers['set-cookie'] || config.previous_resp_cookies)) { + resp.cookies = extend(config.previous_resp_cookies || {}, cookies.read(headers['set-cookie'])); + debug('Got cookies', resp.cookies); + } + + // if redirect code is found, determine if we should follow it according to the given options. + if (redirect_codes.indexOf(resp.statusCode) !== -1 && self.should_follow(headers.location, config, uri)) { + // clear timer before following redirects to prevent unexpected setTimeout consequence + clearTimeout(timer); + + if (count <= config.follow_max) { + out.emit('redirect', headers.location); + + // unless 'follow_keep_method' is true, rewrite the request to GET before continuing. + if (!config.follow_keep_method) { + method = 'GET'; + post_data = null; + delete config.headers['content-length']; // in case the original was a multipart POST request. + } + + // if follow_set_cookies is true, insert cookies in the next request's headers. + // we set both the original request cookies plus any response cookies we might have received. + if (config.follow_set_cookies) { + var request_cookies = cookies.read(config.headers['cookie']); + config.previous_resp_cookies = resp.cookies; + if (Object.keys(request_cookies).length || Object.keys(resp.cookies || {}).length) { + config.headers['cookie'] = cookies.write(extend(request_cookies, resp.cookies)); + } + } else if (config.headers['cookie']) { + debug('Clearing original request cookie', config.headers['cookie']); + delete config.headers['cookie']; + } + + if (config.follow_set_referer) + config.headers['referer'] = encodeURI(uri); // the original, not the destination URL. + + config.headers['host'] = null; // clear previous Host header to avoid conflicts. + + var redirect_url = resolve_url(headers.location, uri); + debug('Redirecting to ' + redirect_url.toString()); + return self.send_request(++count, method, redirect_url.toString(), config, post_data, out, callback); + } else if (config.follow_max > 0) { + return done(new Error('Max redirects reached. Possible loop in: ' + headers.location)); + } + } + + // if auth is requested and credentials were not passed, resend request, provided we have user/pass. + if (resp.statusCode == 401 && headers['www-authenticate'] && config.credentials) { + if (!config.headers['authorization']) { // only if authentication hasn't been sent + var auth_header = auth.header(headers['www-authenticate'], config.credentials, request_opts); + + if (auth_header) { + config.headers['authorization'] = auth_header; + return self.send_request(count, method, uri, config, post_data, out, callback); + } + } + } + + // ok, so we got a valid (non-redirect & authorized) response. let's notify the stream guys. + out.emit('header', resp.statusCode, headers); + out.emit('headers', headers); + + var pipeline = [], + mime = parse_content_type(headers['content-type']), + text_response = mime.type && (mime.type.indexOf('text/') != -1 || !!mime.type.match(/(\/|\+)(xml|json)$/)); + + // To start, if our body is compressed and we're able to inflate it, do it. + if (headers['content-encoding'] && decompressors[headers['content-encoding']]) { + + var decompressor = decompressors[headers['content-encoding']](); + + // make sure we catch errors triggered by the decompressor. + decompressor.on('error', had_error); + pipeline.push(decompressor); + } + + // If parse is enabled and we have a parser for it, then go for it. + if (config.parser && parsers[mime.type]) { + + // If a specific parser was requested, make sure we don't parse other types. + var parser_name = config.parser.toString().toLowerCase(); + if (['xml', 'json'].indexOf(parser_name) == -1 || parsers[mime.type].name == parser_name) { + + // OK, so either we're parsing all content types or the one requested matches. + out.parser = parsers[mime.type].name; + pipeline.push(parsers[mime.type].fn()); + + // Set objectMode on out stream to improve performance. + out._writableState.objectMode = true; + out._readableState.objectMode = true; + } + + // If we're not parsing, and unless decoding was disabled, we'll try + // decoding non UTF-8 bodies to UTF-8, using the iconv-lite library. + } else if (text_response && config.decode_response && mime.charset) { + pipeline.push(decoder(mime.charset)); + } + + // And `out` is the stream we finally push the decoded/parsed output to. + pipeline.push(out); + + // Now, release the kraken! + pump_streams([resp].concat(pipeline), function(err) { + if (err) debug(err) + + // on node v8.x, if an error ocurrs on the receiving end, + // then we want to abort the request to avoid having dangling sockets + if (err && err.message == 'write after end') request.destroy(); + }); + + // If the user has requested and output file, pipe the output stream to it. + // In stream mode, we will still get the response stream to play with. + if (config.output && resp.statusCode == 200) { + + // for some reason, simply piping resp to the writable stream doesn't + // work all the time (stream gets cut in the middle with no warning). + // so we'll manually need to do the readable/write(chunk) trick. + var file = fs.createWriteStream(config.output); + file.on('error', had_error); + + out.on('end', function() { + if (file.writable) file.end(); + }); + + file.on('close', function() { + delete out.file; + }) + + out.on('readable', function() { + var chunk; + while ((chunk = this.read()) !== null) { + if (file.writable) file.write(chunk); + + // if callback was requested, also push it to resp.body + if (resp.body) resp.body.push(chunk); + } + }) + + out.file = file; + } + + // Only aggregate the full body if a callback was requested. + if (callback) { + resp.raw = []; + resp.body = []; + resp.bytes = 0; + + // Gather and count the amount of (raw) bytes using a PassThrough stream. + var clean_pipe = new stream.PassThrough(); + + clean_pipe.on('readable', function() { + var chunk; + while ((chunk = this.read()) != null) { + resp.bytes += chunk.length; + resp.raw.push(chunk); + } + }) + + pump_streams([resp, clean_pipe], function(err) { + if (err) debug(err); + }); + + // Listen on the 'readable' event to aggregate the chunks, but only if + // file output wasn't requested. Otherwise we'd have two stream readers. + if (!config.output || resp.statusCode != 200) { + out.on('readable', function() { + var chunk; + while ((chunk = this.read()) !== null) { + // We're either pushing buffers or objects, never strings. + if (typeof chunk == 'string') chunk = Buffer.from(chunk); + + // Push all chunks to resp.body. We'll bind them in resp.end(). + resp.body.push(chunk); + } + }) + } + } + + // And set the .body property once all data is in. + out.on('end', function() { + if (resp.body) { // callback mode + + // we want to be able to access to the raw data later, so keep a reference. + resp.raw = Buffer.concat(resp.raw); + + // if parse was successful, we should have an array with one object + if (resp.body[0] !== undefined && !Buffer.isBuffer(resp.body[0])) { + + // that's our body right there. + resp.body = resp.body[0]; + + // set the parser property on our response. we may want to check. + if (out.parser) resp.parser = out.parser; + + } else { // we got one or several buffers. string or binary. + resp.body = Buffer.concat(resp.body); + + // if we're here and parsed is true, it means we tried to but it didn't work. + // so given that we got a text response, let's stringify it. + if (text_response || out.parser) { + resp.body = resp.body.toString(); + } + } + } + + // if an output file is being written to, make sure the callback + // is triggered after all data has been written to it. + if (out.file) { + out.file.on('close', function() { + done(null, resp); + }) + } else { // elvis has left the building. + done(null, resp); + } + + }); + + // out.on('error', function(err) { + // had_error(err); + // if (err.code == 'ERR_STREAM_DESTROYED' || err.code == 'ERR_STREAM_PREMATURE_CLOSE') { + // request.abort(); + // } + // }) + + }); // end request call + + // unless open_timeout was disabled, set a timeout to abort the request. + set_timeout('open', config.open_timeout); + + // handle errors on the request object. things might get bumpy. + request.on('error', had_error); + + // make sure timer is cleared if request is aborted (issue #257) + request.once('abort', function() { + if (timer) clearTimeout(timer); + }) + + // handle socket 'end' event to ensure we don't get delayed EPIPE errors. + request.once('socket', function(socket) { + if (socket.connecting) { + socket.once('connect', function() { + set_timeout('response', config.response_timeout); + }) + } else { + set_timeout('response', config.response_timeout); + } + + // socket.once('close', function(e) { + // console.log('socket closed!', e); + // }) + + if (!socket.on_socket_end) { + socket.on_socket_end = on_socket_end; + socket.once('end', function() { process.nextTick(on_socket_end.bind(socket)) }); + } + }) + + if (post_data) { + if (is_stream(post_data)) { + pump_streams([post_data, request], function(err) { + if (err) debug(err); + }); + } else { + request.write(post_data, config.encoding); + request.end(); + } + } else { + request.end(); + } + + out.abort = function() { request.abort() }; // easier access + out.request = request; + return out; +} + +////////////////////////////////////////// +// exports + +if (typeof Promise !== 'undefined') { + module.exports = function() { + var verb, args = [].slice.call(arguments); + + if (args[0].match(/\.|\//)) // first argument looks like a URL + verb = (args.length > 2) ? 'post' : 'get'; + else + verb = args.shift(); + + if (verb.match(/get|head/i) && args.length == 2) + args.splice(1, 0, null); // assume no data if head/get with two args (url, options) + + return new Promise(function(resolve, reject) { + module.exports.request(verb, args[0], args[1], args[2], function(err, resp) { + return err ? reject(err) : resolve(resp); + }); + }) + } +} + +module.exports.version = version; + +module.exports.defaults = function(obj) { + for (var key in obj) { + var target_key = aliased.options[key] || key; + + if (defaults.hasOwnProperty(target_key) && typeof obj[key] != 'undefined') { + if (target_key != 'parse_response' && target_key != 'proxy') { + // ensure type matches the original, except for proxy/parse_response that can be null/bool or string + var valid_type = defaults[target_key].constructor.name; + + if (obj[key].constructor.name != valid_type) + throw new TypeError('Invalid type for ' + key + ', should be ' + valid_type); + } + defaults[target_key] = obj[key]; + } else { + throw new Error('Invalid property for defaults:' + target_key); + } + } + + return defaults; +} + +'head get'.split(' ').forEach(function(method) { + module.exports[method] = function(uri, options, callback) { + return new Needle(method, uri, null, options, callback).start(); + } +}) + +'post put patch delete'.split(' ').forEach(function(method) { + module.exports[method] = function(uri, data, options, callback) { + return new Needle(method, uri, data, options, callback).start(); + } +}) + +module.exports.request = function(method, uri, data, opts, callback) { + return new Needle(method, uri, data, opts, callback).start(); +}; diff --git a/node_modules/needle/lib/parsers.js b/node_modules/needle/lib/parsers.js new file mode 100644 index 0000000000000000000000000000000000000000..3da72871029f66c3b6779be299d0517f6dc659ea --- /dev/null +++ b/node_modules/needle/lib/parsers.js @@ -0,0 +1,121 @@ +////////////////////////////////////////// +// Defines mappings between content-type +// and the appropriate parsers. +////////////////////////////////////////// + +var Transform = require('stream').Transform; +var sax = require('sax'); + +function parseXML(str, cb) { + var obj, current, parser = sax.parser(true, { trim: true, lowercase: true }) + parser.onerror = parser.onend = done; + + function done(err) { + parser.onerror = parser.onend = function() { } + cb(err, obj) + } + + function newElement(name, attributes) { + return { + name: name || '', + value: '', + attributes: attributes || {}, + children: [] + } + } + + parser.oncdata = parser.ontext = function(t) { + if (current) current.value += t + } + + parser.onopentag = function(node) { + var element = newElement(node.name, node.attributes) + if (current) { + element.parent = current + current.children.push(element) + } else { // root object + obj = element + } + + current = element + }; + + parser.onclosetag = function() { + if (typeof current.parent !== 'undefined') { + var just_closed = current + current = current.parent + delete just_closed.parent + } + } + + parser.write(str).close() +} + +function parserFactory(name, fn) { + + function parser() { + var chunks = [], + stream = new Transform({ objectMode: true }); + + // Buffer all our data + stream._transform = function(chunk, encoding, done) { + chunks.push(chunk); + done(); + } + + // And call the parser when all is there. + stream._flush = function(done) { + var self = this, + data = Buffer.concat(chunks); + + try { + fn(data, function(err, result) { + if (err) throw err; + self.push(result); + }); + } catch (err) { + self.push(data); // just pass the original data + } finally { + done(); + } + } + + return stream; + } + + return { fn: parser, name: name }; +} + +var parsers = {} + +function buildParser(name, types, fn) { + var parser = parserFactory(name, fn); + types.forEach(function(type) { + parsers[type] = parser; + }) +} + +buildParser('json', [ + 'application/json', + 'text/javascript', + 'application/vnd.api+json' +], function(buffer, cb) { + var err, data; + try { data = JSON.parse(buffer); } catch (e) { err = e; } + cb(err, data); +}); + +buildParser('xml', [ + 'text/xml', + 'application/xml', + 'application/rdf+xml', + 'application/rss+xml', + 'application/atom+xml' +], function(buffer, cb) { + parseXML(buffer.toString(), function(err, obj) { + cb(err, obj) + }) +}); + +module.exports = parsers; +module.exports.use = buildParser; diff --git a/node_modules/needle/lib/querystring.js b/node_modules/needle/lib/querystring.js new file mode 100644 index 0000000000000000000000000000000000000000..e58cc426fe0ad6af28838b60c8fedbb4b9a02d1f --- /dev/null +++ b/node_modules/needle/lib/querystring.js @@ -0,0 +1,49 @@ +// based on the qs module, but handles null objects as expected +// fixes by Tomas Pollak. + +var toString = Object.prototype.toString; + +function stringify(obj, prefix) { + if (prefix && (obj === null || typeof obj == 'undefined')) { + return prefix + '='; + } else if (toString.call(obj) == '[object Array]') { + return stringifyArray(obj, prefix); + } else if (toString.call(obj) == '[object Object]') { + return stringifyObject(obj, prefix); + } else if (toString.call(obj) == '[object Date]') { + return obj.toISOString(); + } else if (prefix) { // string inside array or hash + return prefix + '=' + encodeURIComponent(String(obj)); + } else if (String(obj).indexOf('=') !== -1) { // string with equal sign + return String(obj); + } else { + throw new TypeError('Cannot build a querystring out of: ' + obj); + } +}; + +function stringifyArray(arr, prefix) { + var ret = []; + + for (var i = 0, len = arr.length; i < len; i++) { + if (prefix) + ret.push(stringify(arr[i], prefix + '[]')); + else + ret.push(stringify(arr[i])); + } + + return ret.join('&'); +} + +function stringifyObject(obj, prefix) { + var ret = []; + + Object.keys(obj).forEach(function(key) { + ret.push(stringify(obj[key], prefix + ? prefix + '[' + encodeURIComponent(key) + ']' + : encodeURIComponent(key))); + }) + + return ret.join('&'); +} + +exports.build = stringify; diff --git a/node_modules/needle/license.txt b/node_modules/needle/license.txt new file mode 100644 index 0000000000000000000000000000000000000000..fb245f39b923e20aa6bb2c90a170e509fbbf834c --- /dev/null +++ b/node_modules/needle/license.txt @@ -0,0 +1,19 @@ +Copyright (c) Fork, Ltd. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/needle/node_modules/debug/CHANGELOG.md b/node_modules/needle/node_modules/debug/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..820d21e3322b9d2778786ea743dd5e818991d595 --- /dev/null +++ b/node_modules/needle/node_modules/debug/CHANGELOG.md @@ -0,0 +1,395 @@ + +3.1.0 / 2017-09-26 +================== + + * Add `DEBUG_HIDE_DATE` env var (#486) + * Remove ReDoS regexp in %o formatter (#504) + * Remove "component" from package.json + * Remove `component.json` + * Ignore package-lock.json + * Examples: fix colors printout + * Fix: browser detection + * Fix: spelling mistake (#496, @EdwardBetts) + +3.0.1 / 2017-08-24 +================== + + * Fix: Disable colors in Edge and Internet Explorer (#489) + +3.0.0 / 2017-08-08 +================== + + * Breaking: Remove DEBUG_FD (#406) + * Breaking: Use `Date#toISOString()` instead to `Date#toUTCString()` when output is not a TTY (#418) + * Breaking: Make millisecond timer namespace specific and allow 'always enabled' output (#408) + * Addition: document `enabled` flag (#465) + * Addition: add 256 colors mode (#481) + * Addition: `enabled()` updates existing debug instances, add `destroy()` function (#440) + * Update: component: update "ms" to v2.0.0 + * Update: separate the Node and Browser tests in Travis-CI + * Update: refactor Readme, fixed documentation, added "Namespace Colors" section, redid screenshots + * Update: separate Node.js and web browser examples for organization + * Update: update "browserify" to v14.4.0 + * Fix: fix Readme typo (#473) + +2.6.9 / 2017-09-22 +================== + + * remove ReDoS regexp in %o formatter (#504) + +2.6.8 / 2017-05-18 +================== + + * Fix: Check for undefined on browser globals (#462, @marbemac) + +2.6.7 / 2017-05-16 +================== + + * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) + * Fix: Inline extend function in node implementation (#452, @dougwilson) + * Docs: Fix typo (#455, @msasad) + +2.6.5 / 2017-04-27 +================== + + * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) + * Misc: clean up browser reference checks (#447, @thebigredgeek) + * Misc: add npm-debug.log to .gitignore (@thebigredgeek) + + +2.6.4 / 2017-04-20 +================== + + * Fix: bug that would occur if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) + * Chore: ignore bower.json in npm installations. (#437, @joaovieira) + * Misc: update "ms" to v0.7.3 (@tootallnate) + +2.6.3 / 2017-03-13 +================== + + * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) + * Docs: Changelog fix (@thebigredgeek) + +2.6.2 / 2017-03-10 +================== + + * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) + * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) + * Docs: Add Slackin invite badge (@tootallnate) + +2.6.1 / 2017-02-10 +================== + + * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error + * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) + * Fix: IE8 "Expected identifier" error (#414, @vgoma) + * Fix: Namespaces would not disable once enabled (#409, @musikov) + +2.6.0 / 2016-12-28 +================== + + * Fix: added better null pointer checks for browser useColors (@thebigredgeek) + * Improvement: removed explicit `window.debug` export (#404, @tootallnate) + * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) + +2.5.2 / 2016-12-25 +================== + + * Fix: reference error on window within webworkers (#393, @KlausTrainer) + * Docs: fixed README typo (#391, @lurch) + * Docs: added notice about v3 api discussion (@thebigredgeek) + +2.5.1 / 2016-12-20 +================== + + * Fix: babel-core compatibility + +2.5.0 / 2016-12-20 +================== + + * Fix: wrong reference in bower file (@thebigredgeek) + * Fix: webworker compatibility (@thebigredgeek) + * Fix: output formatting issue (#388, @kribblo) + * Fix: babel-loader compatibility (#383, @escwald) + * Misc: removed built asset from repo and publications (@thebigredgeek) + * Misc: moved source files to /src (#378, @yamikuronue) + * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) + * Test: coveralls integration (#378, @yamikuronue) + * Docs: simplified language in the opening paragraph (#373, @yamikuronue) + +2.4.5 / 2016-12-17 +================== + + * Fix: `navigator` undefined in Rhino (#376, @jochenberger) + * Fix: custom log function (#379, @hsiliev) + * Improvement: bit of cleanup + linting fixes (@thebigredgeek) + * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) + * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) + +2.4.4 / 2016-12-14 +================== + + * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) + +2.4.3 / 2016-12-14 +================== + + * Fix: navigation.userAgent error for react native (#364, @escwald) + +2.4.2 / 2016-12-14 +================== + + * Fix: browser colors (#367, @tootallnate) + * Misc: travis ci integration (@thebigredgeek) + * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) + +2.4.1 / 2016-12-13 +================== + + * Fix: typo that broke the package (#356) + +2.4.0 / 2016-12-13 +================== + + * Fix: bower.json references unbuilt src entry point (#342, @justmatt) + * Fix: revert "handle regex special characters" (@tootallnate) + * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) + * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) + * Improvement: allow colors in workers (#335, @botverse) + * Improvement: use same color for same namespace. (#338, @lchenay) + +2.3.3 / 2016-11-09 +================== + + * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) + * Fix: Returning `localStorage` saved values (#331, Levi Thomason) + * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) + +2.3.2 / 2016-11-09 +================== + + * Fix: be super-safe in index.js as well (@TooTallNate) + * Fix: should check whether process exists (Tom Newby) + +2.3.1 / 2016-11-09 +================== + + * Fix: Added electron compatibility (#324, @paulcbetts) + * Improvement: Added performance optimizations (@tootallnate) + * Readme: Corrected PowerShell environment variable example (#252, @gimre) + * Misc: Removed yarn lock file from source control (#321, @fengmk2) + +2.3.0 / 2016-11-07 +================== + + * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) + * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) + * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) + * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) + * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) + * Package: Update "ms" to 0.7.2 (#315, @DevSide) + * Package: removed superfluous version property from bower.json (#207 @kkirsche) + * Readme: fix USE_COLORS to DEBUG_COLORS + * Readme: Doc fixes for format string sugar (#269, @mlucool) + * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) + * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) + * Readme: better docs for browser support (#224, @matthewmueller) + * Tooling: Added yarn integration for development (#317, @thebigredgeek) + * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) + * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) + * Misc: Updated contributors (@thebigredgeek) + +2.2.0 / 2015-05-09 +================== + + * package: update "ms" to v0.7.1 (#202, @dougwilson) + * README: add logging to file example (#193, @DanielOchoa) + * README: fixed a typo (#191, @amir-s) + * browser: expose `storage` (#190, @stephenmathieson) + * Makefile: add a `distclean` target (#189, @stephenmathieson) + +2.1.3 / 2015-03-13 +================== + + * Updated stdout/stderr example (#186) + * Updated example/stdout.js to match debug current behaviour + * Renamed example/stderr.js to stdout.js + * Update Readme.md (#184) + * replace high intensity foreground color for bold (#182, #183) + +2.1.2 / 2015-03-01 +================== + + * dist: recompile + * update "ms" to v0.7.0 + * package: update "browserify" to v9.0.3 + * component: fix "ms.js" repo location + * changed bower package name + * updated documentation about using debug in a browser + * fix: security error on safari (#167, #168, @yields) + +2.1.1 / 2014-12-29 +================== + + * browser: use `typeof` to check for `console` existence + * browser: check for `console.log` truthiness (fix IE 8/9) + * browser: add support for Chrome apps + * Readme: added Windows usage remarks + * Add `bower.json` to properly support bower install + +2.1.0 / 2014-10-15 +================== + + * node: implement `DEBUG_FD` env variable support + * package: update "browserify" to v6.1.0 + * package: add "license" field to package.json (#135, @panuhorsmalahti) + +2.0.0 / 2014-09-01 +================== + + * package: update "browserify" to v5.11.0 + * node: use stderr rather than stdout for logging (#29, @stephenmathieson) + +1.0.4 / 2014-07-15 +================== + + * dist: recompile + * example: remove `console.info()` log usage + * example: add "Content-Type" UTF-8 header to browser example + * browser: place %c marker after the space character + * browser: reset the "content" color via `color: inherit` + * browser: add colors support for Firefox >= v31 + * debug: prefer an instance `log()` function over the global one (#119) + * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) + +1.0.3 / 2014-07-09 +================== + + * Add support for multiple wildcards in namespaces (#122, @seegno) + * browser: fix lint + +1.0.2 / 2014-06-10 +================== + + * browser: update color palette (#113, @gscottolson) + * common: make console logging function configurable (#108, @timoxley) + * node: fix %o colors on old node <= 0.8.x + * Makefile: find node path using shell/which (#109, @timoxley) + +1.0.1 / 2014-06-06 +================== + + * browser: use `removeItem()` to clear localStorage + * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) + * package: add "contributors" section + * node: fix comment typo + * README: list authors + +1.0.0 / 2014-06-04 +================== + + * make ms diff be global, not be scope + * debug: ignore empty strings in enable() + * node: make DEBUG_COLORS able to disable coloring + * *: export the `colors` array + * npmignore: don't publish the `dist` dir + * Makefile: refactor to use browserify + * package: add "browserify" as a dev dependency + * Readme: add Web Inspector Colors section + * node: reset terminal color for the debug content + * node: map "%o" to `util.inspect()` + * browser: map "%j" to `JSON.stringify()` + * debug: add custom "formatters" + * debug: use "ms" module for humanizing the diff + * Readme: add "bash" syntax highlighting + * browser: add Firebug color support + * browser: add colors for WebKit browsers + * node: apply log to `console` + * rewrite: abstract common logic for Node & browsers + * add .jshintrc file + +0.8.1 / 2014-04-14 +================== + + * package: re-add the "component" section + +0.8.0 / 2014-03-30 +================== + + * add `enable()` method for nodejs. Closes #27 + * change from stderr to stdout + * remove unnecessary index.js file + +0.7.4 / 2013-11-13 +================== + + * remove "browserify" key from package.json (fixes something in browserify) + +0.7.3 / 2013-10-30 +================== + + * fix: catch localStorage security error when cookies are blocked (Chrome) + * add debug(err) support. Closes #46 + * add .browser prop to package.json. Closes #42 + +0.7.2 / 2013-02-06 +================== + + * fix package.json + * fix: Mobile Safari (private mode) is broken with debug + * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript + +0.7.1 / 2013-02-05 +================== + + * add repository URL to package.json + * add DEBUG_COLORED to force colored output + * add browserify support + * fix component. Closes #24 + +0.7.0 / 2012-05-04 +================== + + * Added .component to package.json + * Added debug.component.js build + +0.6.0 / 2012-03-16 +================== + + * Added support for "-" prefix in DEBUG [Vinay Pulim] + * Added `.enabled` flag to the node version [TooTallNate] + +0.5.0 / 2012-02-02 +================== + + * Added: humanize diffs. Closes #8 + * Added `debug.disable()` to the CS variant + * Removed padding. Closes #10 + * Fixed: persist client-side variant again. Closes #9 + +0.4.0 / 2012-02-01 +================== + + * Added browser variant support for older browsers [TooTallNate] + * Added `debug.enable('project:*')` to browser variant [TooTallNate] + * Added padding to diff (moved it to the right) + +0.3.0 / 2012-01-26 +================== + + * Added millisecond diff when isatty, otherwise UTC string + +0.2.0 / 2012-01-22 +================== + + * Added wildcard support + +0.1.0 / 2011-12-02 +================== + + * Added: remove colors unless stderr isatty [TooTallNate] + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/needle/node_modules/debug/LICENSE b/node_modules/needle/node_modules/debug/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..658c933d28255e8c716899789e8c0f846e5dc125 --- /dev/null +++ b/node_modules/needle/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/needle/node_modules/debug/README.md b/node_modules/needle/node_modules/debug/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0ee7634ddd0a4a6337fe7677e99ba78cd626fa07 --- /dev/null +++ b/node_modules/needle/node_modules/debug/README.md @@ -0,0 +1,437 @@ +# debug +[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny JavaScript debugging utility modelled after Node.js core's debugging +technique. Works in Node.js and web browsers. + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example [_app.js_](./examples/node/app.js): + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %o', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example [_worker.js_](./examples/node/worker.js): + +```js +var a = require('debug')('worker:a') + , b = require('debug')('worker:b'); + +function work() { + a('doing lots of uninteresting work'); + setTimeout(work, Math.random() * 1000); +} + +work(); + +function workb() { + b('doing some work'); + setTimeout(workb, Math.random() * 2000); +} + +workb(); +``` + +The `DEBUG` environment variable is then used to enable these based on space or +comma-delimited names. + +Here are some examples: + +screen shot 2017-08-08 at 12 53 04 pm +screen shot 2017-08-08 at 12 53 38 pm +screen shot 2017-08-08 at 12 53 25 pm + +#### Windows command prompt notes + +##### CMD + +On Windows the environment variable is set using the `set` command. + +```cmd +set DEBUG=*,-not_this +``` + +Example: + +```cmd +set DEBUG=* & node app.js +``` + +##### PowerShell (VS Code default) + +PowerShell uses different syntax to set environment variables. + +```cmd +$env:DEBUG = "*,-not_this" +``` + +Example: + +```cmd +$env:DEBUG='app';node app.js +``` + +Then, run the program to be debugged as usual. + +npm script example: +```js + "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", +``` + +## Namespace Colors + +Every debug instance has a color generated for it based on its namespace name. +This helps when visually parsing the debug output to identify which debug instance +a debug line belongs to. + +#### Node.js + +In Node.js, colors are enabled when stderr is a TTY. You also _should_ install +the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, +otherwise debug will only use a small handful of basic colors. + + + +#### Web Browser + +Colors are also enabled on "Web Inspectors" that understand the `%c` formatting +option. These are WebKit web inspectors, Firefox ([since version +31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) +and the Firebug plugin for Firefox (any version). + + + + +## Millisecond diff + +When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + + +When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: + + + + +## Conventions + +If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. + +## Wildcards + +The `*` character may be used as a wildcard. Suppose for example your library has +debuggers named "connect:bodyParser", "connect:compress", "connect:session", +instead of listing all three with +`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do +`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + +You can also exclude specific debuggers by prefixing them with a "-" character. +For example, `DEBUG=*,-connect:*` would include all debuggers except those +starting with "connect:". + +## Environment Variables + +When running through Node.js, you can set a few environment variables that will +change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + +__Note:__ The environment variables beginning with `DEBUG_` end up being +converted into an Options object that gets used with `%o`/`%O` formatters. +See the Node.js documentation for +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +## Formatters + +Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. +Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + + +### Custom formatters + +You can add custom formatters by extending the `debug.formatters` object. +For example, if you wanted to add support for rendering a Buffer as hex with +`%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + + +## Browser Support + +You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), +or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), +if you don't want to build it yourself. + +Debug's enable state is currently persisted by `localStorage`. +Consider the situation shown below where you have `worker:a` and `worker:b`, +and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example [_stdout.js_](./examples/node/stdout.js): + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + +## Extend +You can simply extend debugger +```js +const log = require('debug')('auth'); + +//creates new debug instance with extended namespace +const logSign = log.extend('sign'); +const logLogin = log.extend('login'); + +log('hello'); // auth hello +logSign('hello'); //auth:sign hello +logLogin('hello'); //auth:login hello +``` + +## Set dynamically + +You can also enable debug dynamically by calling the `enable()` method : + +```js +let debug = require('debug'); + +console.log(1, debug.enabled('test')); + +debug.enable('test'); +console.log(2, debug.enabled('test')); + +debug.disable(); +console.log(3, debug.enabled('test')); + +``` + +print : +``` +1 false +2 true +3 false +``` + +Usage : +`enable(namespaces)` +`namespaces` can include modes separated by a colon and wildcards. + +Note that calling `enable()` completely overrides previously set DEBUG variable : + +``` +$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' +=> false +``` + +## Checking whether a debug target is enabled + +After you've created a debug instance, you can determine whether or not it is +enabled by checking the `enabled` property: + +```javascript +const debug = require('debug')('http'); + +if (debug.enabled) { + // do stuff... +} +``` + +You can also manually toggle this property to force the debug instance to be +enabled or disabled. + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/needle/node_modules/debug/node.js b/node_modules/needle/node_modules/debug/node.js new file mode 100644 index 0000000000000000000000000000000000000000..7fc36fe6dbecbfd41530c5a490cc738ec2968653 --- /dev/null +++ b/node_modules/needle/node_modules/debug/node.js @@ -0,0 +1 @@ +module.exports = require('./src/node'); diff --git a/node_modules/needle/node_modules/debug/package.json b/node_modules/needle/node_modules/debug/package.json new file mode 100644 index 0000000000000000000000000000000000000000..191c8154787cb9f8662967d4c4f8f9f3467a2bbf --- /dev/null +++ b/node_modules/needle/node_modules/debug/package.json @@ -0,0 +1,51 @@ +{ + "name": "debug", + "version": "3.2.7", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "files": [ + "src", + "node.js", + "dist/debug.js", + "LICENSE", + "README.md" + ], + "author": "TJ Holowaychuk ", + "contributors": [ + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne " + ], + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + }, + "devDependencies": { + "@babel/cli": "^7.0.0", + "@babel/core": "^7.0.0", + "@babel/preset-env": "^7.0.0", + "browserify": "14.4.0", + "chai": "^3.5.0", + "concurrently": "^3.1.0", + "coveralls": "^3.0.2", + "istanbul": "^0.4.5", + "karma": "^3.0.0", + "karma-chai": "^0.1.0", + "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", + "mocha": "^5.2.0", + "mocha-lcov-reporter": "^1.2.0", + "rimraf": "^2.5.4", + "xo": "^0.23.0" + }, + "main": "./src/index.js", + "browser": "./src/browser.js", + "unpkg": "./dist/debug.js" +} diff --git a/node_modules/needle/node_modules/debug/src/browser.js b/node_modules/needle/node_modules/debug/src/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..c924b0ac4d4882e4a72a116436ed17a487c2fc05 --- /dev/null +++ b/node_modules/needle/node_modules/debug/src/browser.js @@ -0,0 +1,180 @@ +"use strict"; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +/** + * Colors. + */ + +exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33']; +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ +// eslint-disable-next-line complexity + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } // Internet Explorer and Edge do not support colors. + + + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + + + return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); +} +/** + * Colorize log arguments if enabled. + * + * @api public + */ + + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function (match) { + if (match === '%%') { + return; + } + + index++; + + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + args.splice(lastC, 0, c); +} +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + + +function log() { + var _console; + + // This hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments); +} +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + + +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) {// Swallow + // XXX (@Qix-) should we be logging these? + } +} +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + + +function load() { + var r; + + try { + r = exports.storage.getItem('debug'); + } catch (error) {} // Swallow + // XXX (@Qix-) should we be logging these? + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + + + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) {// Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = require('./common')(exports); +var formatters = module.exports.formatters; +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; + diff --git a/node_modules/needle/node_modules/debug/src/common.js b/node_modules/needle/node_modules/debug/src/common.js new file mode 100644 index 0000000000000000000000000000000000000000..e0de3fb530f1c2ea33c4c65bcfd39b98a53600d7 --- /dev/null +++ b/node_modules/needle/node_modules/debug/src/common.js @@ -0,0 +1,249 @@ +"use strict"; + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require('ms'); + Object.keys(env).forEach(function (key) { + createDebug[key] = env[key]; + }); + /** + * Active `debug` instances. + */ + + createDebug.instances = []; + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + + createDebug.formatters = {}; + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + + function selectColor(namespace) { + var hash = 0; + + for (var i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + + createDebug.selectColor = selectColor; + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + + function createDebug(namespace) { + var prevTime; + + function debug() { + // Disabled? + if (!debug.enabled) { + return; + } + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var self = debug; // Set `diff` timestamp + + var curr = Number(new Date()); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } // Apply any `formatters` transformations + + + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return match; + } + + index++; + var formatter = createDebug.formatters[format]; + + if (typeof formatter === 'function') { + var val = args[index]; + match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` + + args.splice(index, 1); + index--; + } + + return match; + }); // Apply env-specific formatting (colors, etc.) + + createDebug.formatArgs.call(self, args); + var logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = createDebug.enabled(namespace); + debug.useColors = createDebug.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; + debug.extend = extend; // Debug.formatArgs = formatArgs; + // debug.rawLog = rawLog; + // env-specific initialization logic for debug instances + + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + createDebug.instances.push(debug); + return debug; + } + + function destroy() { + var index = createDebug.instances.indexOf(this); + + if (index !== -1) { + createDebug.instances.splice(index, 1); + return true; + } + + return false; + } + + function extend(namespace, delimiter) { + return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + } + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + + + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.names = []; + createDebug.skips = []; + var i; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + + for (i = 0; i < createDebug.instances.length; i++) { + var instance = createDebug.instances[i]; + instance.enabled = createDebug.enabled(instance.namespace); + } + } + /** + * Disable debug output. + * + * @api public + */ + + + function disable() { + createDebug.enable(''); + } + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + + + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + var i; + var len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + + + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + + return val; + } + + createDebug.enable(createDebug.load()); + return createDebug; +} + +module.exports = setup; + diff --git a/node_modules/needle/node_modules/debug/src/index.js b/node_modules/needle/node_modules/debug/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..021731593ac517b224bddda8c450bac52889843a --- /dev/null +++ b/node_modules/needle/node_modules/debug/src/index.js @@ -0,0 +1,12 @@ +"use strict"; + +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} + diff --git a/node_modules/needle/node_modules/debug/src/node.js b/node_modules/needle/node_modules/debug/src/node.js new file mode 100644 index 0000000000000000000000000000000000000000..1e6a5f16aecdd38a2bfb607f3d82e299f7624f9a --- /dev/null +++ b/node_modules/needle/node_modules/debug/src/node.js @@ -0,0 +1,177 @@ +"use strict"; + +/** + * Module dependencies. + */ +var tty = require('tty'); + +var util = require('util'); +/** + * This is the Node.js implementation of `debug()`. + */ + + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + var supportsColor = require('supports-color'); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221]; + } +} catch (error) {} // Swallow - we only care if `supports-color` is available; it doesn't have to be. + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // Camel-case + var prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, function (_, k) { + return k.toUpperCase(); + }); // Coerce string value into JS value + + var val = process.env[key]; + + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); +} +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + + +function formatArgs(args) { + var name = this.namespace, + useColors = this.useColors; + + if (useColors) { + var c = this.color; + var colorCode = "\x1B[3" + (c < 8 ? c : '8;5;' + c); + var prefix = " ".concat(colorCode, ";1m").concat(name, " \x1B[0m"); + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + + return new Date().toISOString() + ' '; +} +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + + +function log() { + return process.stderr.write(util.format.apply(util, arguments) + '\n'); +} +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + + +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + + +function load() { + return process.env.DEBUG; +} +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + + +function init(debug) { + debug.inspectOpts = {}; + var keys = Object.keys(exports.inspectOpts); + + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = require('./common')(exports); +var formatters = module.exports.formatters; +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(function (str) { return str.trim(); }) + .join(' '); +}; +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + diff --git a/node_modules/needle/package.json b/node_modules/needle/package.json new file mode 100644 index 0000000000000000000000000000000000000000..195f48f8f975c9485a0f9fab9b81d3ea47f3d253 --- /dev/null +++ b/node_modules/needle/package.json @@ -0,0 +1,71 @@ +{ + "name": "needle", + "version": "2.9.1", + "description": "The leanest and most handsome HTTP client in the Nodelands.", + "keywords": [ + "http", + "https", + "simple", + "request", + "client", + "multipart", + "upload", + "proxy", + "deflate", + "timeout", + "charset", + "iconv", + "cookie", + "redirect" + ], + "tags": [ + "http", + "https", + "simple", + "request", + "client", + "multipart", + "upload", + "proxy", + "deflate", + "timeout", + "charset", + "iconv", + "cookie", + "redirect" + ], + "author": "Tomás Pollak ", + "repository": { + "type": "git", + "url": "https://github.com/tomas/needle.git" + }, + "dependencies": { + "debug": "^3.2.6", + "iconv-lite": "^0.4.4", + "sax": "^1.2.4" + }, + "devDependencies": { + "JSONStream": "^1.3.5", + "jschardet": "^1.6.0", + "mocha": "^5.2.0", + "pump": "^3.0.0", + "q": "^1.5.1", + "should": "^13.2.3", + "sinon": "^2.3.0", + "xml2js": "^0.4.19" + }, + "scripts": { + "test": "mocha test" + }, + "directories": { + "lib": "./lib" + }, + "main": "./lib/needle", + "bin": { + "needle": "./bin/needle" + }, + "license": "MIT", + "engines": { + "node": ">= 4.4.x" + } +} diff --git a/node_modules/needle/test/auth_digest_spec.js b/node_modules/needle/test/auth_digest_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..58799f21c10480f23e653cc7f10bd64456995844 --- /dev/null +++ b/node_modules/needle/test/auth_digest_spec.js @@ -0,0 +1,192 @@ +var needle = require('../'), + auth = require('../lib/auth'), + sinon = require('sinon'), + should = require('should'), + http = require('http'), + helpers = require('./helpers'); + +var createHash = require('crypto').createHash; + +function md5(string) { + return createHash('md5').update(string).digest('hex'); +} + +function parse_header(header) { + var challenge = {}, + matches = header.match(/([a-z0-9_-]+)="?([a-z0-9=\/\.@\s-\+]+)"?/gi); + + for (var i = 0, l = matches.length; i < l; i++) { + var parts = matches[i].split('='), + key = parts.shift(), + val = parts.join('=').replace(/^"/, '').replace(/"$/, ''); + + challenge[key] = val; + } + + return challenge; +} + +describe('auth_digest', function() { + describe('With qop (RFC 2617)', function() { + it('should generate a proper header', function() { + // from https://tools.ietf.org/html/rfc2617 + var performDigest = function() { + var header = 'Digest realm="testrealm@host.com", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41"'; + var user = 'Mufasa'; + var pass = 'Circle Of Life'; + var method = 'get'; + var path = '/dir/index.html'; + + var updatedHeader = auth.digest(header, user, pass, method, path); + var parsedUpdatedHeader = parse_header(updatedHeader); + + var ha1 = md5(user + ':' + parsedUpdatedHeader.realm + ':' + pass); + var ha2 = md5(method.toUpperCase() + ':' + path); + var expectedResponse = md5([ + ha1, + parsedUpdatedHeader.nonce, + parsedUpdatedHeader.nc, + parsedUpdatedHeader.cnonce, + parsedUpdatedHeader.qop, + ha2 + ].join(':')); + + return { + header: updatedHeader, + parsed: parsedUpdatedHeader, + expectedResponse: expectedResponse, + } + } + + const result = performDigest(); + + (result.header).should + .match(/qop="auth"/) + .match(/uri="\/dir\/index.html"/) + .match(/opaque="5ccc069c403ebaf9f0171e9517f40e41"/) + .match(/realm="testrealm@host\.com"/) + .match(/response=/) + .match(/nc=/) + .match(/nonce=/) + .match(/cnonce=/); + + (result.parsed.response).should.be.eql(result.expectedResponse); + }); + }); + + describe('With plus character in nonce header', function() { + it('should generate a proper header', function() { + // from https://tools.ietf.org/html/rfc2617 + var performDigest = function() { + var header = 'Digest realm="testrealm@host.com", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f6+00bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41"'; + var user = 'Mufasa'; + var pass = 'Circle Of Life'; + var method = 'get'; + var path = '/dir/index.html'; + + var updatedHeader = auth.digest(header, user, pass, method, path); + var parsedUpdatedHeader = parse_header(updatedHeader); + + var ha1 = md5(user + ':' + parsedUpdatedHeader.realm + ':' + pass); + var ha2 = md5(method.toUpperCase() + ':' + path); + var expectedResponse = md5([ + ha1, + parsedUpdatedHeader.nonce, + parsedUpdatedHeader.nc, + parsedUpdatedHeader.cnonce, + parsedUpdatedHeader.qop, + ha2 + ].join(':')); + + return { + header: updatedHeader, + parsed: parsedUpdatedHeader, + expectedResponse: expectedResponse, + } + } + + const result = performDigest(); + + (result.header).should + .match(/nonce="dcd98b7102dd2f0e8b11d0f6\+00bfb0c093"/) + }); + }); + + describe('With brackets in realm header', function() { + it('should generate a proper header', function() { + // from https://tools.ietf.org/html/rfc2617 + var performDigest = function() { + var header = 'Digest qop="auth", realm="IP Camera(76475)", nonce="4e4449794d575269597a706b5a575935595441324d673d3d", stale="FALSE", Basic realm="IP Camera(76475)"'; + var user = 'Mufasa'; + var pass = 'Circle Of Life'; + var method = 'get'; + var path = '/dir/index.html'; + + var updatedHeader = auth.digest(header, user, pass, method, path); + var parsedUpdatedHeader = parse_header(updatedHeader); + + var ha1 = md5(user + ':' + parsedUpdatedHeader.realm + ':' + pass); + var ha2 = md5(method.toUpperCase() + ':' + path); + var expectedResponse = md5([ + ha1, + parsedUpdatedHeader.nonce, + parsedUpdatedHeader.nc, + parsedUpdatedHeader.cnonce, + parsedUpdatedHeader.qop, + ha2 + ].join(':')); + + return { + header: updatedHeader, + parsed: parsedUpdatedHeader, + expectedResponse: expectedResponse, + } + } + + const result = performDigest(); + + (result.header).should + .match(/realm="IP Camera\(76475\)"/) + }); + }); + + describe('Without qop (RFC 2617)', function() { + it('should generate a proper header', function() { + // from https://tools.ietf.org/html/rfc2069 + var performDigest = function() { + var header = 'Digest realm="testrealm@host.com", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41"'; + var user = 'Mufasa'; + var pass = 'Circle Of Life'; + var method = 'get'; + var path = '/dir/index.html'; + + var updatedHeader = auth.digest(header, user, pass, method, path); + var parsedUpdatedHeader = parse_header(updatedHeader); + + var ha1 = md5(user + ':' + parsedUpdatedHeader.realm + ':' + pass); + var ha2 = md5(method.toUpperCase() + ':' + path); + var expectedResponse = md5([ha1, parsedUpdatedHeader.nonce, ha2].join(':')); + + return { + header: updatedHeader, + parsed: parsedUpdatedHeader, + expectedResponse: expectedResponse, + } + } + + const result = performDigest(); + + (result.header).should + .not.match(/qop=/) + .match(/uri="\/dir\/index.html"/) + .match(/opaque="5ccc069c403ebaf9f0171e9517f40e41"/) + .match(/realm="testrealm@host\.com"/) + .match(/response=/) + .not.match(/nc=/) + .match(/nonce=/) + .not.match(/cnonce=/); + + (result.parsed.response).should.be.eql(result.expectedResponse); + }); + }); +}) \ No newline at end of file diff --git a/node_modules/needle/test/basic_auth_spec.js b/node_modules/needle/test/basic_auth_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..343f1db0e9640b5db952f3a10ec89734611cdd22 --- /dev/null +++ b/node_modules/needle/test/basic_auth_spec.js @@ -0,0 +1,196 @@ +var helpers = require('./helpers'), + should = require('should'), + needle = require('./../'), + server; + +var port = 7707; + +describe('Basic Auth', function() { + + before(function(done) { + server = helpers.server({ port: port }, done); + }) + + after(function(done) { + server.close(done); + }) + + ///////////////// helpers + + var get_auth = function(header) { + var token = header.split(/\s+/).pop(); + return token && Buffer.from(token, 'base64').toString().split(':'); + } + + describe('when neither username or password are passed', function() { + + it('doesnt send any Authorization headers', function(done) { + needle.get('localhost:' + port, { parse: true }, function(err, resp) { + var sent_headers = resp.body.headers; + Object.keys(sent_headers).should.not.containEql('authorization'); + done(); + }) + }) + + }) + + describe('when username is an empty string, and password is a valid string', function() { + + var opts = { username: '', password: 'foobar', parse: true }; + + it('doesnt send any Authorization headers', function(done) { + needle.get('localhost:' + port, { parse: true }, function(err, resp) { + var sent_headers = resp.body.headers; + Object.keys(sent_headers).should.not.containEql('authorization'); + done(); + }) + }) + + }); + + describe('when username is a valid string, but no username is passed', function() { + + var opts = { username: 'foobar', parse: true }; + + it('sends Authorization header', function(done) { + needle.get('localhost:' + port, opts, function(err, resp) { + var sent_headers = resp.body.headers; + Object.keys(sent_headers).should.containEql('authorization'); + done(); + }) + }) + + it('Basic Auth only includes username, without colon', function(done) { + needle.get('localhost:' + port, opts, function(err, resp) { + var sent_headers = resp.body.headers; + var auth = get_auth(sent_headers['authorization']); + auth[0].should.equal('foobar'); + auth.should.have.lengthOf(1); + done(); + }) + }) + + }) + + describe('when username is a valid string, and password is null', function() { + + var opts = { username: 'foobar', password: null, parse: true }; + + it('sends Authorization header', function(done) { + needle.get('localhost:' + port, opts, function(err, resp) { + var sent_headers = resp.body.headers; + Object.keys(sent_headers).should.containEql('authorization'); + done(); + }) + }) + + it('Basic Auth only includes both username and password', function(done) { + needle.get('localhost:' + port, opts, function(err, resp) { + var sent_headers = resp.body.headers; + var auth = get_auth(sent_headers['authorization']); + auth[0].should.equal('foobar'); + auth[1].should.equal(''); + done(); + }) + }) + + }) + + describe('when username is a valid string, and password is an empty string', function() { + + var opts = { username: 'foobar', password: '', parse: true }; + + it('sends Authorization header', function(done) { + needle.get('localhost:' + port, opts, function(err, resp) { + var sent_headers = resp.body.headers; + Object.keys(sent_headers).should.containEql('authorization'); + done(); + }) + }) + + it('Basic Auth only includes both username and password', function(done) { + needle.get('localhost:' + port, opts, function(err, resp) { + var sent_headers = resp.body.headers; + var auth = get_auth(sent_headers['authorization']); + auth[0].should.equal('foobar'); + auth[1].should.equal(''); + auth.should.have.lengthOf(2); + done(); + }) + }) + + }) + + describe('when username AND password are non empty strings', function() { + + var opts = { username: 'foobar', password: 'jakub', parse: true }; + + it('sends Authorization header', function(done) { + needle.get('localhost:' + port, opts, function(err, resp) { + var sent_headers = resp.body.headers; + Object.keys(sent_headers).should.containEql('authorization'); + done(); + }) + }) + + it('Basic Auth only includes both user and password', function(done) { + needle.get('localhost:' + port, opts, function(err, resp) { + var sent_headers = resp.body.headers; + var auth = get_auth(sent_headers['authorization']); + auth[0].should.equal('foobar'); + auth[1].should.equal('jakub'); + auth.should.have.lengthOf(2); + done(); + }) + }) + + }) + + describe('URL with @ but not username/pass', function() { + it('doesnt send Authorization header', function(done) { + var url = 'localhost:' + port + '/abc/@def/xyz.zip'; + + needle.get(url, {}, function(err, resp) { + var sent_headers = resp.body.headers; + Object.keys(sent_headers).should.not.containEql('authorization'); + done(); + }) + }) + + it('sends user:pass headers if passed via options', function(done) { + var url = 'localhost:' + port + '/abc/@def/xyz.zip'; + + needle.get(url, { username: 'foo' }, function(err, resp) { + var sent_headers = resp.body.headers; + Object.keys(sent_headers).should.containEql('authorization'); + sent_headers['authorization'].should.eql('Basic Zm9v') + done(); + }) + }) + }) + + describe('when username/password are included in URL', function() { + var opts = { parse: true }; + + it('sends Authorization header', function(done) { + needle.get('foobar:jakub@localhost:' + port, opts, function(err, resp) { + var sent_headers = resp.body.headers; + Object.keys(sent_headers).should.containEql('authorization'); + done(); + }) + }) + + it('Basic Auth only includes both user and password', function(done) { + needle.get('foobar:jakub@localhost:' + port, opts, function(err, resp) { + var sent_headers = resp.body.headers; + var auth = get_auth(sent_headers['authorization']); + auth[0].should.equal('foobar'); + auth[1].should.equal('jakub'); + auth.should.have.lengthOf(2); + done(); + }) + }) + + }) + +}) diff --git a/node_modules/needle/test/compression_spec.js b/node_modules/needle/test/compression_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..227ae09355b02de975157c0a386ff78b65e1ce22 --- /dev/null +++ b/node_modules/needle/test/compression_spec.js @@ -0,0 +1,112 @@ +var should = require('should'), + needle = require('./../'), + http = require('http'), + zlib = require('zlib'), + stream = require('stream'), + port = 11123, + server; + +describe('compression', function(){ + + require.bind(null, 'zlib').should.not.throw() + + var jsonData = '{"foo":"bar"}'; + + describe('when server supports compression', function(){ + + before(function(){ + server = http.createServer(function(req, res) { + var raw = new stream.PassThrough(); + + var acceptEncoding = req.headers['accept-encoding']; + if (!acceptEncoding) { + acceptEncoding = ''; + } + + if (acceptEncoding.match(/\bdeflate\b/)) { + res.setHeader('Content-Encoding', 'deflate'); + raw.pipe(zlib.createDeflate()).pipe(res); + } else if (acceptEncoding.match(/\bgzip\b/)) { + res.setHeader('Content-Encoding', 'gzip'); + raw.pipe(zlib.createGzip()).pipe(res); + } else if (acceptEncoding.match(/\bbr\b/)) { + res.setHeader('Content-Encoding', 'br'); + raw.pipe(zlib.createBrotliCompress()).pipe(res); + } else { + raw.pipe(res); + } + + res.setHeader('Content-Type', 'application/json') + if (req.headers['with-bad']) { + res.end('foo'); // end, no deflate data + } else { + raw.end(jsonData) + } + + }) + + server.listen(port); + }); + + after(function(done){ + server.close(done); + }) + + describe('and client requests no compression', function() { + it('should have the body decompressed', function(done){ + needle.get('localhost:' + port, function(err, response, body){ + should.ifError(err); + body.should.have.property('foo', 'bar'); + response.bytes.should.equal(jsonData.length); + done(); + }) + }) + }) + + describe('and client requests gzip compression', function() { + it('should have the body decompressed', function(done){ + needle.get('localhost:' + port, {headers: {'Accept-Encoding': 'gzip'}}, function(err, response, body){ + should.ifError(err); + body.should.have.property('foo', 'bar'); + response.bytes.should.not.equal(jsonData.length); + done(); + }) + }) + }) + + describe('and client requests deflate compression', function() { + it('should have the body decompressed', function(done){ + needle.get('localhost:' + port, {headers: {'Accept-Encoding': 'deflate'}}, function(err, response, body){ + should.ifError(err); + body.should.have.property('foo', 'bar'); + response.bytes.should.not.equal(jsonData.length); + done(); + }) + }) + + it('should rethrow errors from decompressors', function(done){ + needle.get('localhost:' + port, {headers: {'Accept-Encoding': 'deflate', 'With-Bad': 'true'}}, function(err, response, body) { + should.exist(err); + err.message.should.equal("incorrect header check"); + err.code.should.equal("Z_DATA_ERROR") + done(); + }) + }) + }) + + describe('and client requests brotli compression', function() { + it('should have the body decompressed', function(done){ + // Skip this test if Brotli is not supported + if (typeof zlib.BrotliDecompress !== 'function') { + return done(); + } + needle.get('localhost:' + port, {headers: {'Accept-Encoding': 'br'}}, function(err, response, body){ + should.ifError(err); + body.should.have.property('foo', 'bar'); + response.bytes.should.not.equal(jsonData.length); + done(); + }) + }) + }) + }) +}) diff --git a/node_modules/needle/test/cookies_spec.js b/node_modules/needle/test/cookies_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..745f4c71f81fc3fe7f1b8dc903d50e09a3cc2eb8 --- /dev/null +++ b/node_modules/needle/test/cookies_spec.js @@ -0,0 +1,396 @@ +var needle = require('../'), + cookies = require('../lib/cookies'), + sinon = require('sinon'), + http = require('http'), + should = require('should'); + +var WEIRD_COOKIE_NAME = 'wc', + BASE64_COOKIE_NAME = 'bc', + FORBIDDEN_COOKIE_NAME = 'fc', + NUMBER_COOKIE_NAME = 'nc'; + +var WEIRD_COOKIE_VALUE = '!\'*+#()&-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~', + BASE64_COOKIE_VALUE = 'Y29va2llCg==', + FORBIDDEN_COOKIE_VALUE = ' ;"\\,', + NUMBER_COOKIE_VALUE = 12354342; + +var NO_COOKIES_TEST_PORT = 11112, + ALL_COOKIES_TEST_PORT = 11113; + +describe('cookies', function() { + + var setCookieHeader, headers, server, opts; + + function decode(str) { + return decodeURIComponent(str); + } + + function encode(str) { + str = str.toString().replace(/[\x00-\x1F\x7F]/g, encodeURIComponent); + return str.replace(/[\s\"\,;\\%]/g, encodeURIComponent); + } + + before(function() { + setCookieHeader = [ + WEIRD_COOKIE_NAME + '=' + encode(WEIRD_COOKIE_VALUE) + ';', + BASE64_COOKIE_NAME + '=' + encode(BASE64_COOKIE_VALUE) + ';', + FORBIDDEN_COOKIE_NAME + '=' + encode(FORBIDDEN_COOKIE_VALUE) + ';', + NUMBER_COOKIE_NAME + '=' + encode(NUMBER_COOKIE_VALUE) + ';' + ]; + }); + + before(function(done) { + serverAllCookies = http.createServer(function(req, res) { + res.setHeader('Content-Type', 'text/html'); + res.setHeader('Set-Cookie', setCookieHeader); + res.end('200'); + }).listen(ALL_COOKIES_TEST_PORT, done); + }); + + after(function(done) { + serverAllCookies.close(done); + }); + + describe('with default options', function() { + it('no cookie header is set on request', function(done) { + needle.get( + 'localhost:' + ALL_COOKIES_TEST_PORT, function(err, response) { + should.not.exist(response.req._headers.cookie); + done(); + }); + }); + }); + + describe('if response does not contain cookies', function() { + before(function(done) { + serverNoCookies = http.createServer(function(req, res) { + res.setHeader('Content-Type', 'text/html'); + res.end('200'); + }).listen(NO_COOKIES_TEST_PORT, done); + }); + + it('response.cookies is undefined', function(done) { + needle.get( + 'localhost:' + NO_COOKIES_TEST_PORT, function(error, response) { + should.not.exist(response.cookies); + done(); + }); + }); + + after(function(done) { + serverNoCookies.close(done); + }); + }); + + describe('if response contains cookies', function() { + + it('puts them on resp.cookies', function(done) { + needle.get( + 'localhost:' + ALL_COOKIES_TEST_PORT, function(error, response) { + response.should.have.property('cookies'); + done(); + }); + }); + + it('parses them as a object', function(done) { + needle.get( + 'localhost:' + ALL_COOKIES_TEST_PORT, function(error, response) { + response.cookies.should.be.an.instanceOf(Object) + .and.have.property(WEIRD_COOKIE_NAME); + response.cookies.should.have.property(BASE64_COOKIE_NAME); + response.cookies.should.have.property(FORBIDDEN_COOKIE_NAME); + response.cookies.should.have.property(NUMBER_COOKIE_NAME); + done(); + }); + }); + + it('must decode it', function(done) { + needle.get( + 'localhost:' + ALL_COOKIES_TEST_PORT, function(error, response) { + response.cookies.wc.should.be.eql(WEIRD_COOKIE_VALUE); + response.cookies.bc.should.be.eql(BASE64_COOKIE_VALUE); + response.cookies.fc.should.be.eql(FORBIDDEN_COOKIE_VALUE); + response.cookies.nc.should.be.eql(NUMBER_COOKIE_VALUE.toString()); + done(); + }); + }); + + describe('when a cookie value is invalid', function() { + + before(function() { + setCookieHeader = [ + 'geo_city=%D1%E0%ED%EA%F2-%CF%E5%F2%E5%F0%E1%F3%F0%E3' + ]; + }) + + it('doesnt blow up', function(done) { + needle.get('localhost:' + ALL_COOKIES_TEST_PORT, function(error, response) { + should.not.exist(error) + var whatever = 'efbfbdefbfbdefbfbdefbfbdefbfbd2defbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbdefbfbd'; + Buffer.from(response.cookies.geo_city).toString('hex').should.eql(whatever) + done(); + }); + }) + + }) + + describe('and response is a redirect', function() { + + var redirectServer, testPort = 22222; + var requestCookies = []; + + var responseCookies = [ + [ // first req + WEIRD_COOKIE_NAME + '=' + encode(WEIRD_COOKIE_VALUE) + ';', + BASE64_COOKIE_NAME + '=' + encode(BASE64_COOKIE_VALUE) + ';', + 'FOO=123;' + ], [ // second req + FORBIDDEN_COOKIE_NAME + '=' + encode(FORBIDDEN_COOKIE_VALUE) + ';', + NUMBER_COOKIE_NAME + '=' + encode(NUMBER_COOKIE_VALUE) + ';' + ], [ // third red + 'FOO=BAR;' + ] + ] + + before(function(done) { + redirectServer = http.createServer(function(req, res) { + var number = parseInt(req.url.replace('/', '')); + var nextUrl = 'http://' + 'localhost:' + testPort + '/' + (number + 1); + + if (number == 0) requestCookies = []; // reset + requestCookies.push(req.headers['cookie']); + + if (responseCookies[number]) { // we should send cookies for this request + res.statusCode = 302; + res.setHeader('Set-Cookie', responseCookies[number]); + res.setHeader('Location', nextUrl); + } else if (number == 3) { + res.statusCode = 302; // redirect but without cookies + res.setHeader('Location', nextUrl); + } + + res.end('OK'); + }).listen(22222, done); + }); + + after(function(done) { + redirectServer.close(done); + }) + + describe('and follow_set_cookies is false', function() { + + describe('with original request cookie', function() { + + var opts = { + follow_set_cookies: false, + follow_max: 4, + cookies: { 'xxx': 123 } + }; + + it('request cookie is not passed to redirects', function(done) { + needle.get('localhost:' + testPort + '/0', opts, function(err, resp) { + requestCookies.should.eql(["xxx=123", undefined, undefined, undefined, undefined]) + done(); + }); + }); + + it('response cookies are not passed either', function(done) { + needle.get('localhost:' + testPort + '/0', opts, function(err, resp) { + should.not.exist(resp.cookies); + done(); + }); + }); + + }) + + describe('without original request cookie', function() { + + var opts = { + follow_set_cookies: false, + follow_max: 4, + }; + + it('no request cookies are sent', function(done) { + needle.get('localhost:' + testPort + '/0', opts, function(err, resp) { + requestCookies.should.eql([undefined, undefined, undefined, undefined, undefined]) + done(); + }); + }); + + it('response cookies are not passed either', function(done) { + needle.get('localhost:' + testPort + '/0', opts, function(err, resp) { + should.not.exist(resp.cookies); + done(); + }); + }); + + }) + + }); + + describe('and follow_set_cookies is true', function() { + + describe('with original request cookie', function() { + + var opts = { + follow_set_cookies: true, + follow_max: 4, + cookies: { 'xxx': 123 } + }; + + it('request cookie is passed passed to redirects, and response cookies are added too', function(done) { + needle.get('localhost:' + testPort + '/0', opts, function(err, resp) { + requestCookies.should.eql([ + "xxx=123", + "xxx=123; wc=!'*+#()&-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~; bc=Y29va2llCg==; FOO=123", + "xxx=123; wc=!\'*+#()&-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~; bc=Y29va2llCg==; FOO=123; fc=%20%3B%22%5C%2C; nc=12354342", + "xxx=123; wc=!\'*+#()&-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~; bc=Y29va2llCg==; FOO=BAR; fc=%20%3B%22%5C%2C; nc=12354342", + "xxx=123; wc=!\'*+#()&-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~; bc=Y29va2llCg==; FOO=BAR; fc=%20%3B%22%5C%2C; nc=12354342" + ]) + done(); + }); + }); + + it('response cookies are passed as well', function(done) { + needle.get('localhost:' + testPort + '/0', opts, function(err, resp) { + resp.cookies.should.have.property(WEIRD_COOKIE_NAME); + resp.cookies.should.have.property(BASE64_COOKIE_NAME); + resp.cookies.should.have.property(FORBIDDEN_COOKIE_NAME); + resp.cookies.should.have.property(NUMBER_COOKIE_NAME); + resp.cookies.should.have.property('FOO'); + resp.cookies.FOO.should.eql('BAR'); // should overwrite previous one + done(); + }); + }); + + }) + + describe('without original request cookie', function() { + + var opts = { + follow_set_cookies: true, + follow_max: 4, + }; + + it('response cookies are passed to redirects', function(done) { + needle.get('localhost:' + testPort + '/0', opts, function(err, resp) { + requestCookies.should.eql([ + undefined, + "wc=!'*+#()&-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~; bc=Y29va2llCg==; FOO=123", + "wc=!\'*+#()&-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~; bc=Y29va2llCg==; FOO=123; fc=%20%3B%22%5C%2C; nc=12354342", + "wc=!\'*+#()&-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~; bc=Y29va2llCg==; FOO=BAR; fc=%20%3B%22%5C%2C; nc=12354342", + "wc=!\'*+#()&-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~; bc=Y29va2llCg==; FOO=BAR; fc=%20%3B%22%5C%2C; nc=12354342" + ]) + done(); + }); + }); + + it('response cookies are passed as well', function(done) { + needle.get('localhost:' + testPort + '/0', opts, function(err, resp) { + // resp.cookies.should.have.property(WEIRD_COOKIE_NAME); + // resp.cookies.should.have.property(BASE64_COOKIE_NAME); + // resp.cookies.should.have.property(FORBIDDEN_COOKIE_NAME); + // resp.cookies.should.have.property(NUMBER_COOKIE_NAME); + // resp.cookies.should.have.property('FOO'); + // resp.cookies.FOO.should.eql('BAR'); // should overwrite previous one + done(); + }); + }); + + }) + + }); + }); + + describe('with parse_cookies = false', function() { + it('does not parse them', function(done) { + needle.get( + 'localhost:' + ALL_COOKIES_TEST_PORT, { parse_cookies: false }, function(error, response) { + should.not.exist(response.cookies); + done(); + }); + }); + }); + }); + + describe('if request contains cookie header', function() { + var opts = { + cookies: {} + }; + + before(function() { + opts.cookies[WEIRD_COOKIE_NAME] = WEIRD_COOKIE_VALUE; + opts.cookies[BASE64_COOKIE_NAME] = BASE64_COOKIE_VALUE; + opts.cookies[FORBIDDEN_COOKIE_NAME] = FORBIDDEN_COOKIE_VALUE; + opts.cookies[NUMBER_COOKIE_NAME] = NUMBER_COOKIE_VALUE; + }); + + it('must be a valid cookie string', function(done) { + var COOKIE_PAIR = /^([^=\s]+)\s*=\s*("?)\s*(.*)\s*\2\s*$/; + + var full_header = [ + WEIRD_COOKIE_NAME + '=' + WEIRD_COOKIE_VALUE, + BASE64_COOKIE_NAME + '=' + BASE64_COOKIE_VALUE, + FORBIDDEN_COOKIE_NAME + '=' + encode(FORBIDDEN_COOKIE_VALUE), + NUMBER_COOKIE_NAME + '=' + NUMBER_COOKIE_VALUE + ].join('; ') + + needle.get('localhost:' + ALL_COOKIES_TEST_PORT, opts, function(error, response) { + var cookieString = response.req._headers.cookie; + cookieString.should.be.type('string'); + + cookieString.split(/\s*;\s*/).forEach(function(pair) { + COOKIE_PAIR.test(pair).should.be.exactly(true); + }); + + cookieString.should.be.exactly(full_header); + done(); + }); + }); + + it('dont have to encode allowed characters', function(done) { + var COOKIE_PAIR = /^([^=\s]+)\s*=\s*("?)\s*(.*)\s*\2\s*$/, + KEY_INDEX = 1, + VALUE_INEX = 3; + + needle.get('localhost:' + ALL_COOKIES_TEST_PORT, opts, function(error, response) { + var cookieObj = {}, + cookieString = response.req._headers.cookie; + + cookieString.split(/\s*;\s*/).forEach(function(str) { + var pair = COOKIE_PAIR.exec(str); + cookieObj[pair[KEY_INDEX]] = pair[VALUE_INEX]; + }); + + cookieObj[WEIRD_COOKIE_NAME].should.be.exactly(WEIRD_COOKIE_VALUE); + cookieObj[BASE64_COOKIE_NAME].should.be.exactly(BASE64_COOKIE_VALUE); + done(); + }); + }); + + it('must encode forbidden characters', function(done) { + var COOKIE_PAIR = /^([^=\s]+)\s*=\s*("?)\s*(.*)\s*\2\s*$/, + KEY_INDEX = 1, + VALUE_INEX = 3; + + needle.get('localhost:' + ALL_COOKIES_TEST_PORT, opts, function(error, response) { + var cookieObj = {}, + cookieString = response.req._headers.cookie; + + cookieString.split(/\s*;\s*/).forEach(function(str) { + var pair = COOKIE_PAIR.exec(str); + cookieObj[pair[KEY_INDEX]] = pair[VALUE_INEX]; + }); + + cookieObj[FORBIDDEN_COOKIE_NAME].should.not.be.eql( + FORBIDDEN_COOKIE_VALUE); + cookieObj[FORBIDDEN_COOKIE_NAME].should.be.exactly( + encode(FORBIDDEN_COOKIE_VALUE)); + cookieObj[FORBIDDEN_COOKIE_NAME].should.be.exactly( + encodeURIComponent(FORBIDDEN_COOKIE_VALUE)); + done(); + }); + }); + }); + +}); diff --git a/node_modules/needle/test/decoder_spec.js b/node_modules/needle/test/decoder_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..db38821df4b25789f9ef6ffc4a42507c58836a1a --- /dev/null +++ b/node_modules/needle/test/decoder_spec.js @@ -0,0 +1,121 @@ +var should = require('should'), + needle = require('./../'), + Q = require('q'), + chardet = require('jschardet'), + helpers = require('./helpers'); + +describe('character encoding', function() { + + var url; + this.timeout(5000); + + describe('Given content-type: "text/html; charset=EUC-JP"', function() { + + before(function() { + url = 'http://www.nina.jp/server/slackware/webapp/tomcat_charset.html'; + }) + + describe('with decode = false', function() { + + it('does not decode', function(done) { + + needle.get(url, { decode: false }, function(err, resp) { + resp.body.should.be.a.String; + chardet.detect(resp.body).encoding.should.eql('windows-1252'); + resp.body.indexOf('EUCを使う').should.eql(-1); + done(); + }) + + }) + + }) + + describe('with decode = true', function() { + + it('decodes', function(done) { + + needle.get(url, { decode: true }, function(err, resp) { + resp.body.should.be.a.String; + chardet.detect(resp.body).encoding.should.eql('ascii'); + resp.body.indexOf('EUCを使う').should.not.eql(-1); + done(); + }) + + }) + + }) + + }) + + describe('Given content-type: "text/html but file is charset: gb2312', function() { + + it('encodes to UTF-8', function(done) { + + // Our Needle wrapper that requests a chinese website. + var task = Q.nbind(needle.get, needle, 'http://www.chinesetop100.com/'); + + // Different instantiations of this task + var tasks = [Q.fcall(task, {decode: true}), + Q.fcall(task, {decode: false})]; + + var results = tasks.map(function(task) { + return task.then(function(obj) { + return obj[0].body; + }); + }); + + // Execute all requests concurrently + Q.all(results).done(function(bodies) { + + var charsets = [ + chardet.detect(bodies[0]).encoding, + chardet.detect(bodies[1]).encoding, + ] + + // We wanted to decode our first stream as specified by options + charsets[0].should.equal('ascii'); + bodies[0].indexOf('全球中文网站前二十强').should.not.equal(-1); + + // But not our second stream + charsets[1].should.equal('windows-1252'); + bodies[1].indexOf('全球中文网站前二十强').should.equal(-1); + + done(); + }); + }) + }) + + describe('Given content-type: "text/html"', function () { + + var server, + port = 54321, + text = 'Magyarországi Fióktelepe' + + before(function(done) { + server = helpers.server({ + port: port, + response: text, + headers: { 'Content-Type': 'text/html' } + }, done); + }) + + after(function(done) { + server.close(done) + }) + + describe('with decode = false', function () { + it('decodes by default to utf-8', function (done) { + + needle.get('http://localhost:' + port, { decode: false }, function (err, resp) { + resp.body.should.be.a.String; + chardet.detect(resp.body).encoding.should.eql('ISO-8859-2'); + resp.body.should.eql('Magyarországi Fióktelepe') + done(); + }) + + }) + + }) + + }) +}) diff --git a/node_modules/needle/test/errors_spec.js b/node_modules/needle/test/errors_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..c1956814468a3fe5e184f1b19ad1f7a7ea0be3cc --- /dev/null +++ b/node_modules/needle/test/errors_spec.js @@ -0,0 +1,272 @@ +var needle = require('../'), + sinon = require('sinon'), + should = require('should'), + http = require('http'), + Emitter = require('events').EventEmitter, + helpers = require('./helpers'); + +var get_catch = function(url, opts) { + var err; + try { + needle.get(url, opts); + } catch(e) { + err = e; + } + return err; +} + +describe('errors', function() { + + after(function(done) { + setTimeout(done, 100) + }) + + describe('when host does not exist', function() { + + var url = 'http://unexistinghost/foo'; + + describe('with callback', function() { + + it('does not throw', function() { + var ex = get_catch(url); + should.not.exist(ex); + }) + + it('callbacks an error', function(done) { + needle.get(url, function(err) { + err.should.be.a.Error; + done(); + }) + }) + + it('error should be ENOTFOUND or EADDRINFO or EAI_AGAIN', function(done) { + needle.get(url, function(err) { + err.code.should.match(/ENOTFOUND|EADDRINFO|EAI_AGAIN/) + done(); + }) + }) + + it('does not callback a response', function(done) { + needle.get(url, function(err, resp) { + should.not.exist(resp); + done(); + }) + }) + + it('does not emit an error event', function(done) { + var emitted = false; + var req = needle.get(url, function(err, resp) { }) + + req.on('error', function() { + emitted = true; + }) + + setTimeout(function() { + emitted.should.eql(false); + done(); + }, 100); + }) + + }) + + describe('without callback', function() { + + it('does not throw', function() { + var ex = get_catch(url); + should.not.exist(ex); + }) + + it('emits end event once, with error', function(done) { + var callcount = 0, + stream = needle.get(url); + + stream.on('done', function(err) { + err.code.should.match(/ENOTFOUND|EADDRINFO|EAI_AGAIN/) + callcount++; + }) + + setTimeout(function() { + callcount.should.equal(1); + done(); + }, 200) + }) + + it('does not emit a readable event', function(done) { + var called = false, + stream = needle.get(url); + + stream.on('readable', function() { + called = true; + }) + + stream.on('done', function(err) { + called.should.be.false; + done(); + }) + }) + + it('does not emit an error event', function(done) { + var emitted = false, + stream = needle.get(url); + + stream.on('error', function() { + emitted = true; + }) + + stream.on('done', function(err) { + emitted.should.eql(false); + done(); + }) + }) + + }) + + }) + + describe('when request times out waiting for response', function() { + + var server, + url = 'http://localhost:3333/foo'; + + var send_request = function(cb) { + return needle.get(url, { response_timeout: 200 }, cb); + } + + before(function() { + server = helpers.server({ port: 3333, wait: 1000 }); + }) + + after(function() { + server.close(); + }) + + describe('with callback', function() { + + it('aborts the request', function(done) { + + var time = new Date(); + + send_request(function(err) { + var timediff = (new Date() - time); + timediff.should.be.within(200, 300); + done(); + }) + + }) + + it('callbacks an error', function(done) { + send_request(function(err) { + err.should.be.a.Error; + done(); + }) + }) + + it('error should be ECONNRESET', function(done) { + send_request(function(err) { + err.code.should.equal('ECONNRESET') + done(); + }) + }) + + it('does not callback a response', function(done) { + send_request(function(err, resp) { + should.not.exist(resp); + done(); + }) + }) + + it('does not emit an error event', function(done) { + var emitted = false; + + var req = send_request(function(err, resp) { + should.not.exist(resp); + }) + + req.on('error', function() { + emitted = true; + }) + + setTimeout(function() { + emitted.should.eql(false); + done(); + }, 350); + }) + + }) + + describe('without callback', function() { + + it('emits done event once, with error', function(done) { + var error, + called = 0, + stream = send_request(); + + stream.on('done', function(err) { + err.code.should.equal('ECONNRESET'); + called++; + }) + + setTimeout(function() { + called.should.equal(1); + done(); + }, 250) + }) + + it('aborts the request', function(done) { + + var time = new Date(); + var stream = send_request(); + + stream.on('done', function(err) { + var timediff = (new Date() - time); + timediff.should.be.within(200, 300); + done(); + }) + + }) + + it('error should be ECONNRESET', function(done) { + var error, + stream = send_request(); + + stream.on('done', function(err) { + err.code.should.equal('ECONNRESET') + done(); + }) + }) + + it('does not emit a readable event', function(done) { + var called = false, + stream = send_request(); + + stream.on('readable', function() { + called = true; + }) + + stream.on('done', function(err) { + called.should.be.false; + done(); + }) + }) + + it('does not emit an error event', function(done) { + var emitted = false; + var stream = send_request(); + + stream.on('error', function() { + emitted = true; + }) + + stream.on('done', function(err) { + err.should.be.a.Error; + err.code.should.equal('ECONNRESET') + emitted.should.eql(false); + done(); + }) + }) + + }) + + }) + +}) diff --git a/node_modules/needle/test/headers_spec.js b/node_modules/needle/test/headers_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..a5c17e62d9e00ffd48e937b0fabe0278dad277ea --- /dev/null +++ b/node_modules/needle/test/headers_spec.js @@ -0,0 +1,203 @@ +var http = require('http'), + helpers = require('./helpers'), + should = require('should'); + +var port = 54321; + +describe('request headers', function() { + + var needle, + server, + existing_sockets, + original_defaultMaxSockets; + + before(function(done) { + setTimeout(function() { + existing_sockets = get_active_sockets().length; + server = helpers.server({ port: port }, done); + }, 100); + }) + + after(function(done) { + server.close(done); + }) + + function send_request(opts, cb) { + needle.get('http://localhost:' + port, opts, cb); + } + + function get_active_sockets() { + var handles = process._getActiveHandles(); + + return handles.filter(function(el) { + if (el.constructor.name.toString() == 'Socket') { + return el.destroyed !== true; + } + }) + } + + describe('old node versions (<0.11.4) with persistent keep-alive connections', function() { + + before(function() { + delete require.cache[require.resolve('..')] // in case it was already loaded + original_defaultMaxSockets = http.Agent.defaultMaxSockets; + http.Agent.defaultMaxSockets = 5; + needle = require('..'); + }) + + after(function() { + http.Agent.defaultMaxSockets = original_defaultMaxSockets; + delete require.cache[require.resolve('..')] + }) + + describe('default options', function() { + + it('sends a Connection: close header', function(done) { + send_request({}, function(err, resp) { + resp.body.headers['connection'].should.eql('close'); + done(); + }) + }) + + it('no open sockets remain after request', function(done) { + send_request({}, function(err, resp) { + setTimeout(function() { + get_active_sockets().length.should.eql(existing_sockets); + done(); + }, 10) + }); + }) + + }) + + describe('passing connection: close', function() { + + it('sends a Connection: close header', function(done) { + send_request({ connection: 'close' }, function(err, resp) { + resp.body.headers['connection'].should.eql('close'); + done(); + }) + }) + + it('no open sockets remain after request', function(done) { + send_request({ connection: 'close' }, function(err, resp) { + setTimeout(function() { + get_active_sockets().length.should.eql(existing_sockets); + done(); + }, 10) + }); + }) + + }) + + describe('passing connection: keep-alive', function() { + + it('sends a Connection: keep-alive header (using options.headers.connection)', function(done) { + send_request({ headers: { connection: 'keep-alive' }}, function(err, resp) { + resp.body.headers['connection'].should.eql('keep-alive'); + done(); + }) + }) + + it('sends a Connection: keep-alive header (using options.connection)', function(done) { + send_request({ connection: 'keep-alive' }, function(err, resp) { + resp.body.headers['connection'].should.eql('keep-alive'); + done(); + }) + }) + + it('one open socket remain after request', function(done) { + send_request({ connection: 'keep-alive' }, function(err, resp) { + get_active_sockets().length.should.eql(existing_sockets + 1); + done(); + }); + }) + + }) + + }) + + describe('new node versions with smarter connection disposing', function() { + + before(function() { + delete require.cache[require.resolve('..')] + original_defaultMaxSockets = http.Agent.defaultMaxSockets; + http.Agent.defaultMaxSockets = Infinity; + needle = require('..'); + }) + + after(function() { + http.Agent.defaultMaxSockets = original_defaultMaxSockets; + delete require.cache[require.resolve('..')] + }) + + describe('default options', function() { + + // TODO: + // this is weird. by default, new node versions set a 'close' header + // while older versions set a keep-alive header + + it.skip('sets a Connection header', function(done) { + send_request({}, function(err, resp) { + // should.not.exist(resp.body.headers['connection']); + // done(); + }) + }) + + it.skip('one open sockets remain after request', function(done) { + send_request({}, function(err, resp) { + // get_active_sockets().length.should.eql(1); + // done(); + }); + }) + + }) + + describe('passing connection: close', function() { + + it('sends a Connection: close header', function(done) { + send_request({ connection: 'close' }, function(err, resp) { + resp.body.headers['connection'].should.eql('close'); + done(); + }) + }) + + it('no open sockets remain after request', function(done) { + send_request({ connection: 'close' }, function(err, resp) { + setTimeout(function() { + get_active_sockets().length.should.eql(existing_sockets); + done(); + }, 10); + }); + }) + + }) + + describe('passing connection: keep-alive', function() { + + it('sends a Connection: keep-alive header (using options.headers.connection)', function(done) { + send_request({ headers: { connection: 'keep-alive' }}, function(err, resp) { + resp.body.headers['connection'].should.eql('keep-alive'); + done(); + }) + }) + + it('sends a Connection: keep-alive header (using options.connection)', function(done) { + send_request({ connection: 'keep-alive' }, function(err, resp) { + resp.body.headers['connection'].should.eql('keep-alive'); + done(); + }) + }) + + it('one open socket remain after request', function(done) { + send_request({ connection: 'keep-alive' }, function(err, resp) { + get_active_sockets().length.should.eql(existing_sockets + 1); + done(); + }); + }) + + }) + + }) + +}) diff --git a/node_modules/needle/test/helpers.js b/node_modules/needle/test/helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..613ff5780ac590085b6938592cfa0d28d1389eaf --- /dev/null +++ b/node_modules/needle/test/helpers.js @@ -0,0 +1,74 @@ +var fs = require('fs'); + +var protocols = { + http : require('http'), + https : require('https') +} + +var keys = { + cert : fs.readFileSync(__dirname + '/keys/ssl.cert'), + key : fs.readFileSync(__dirname + '/keys/ssl.key') +} + +var helpers = {}; + +helpers.server = function(opts, cb) { + + var defaults = { + code : 200, + headers : {'Content-Type': 'application/json'} + } + + var mirror_response = function(req) { + return JSON.stringify({ + headers: req.headers, + body: req.body + }) + } + + var get = function(what) { + if (!opts[what]) + return defaults[what]; + + if (typeof opts[what] == 'function') + return opts[what](); // set them at runtime + else + return opts[what]; + } + + var finish = function(req, res) { + if (opts.handler) return opts.handler(req, res); + + res.writeHead(get('code'), get('headers')); + res.end(opts.response || mirror_response(req)); + } + + var handler = function(req, res) { + + req.setEncoding('utf8'); // get as string + req.body = ''; + req.on('data', function(str) { req.body += str }) + req.socket.on('error', function(e) { + // res.writeHead(500, {'Content-Type': 'text/plain'}); + // res.end('Error: ' + e.message); + }) + + setTimeout(function(){ + finish(req, res); + }, opts.wait || 0); + + }; + + var protocol = opts.protocol || 'http'; + var server; + + if (protocol == 'https') + server = protocols[protocol].createServer(keys, handler); + else + server = protocols[protocol].createServer(handler); + + server.listen(opts.port, cb); + return server; +} + +module.exports = helpers; \ No newline at end of file diff --git a/node_modules/needle/test/long_string_spec.js b/node_modules/needle/test/long_string_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..4f2fa7365da8262e8b08dbe2df1eabc90e37d1a9 --- /dev/null +++ b/node_modules/needle/test/long_string_spec.js @@ -0,0 +1,43 @@ +var needle = require('../'), + should = require('should'); + +describe('when posting a very long string', function() { + + this.timeout(20000); + + function get_string(length) { + var str = ''; + for (var i = 0; i < length; i++) { + str += 'x'; + } + return str; + } + + var major_version = process.version.split('.')[0]; + + it("shouldn't throw an EPIPE error out of nowhere", function(done) { + + // for some reason this test fails in Github Actions with Node v8.x + // although in my Linux box passes without issues + if (process.env.CI && (major_version == 'v8' || major_version == 'v6')) { + return done(); + } + + var error; + + function finished() { + setTimeout(function() { + should.not.exist(error); + done(); + }, 300); + } + + try { + needle.post('https://google.com', { data: get_string(Math.pow(2, 20)) }, finished) + } catch(e) { + error = e; + } + + }) + +}) diff --git a/node_modules/needle/test/mimetype.js b/node_modules/needle/test/mimetype.js new file mode 100644 index 0000000000000000000000000000000000000000..dbeaf2951de60b9e42a84482ddce11040e78fa93 --- /dev/null +++ b/node_modules/needle/test/mimetype.js @@ -0,0 +1,81 @@ +var should = require('should'), + needle = require('./../'), + helpers = require('./helpers'); + +describe('receiving json and xml content as string', function() { + + this.timeout(5000); + + ["text/plain", "application/json", "application/ld+json", "application/xml", "image/svg+xml"].forEach(function(mimetype, offset){ + + describe('Given content-type: "'+mimetype+'"', function () { + + var server, port = 54330+offset; + + before(function(done) { + server = helpers.server({ + port: port, + response: 'content', + headers: { 'Content-Type': mimetype } + }, done); + }) + + after(function(done) { + server.close(done) + }) + + describe('with parse = false', function () { + it('delivers by default as string', function (done) { + + needle.get('http://localhost:' + port, { parse: false }, function (err, resp) { + + resp.body.should.be.a.String; + (typeof resp.body).should.eql('string') + done(); + }) + + }) + + }) + + }) + + }); + + ["application/octet-stream", "image/png"].forEach(function(mimetype, offset){ + + describe('Given content-type: "'+mimetype+'"', function () { + + var server, port = 54340+offset; + + before(function(done) { + server = helpers.server({ + port: port, + response: 'content', + headers: { 'Content-Type': mimetype } + }, done); + }) + + after(function(done) { + server.close(done) + }) + + describe('with parse = false', function () { + it('delivers by default as Buffer', function (done) { + + needle.get('http://localhost:' + port, { parse: false }, function (err, resp) { + + resp.body.should.be.a.Buffer; + (resp.body instanceof Buffer).should.eql(true) + done(); + }) + + }) + + }) + + }) + + }) + +}) diff --git a/node_modules/needle/test/output_spec.js b/node_modules/needle/test/output_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..14fc5bb03f784d8c67f78753f51ba3322175bb3b --- /dev/null +++ b/node_modules/needle/test/output_spec.js @@ -0,0 +1,254 @@ +var should = require('should'), + needle = require('./../'), + http = require('http'), + sinon = require('sinon'), + stream = require('stream'), + fs = require('fs'), + port = 11111, + server; + +describe('with output option', function() { + + var server, handler, file = '/tmp/foobar.out'; + + function send_request_cb(where, cb) { + var url = 'http://localhost:' + port + '/whatever.file'; + return needle.get(url, { output: where }, cb); + } + + function send_request_stream(where, cb) { + var url = 'http://localhost:' + port + '/whatever.file'; + var stream = needle.get(url, { output: where }); + stream.on('end', cb); + } + + // this will only work in UNICES + function get_open_file_descriptors() { + var list = fs.readdirSync('/proc/self/fd'); + return list.length; + } + + var send_request = send_request_cb; + + before(function(){ + server = http.createServer(function(req, res) { + handler(req, res); + }).listen(port); + }); + + after(function() { + server.close(); + }) + + beforeEach(function() { + try { fs.unlinkSync(file) } catch(e) { }; + }) + + describe('and a 404 response', function() { + + before(function() { + handler = function(req, res) { + res.writeHead(404, {'Content-Type': 'text/plain' }); + res.end(); + } + }) + + it('doesnt attempt to write a file', function(done) { + var spy = sinon.spy(fs, 'createWriteStream'); + send_request(file, function(err, resp) { + resp.statusCode.should.eql(404); + spy.called.should.eql(false); + spy.restore(); + done(); + }) + }) + + it('doesnt actually write a file', function(done) { + send_request(file, function(err, resp) { + resp.statusCode.should.eql(404); + fs.existsSync(file).should.eql(false); + done(); + }) + }) + + }) + + describe('and a 200 response', function() { + + describe('for an empty response', function() { + + before(function() { + handler = function(req, res) { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end(); + } + }) + + it('uses a writableStream', function(done) { + var spy = sinon.spy(fs, 'createWriteStream'); + send_request(file, function(err, resp) { + resp.statusCode.should.eql(200); + spy.called.should.eql(true); + spy.restore(); + done(); + }) + }) + + it('writes a file', function(done) { + fs.existsSync(file).should.eql(false); + send_request(file, function(err, resp) { + fs.existsSync(file).should.eql(true); + done(); + }) + }) + + it('file is zero bytes in length', function(done) { + send_request(file, function(err, resp) { + fs.statSync(file).size.should.equal(0); + done(); + }) + }) + + if (process.platform != 'win32') { + it('closes the file descriptor', function(done) { + var open_descriptors = get_open_file_descriptors(); + send_request(file + Math.random(), function(err, resp) { + var current_descriptors = get_open_file_descriptors(); + open_descriptors.should.eql(current_descriptors); + done() + }) + }) + } + + }) + + describe('for a JSON response', function() { + + before(function() { + handler = function(req, res) { + res.writeHead(200, { 'Content-Type': 'application/javascript' }); + res.end(JSON.stringify({foo: 'bar'})); + } + }) + + it('uses a writableStream', function(done) { + var spy = sinon.spy(fs, 'createWriteStream'); + send_request(file, function(err, resp) { + resp.statusCode.should.eql(200); + spy.called.should.eql(true); + spy.restore(); + done(); + }) + }) + + it('writes a file', function(done) { + fs.existsSync(file).should.eql(false); + send_request(file, function(err, resp) { + fs.existsSync(file).should.eql(true); + done(); + }) + }) + + it('file size equals response length', function(done) { + send_request(file, function(err, resp) { + fs.statSync(file).size.should.equal(resp.bytes); + done(); + }) + }) + + it('response pipeline is honoured (JSON is decoded by default)', function(done) { + send_request_stream(file, function(err, resp) { + // we need to wait a bit since writing to config.output + // happens independently of needle's callback logic. + setTimeout(function() { + fs.readFileSync(file).toString().should.eql('{\"foo\":\"bar\"}'); + done(); + }, 20); + }) + }) + + it('closes the file descriptor', function(done) { + var open_descriptors = get_open_file_descriptors(); + send_request(file + Math.random(), function(err, resp) { + var current_descriptors = get_open_file_descriptors(); + open_descriptors.should.eql(current_descriptors); + done() + }) + }) + + }) + + describe('for a binary file', function() { + + var pixel = Buffer.from("base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs", "base64"); + + before(function() { + handler = function(req, res) { + res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Transfer-Encoding': 'chunked' }); + res.write(pixel.slice(0, 10)); + res.write(pixel.slice(10, 20)); + res.write(pixel.slice(20, 30)); + res.write(pixel.slice(30)); + res.end(); + } + }) + + it('uses a writableStream', function(done) { + var spy = sinon.spy(fs, 'createWriteStream'); + send_request(file, function(err, resp) { + resp.statusCode.should.eql(200); + spy.called.should.eql(true); + spy.restore(); + done(); + }) + }) + + it('writes a file', function(done) { + fs.existsSync(file).should.eql(false); + send_request(file, function(err, resp) { + fs.existsSync(file).should.eql(true); + done(); + }) + }) + + it('file size equals response length', function(done) { + send_request(file, function(err, resp) { + fs.statSync(file).size.should.equal(resp.bytes); + done(); + }) + }) + + it('file is equal to original buffer', function(done) { + send_request(file, function(err, resp) { + // we need to wait a bit since writing to config.output + // happens independently of needle's callback logic. + setTimeout(function() { + fs.readFileSync(file).should.eql(pixel); + done(); + }, 20); + }) + }) + + it('returns the data in resp.body too', function(done) { + send_request(file, function(err, resp) { + resp.body.should.eql(pixel); + done(); + }) + }) + + if (process.platform != 'win32') { + it('closes the file descriptor', function(done) { + var open_descriptors = get_open_file_descriptors(); + send_request(file + Math.random(), function(err, resp) { + var current_descriptors = get_open_file_descriptors(); + open_descriptors.should.eql(current_descriptors); + done() + }) + }) + } + + }) + + }) + +}) diff --git a/node_modules/needle/test/parsing_spec.js b/node_modules/needle/test/parsing_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..b32bfb1e5538dbdcb3b9173374244fab1964fd66 --- /dev/null +++ b/node_modules/needle/test/parsing_spec.js @@ -0,0 +1,547 @@ +var should = require('should'), + needle = require('./../'), + http = require('http'), + port = 11111, + server; + +describe('parsing', function(){ + + describe('when response is an JSON string', function(){ + + var json_string = '{"foo":"bar"}'; + + before(function(done){ + server = http.createServer(function(req, res) { + res.setHeader('Content-Type', 'application/json'); + res.end(json_string); + }).listen(port, done); + }); + + after(function(done){ + server.close(done); + }) + + describe('and parse option is not passed', function() { + + describe('with default parse_response', function() { + + before(function() { + needle.defaults().parse_response.should.eql('all') + }) + + it('should return object', function(done){ + needle.get('localhost:' + port, function(err, response, body){ + should.ifError(err); + body.should.have.property('foo', 'bar'); + done(); + }) + }) + + }) + + describe('and default parse_response is set to false', function() { + + it('does NOT return object when disabled using .defaults', function(done){ + needle.defaults({ parse_response: false }) + + needle.get('localhost:' + port, function(err, response, body) { + should.not.exist(err); + body.should.be.an.instanceof(String) + body.toString().should.eql('{"foo":"bar"}'); + + needle.defaults({ parse_response: 'all' }); + done(); + }) + }) + + + }) + + }) + + describe('and parse option is true', function() { + + describe('and JSON is valid', function() { + + it('should return object', function(done) { + needle.get('localhost:' + port, { parse: true }, function(err, response, body){ + should.not.exist(err); + body.should.have.property('foo', 'bar') + done(); + }) + }) + + it('should have a .parser = json property', function(done) { + needle.get('localhost:' + port, { parse: true }, function(err, resp) { + should.not.exist(err); + resp.parser.should.eql('json'); + done(); + }) + }) + + }); + + describe('and response is empty', function() { + + var old_json_string; + + before(function() { + old_json_string = json_string; + json_string = ""; + }); + + after(function() { + json_string = old_json_string; + }); + + it('should return an empty string', function(done) { + needle.get('localhost:' + port, { parse: true }, function(err, resp) { + should.not.exist(err); + resp.body.should.equal(''); + done(); + }) + }) + + }) + + describe('and JSON is invalid', function() { + + var old_json_string; + + before(function() { + old_json_string = json_string; + json_string = "this is not going to work"; + }); + + after(function() { + json_string = old_json_string; + }); + + it('does not throw', function(done) { + (function(){ + needle.get('localhost:' + port, { parse: true }, done); + }).should.not.throw(); + }); + + it('does NOT return object', function(done) { + needle.get('localhost:' + port, { parse: true }, function(err, response, body) { + should.not.exist(err); + body.should.be.a.String; + body.toString().should.eql('this is not going to work'); + done(); + }) + }) + + }); + + }) + + describe('and parse option is false', function() { + + it('does NOT return object', function(done){ + needle.get('localhost:' + port, { parse: false }, function(err, response, body) { + should.not.exist(err); + body.should.be.an.instanceof(String) + body.toString().should.eql('{"foo":"bar"}'); + done(); + }) + }) + + it('should NOT have a .parser = json property', function(done) { + needle.get('localhost:' + port, { parse: false }, function(err, resp) { + should.not.exist(err); + should.not.exist(resp.parser); + done(); + }) + }) + + }) + + describe('and parse option is "xml"', function() { + + it('does NOT return object', function(done){ + needle.get('localhost:' + port, { parse: 'xml' }, function(err, response, body) { + should.not.exist(err); + body.should.be.an.instanceof(String) + body.toString().should.eql('{"foo":"bar"}'); + done(); + }) + }) + + it('should NOT have a .parser = json property', function(done) { + needle.get('localhost:' + port, { parse: 'xml' }, function(err, resp) { + should.not.exist(err); + should.not.exist(resp.parser); + done(); + }) + }) + + }) + + }); + + describe('when response is JSON \'false\'', function(){ + + var json_string = 'false'; + + before(function(done){ + server = http.createServer(function(req, res) { + res.setHeader('Content-Type', 'application/json'); + res.end(json_string); + }).listen(port, done); + }); + + after(function(done){ + server.close(done); + }) + + describe('and parse option is not passed', function() { + + it('should return object', function(done){ + needle.get('localhost:' + port, function(err, response, body){ + should.ifError(err); + body.should.equal(false); + done(); + }) + }) + + }) + + describe('and parse option is true', function() { + + describe('and JSON is valid', function() { + + it('should return object', function(done){ + needle.get('localhost:' + port, { parse: true }, function(err, response, body){ + should.not.exist(err); + body.should.equal(false) + done(); + }) + }) + + }); + + describe('and response is empty', function() { + + var old_json_string; + + before(function() { + old_json_string = json_string; + json_string = ""; + }); + + after(function() { + json_string = old_json_string; + }); + + it('should return an empty string', function(done) { + needle.get('localhost:' + port, { parse: true }, function(err, resp) { + should.not.exist(err); + resp.body.should.equal(''); + done(); + }) + }) + + }) + + describe('and JSON is invalid', function() { + + var old_json_string; + + before(function() { + old_json_string = json_string; + json_string = "this is not going to work"; + }); + + after(function() { + json_string = old_json_string; + }); + + it('does not throw', function(done) { + (function(){ + needle.get('localhost:' + port, { parse: true }, done); + }).should.not.throw(); + }); + + it('does NOT return object', function(done) { + needle.get('localhost:' + port, { parse: true }, function(err, response, body) { + should.not.exist(err); + body.should.be.a.String; + body.toString().should.eql('this is not going to work'); + done(); + }) + }) + + }); + + }) + + describe('and parse option is false', function() { + + it('does NOT return object', function(done){ + needle.get('localhost:' + port, { parse: false }, function(err, response, body) { + should.not.exist(err); + body.should.be.an.instanceof(String) + body.toString().should.eql('false'); + done(); + }) + }) + + }) + + describe('and parse option is "xml"', function() { + + it('does NOT return object', function(done){ + needle.get('localhost:' + port, { parse: 'xml' }, function(err, response, body) { + should.not.exist(err); + body.should.be.an.instanceof(String) + body.toString().should.eql('false'); + done(); + }) + }) + + }) + + + }); + + describe('when response is an invalid XML string', function(){ + + before(function(done){ + server = http.createServer(function(req, res) { + res.writeHeader(200, {'Content-Type': 'application/xml'}) + res.end("") + }).listen(port, done); + }); + + after(function(done){ + server.close(done); + }) + + describe('and parse_response is true', function(){ + + it('should return original string', function(done) { + needle.get('localhost:' + port, { parse_response: true }, function(err, response, body) { + should.not.exist(err); + body.should.eql('') + should.not.exist(body.name); + done(); + }) + }) + + it('should not have a .parser = xml property', function(done) { + needle.get('localhost:' + port, { parse_response: true }, function(err, resp) { + should.not.exist(err); + should.not.exist(resp.parser); + done(); + }) + }) + + }) + + describe('and parse response is false', function(){ + + it('should return valid object', function(done) { + needle.get('localhost:' + port, { parse_response: false }, function(err, response, body){ + should.not.exist(err); + body.toString().should.eql('') + done(); + }) + }) + + it('should not have a .parser property', function(done) { + needle.get('localhost:' + port, { parse_response: false }, function(err, resp) { + should.not.exist(err); + should.not.exist(resp.parser) + done(); + }) + }) + + }) + + }) + + describe('when response is a valid XML string', function(){ + + before(function(done) { + server = http.createServer(function(req, res) { + res.writeHeader(200, {'Content-Type': 'application/xml'}) + res.end("

hello

") + }).listen(port, done); + }); + + after(function(done) { + server.close(done); + }) + + describe('and parse_response is true', function(){ + + it('should return valid object', function(done) { + needle.get('localhost:' + port, { parse_response: true }, function(err, response, body) { + should.not.exist(err); + body.name.should.eql('post') + body.children[0].name.should.eql('p') + body.children[0].value.should.eql('hello') + + body.children[1].name.should.eql('p') + body.children[1].value.should.eql('world') + done(); + }) + }) + + it('should have a .parser = xml property', function(done) { + needle.get('localhost:' + port, { parse_response: true }, function(err, resp) { + should.not.exist(err); + resp.parser.should.eql('xml'); + done(); + }) + }) + + }) + + describe('and parse response is false', function(){ + + it('should return valid object', function(done) { + needle.get('localhost:' + port, { parse_response: false }, function(err, response, body){ + should.not.exist(err); + body.toString().should.eql('

hello

') + done(); + }) + }) + + it('should not have a .parser property', function(done) { + needle.get('localhost:' + port, { parse_response: false }, function(err, resp) { + should.not.exist(err); + should.not.exist(resp.parser) + done(); + }) + }) + + }) + + }) + + describe('valid XML, using xml2js', function() { + + var parsers, origParser; + + before(function(done) { + var xml2js = require('xml2js') + parsers = require('../lib/parsers'); + origParser = parsers['application/xml']; + + var customParser = require('xml2js').parseString; + parsers.use('xml2js', ['application/xml'], function(buff, cb) { + var opts = { explicitRoot: true, explicitArray: false }; + customParser(buff, opts, cb); + }) + + server = http.createServer(function(req, res) { + res.writeHeader(200, {'Content-Type': 'application/xml'}) + res.end("

hello

world

") + }).listen(port, done); + }); + + after(function(done) { + parsers['application/xml'] = origParser; + server.close(done); + }) + + describe('and parse_response is true', function(){ + + it('should return valid object', function(done) { + needle.get('localhost:' + port, { parse_response: true }, function(err, response, body) { + should.not.exist(err); + body.should.eql({ post: { p: ['hello', 'world' ]}}) + done(); + }) + }) + + it('should have a .parser = xml property', function(done) { + needle.get('localhost:' + port, { parse_response: true }, function(err, resp) { + should.not.exist(err); + resp.parser.should.eql('xml2js'); + done(); + }) + }) + + }) + + describe('and parse response is false', function(){ + + it('should return valid object', function(done) { + needle.get('localhost:' + port, { parse_response: false }, function(err, response, body){ + should.not.exist(err); + body.toString().should.eql('

hello

world

') + done(); + }) + }) + + it('should not have a .parser property', function(done) { + needle.get('localhost:' + port, { parse_response: false }, function(err, resp) { + should.not.exist(err); + should.not.exist(resp.parser) + done(); + }) + }) + + }) + + }) + + describe('when response is a JSON API flavored JSON string', function () { + + var json_string = '{"data":[{"type":"articles","id":"1","attributes":{"title":"Needle","body":"The leanest and most handsome HTTP client in the Nodelands."}}],"included":[{"type":"people","id":"42","attributes":{"name":"Tomás"}}]}'; + + before(function(done){ + server = http.createServer(function(req, res) { + res.setHeader('Content-Type', 'application/vnd.api+json'); + res.end(json_string); + }).listen(port, done); + }); + + after(function(done){ + server.close(done); + }); + + describe('and parse option is not passed', function() { + + describe('with default parse_response', function() { + + before(function() { + needle.defaults().parse_response.should.eql('all') + }) + + it('should return object', function(done){ + needle.get('localhost:' + port, function(err, response, body){ + should.ifError(err); + body.should.deepEqual({ + "data": [{ + "type": "articles", + "id": "1", + "attributes": { + "title": "Needle", + "body": "The leanest and most handsome HTTP client in the Nodelands." + } + }], + "included": [ + { + "type": "people", + "id": "42", + "attributes": { + "name": "Tomás" + } + } + ] + }); + done(); + }); + }); + + }); + + }) + + }); + +}) diff --git a/node_modules/needle/test/post_data_spec.js b/node_modules/needle/test/post_data_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..5c826d67a02c9959e4edcfa51098c14c0d5a54ed --- /dev/null +++ b/node_modules/needle/test/post_data_spec.js @@ -0,0 +1,1021 @@ +var needle = require('..'), + http = require('http'), + should = require('should'), + sinon = require('sinon'), + stream = require('stream'), + helpers = require('./helpers'); + +var multiparts = ['----------------------NODENEEDLEHTTPCLIENT']; +multiparts.push(['Content-Disposition: form-data; name=\"foo\"']) +multiparts.push(['\r\nbar\r\n----------------------NODENEEDLEHTTPCLIENT--']) +// multiparts.push(['Content-Disposition: form-data; name=\"test\"']) +// multiparts.push(['\r\næµè¯\r\n----------------------NODENEEDLEHTTPCLIENT--']) +// multiparts.push(['\r\n' + Buffer.from('测试').toString() + '\r\n----------------------NODENEEDLEHTTPCLIENT--']) + + +describe('post data (e.g. request body)', function() { + + var stub, spy, server; + + before(function(done) { + server = helpers.server({ port: 4321 }, done); + }) + + after(function(done) { + server.close(done); + }) + + afterEach(function() { + if (stub) stub.restore(); + if (spy) spy.restore(); + }) + + function get(data, opts, cb) { + return needle.request('get', 'http://localhost:' + 4321, data, opts, cb) + } + + function post(data, opts, cb) { + return needle.request('post', 'http://localhost:' + 4321, data, opts, cb) + } + + function spystub_request() { + var http_req = http.request; + stub = sinon.stub(http, 'request').callsFake(function(opts, cb) { + var req = http_req(opts, cb); + spy = sinon.spy(req, 'write'); + return req; + }) + } + + function check_request(method) { + stub.calledOnce.should.be.true; + stub.args[0][0]['headers']['host'].should.equal('localhost:4321'); + stub.args[0][0]['method'].should.equal(method); + } + + describe('with multipart: true', function() { + + describe('when null', function() { + + it('sends request (non multipart)', function(done) { + spystub_request(); + + post(null, { multipart: true }, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('doesnt set Content-Type header', function(done) { + post(null, { multipart: true }, function(err, resp) { + should.not.exist(resp.body.headers['content-type']); + done(); + }) + }) + + it('doesnt change default Accept header', function(done) { + post(null, { multipart: true }, function(err, resp) { + // resp.body contains 'header' and 'body', mirroring what we sent + resp.body.headers['accept'].should.equal('*/*'); + done(); + }) + }) + + it('doesnt write anything', function(done) { + spystub_request(); + + post(null, { multipart: true }, function(err, resp) { + spy.called.should.be.false; + resp.body.body.should.eql(''); + done(); + }) + }) + + }) + + describe('when string', function() { + + it('explodes', function() { + (function() { + post('foobar', { multipart: true }) + }).should.throw() + }) + + }) + + describe('when object', function() { + + describe('get request', function() { + + it('sends request', function(done) { + spystub_request(); + + get({ foo: 'bar', test: '测试' }, { multipart: true }, function(err, resp) { + check_request('get'); + done(); + }) + }) + + it('sets Content-Type header', function(done) { + post({ foo: 'bar', test: '测试' }, { multipart: true }, function(err, resp) { + resp.body.headers['content-type'].should.equal('multipart/form-data; boundary=--------------------NODENEEDLEHTTPCLIENT'); + done(); + }) + }) + + it('doesnt change default Accept header', function(done) { + post({ foo: 'bar', test: '测试' }, { multipart: true }, function(err, resp) { + resp.body.headers['accept'].should.equal('*/*'); + done(); + }) + }) + + it('writes string as buffer', function(done) { + spystub_request(); + + get({ foo: 'bar' }, { multipart: true }, function(err, resp) { + spy.called.should.be.true; + + spy.args[0][0].should.be.an.instanceof(String); + spy.args[0][0].toString().should.equal(multiparts.join('\r\n')); + resp.body.body.should.eql(multiparts.join('\r\n')); + done(); + }) + }) + + it('writes japanese chars correctly as binary', function(done) { + spystub_request(); + + get({ foo: 'bar', test: '测试' }, { multipart: true }, function(err, resp) { + spy.called.should.be.true; + + spy.args[0][0].should.be.an.instanceof(String); + Buffer.from(spy.args[0][0]).toString('hex').should.eql('2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d4e4f44454e4545444c4548545450434c49454e540d0a436f6e74656e742d446973706f736974696f6e3a20666f726d2d646174613b206e616d653d22666f6f220d0a0d0a6261720d0a2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d4e4f44454e4545444c4548545450434c49454e540d0a436f6e74656e742d446973706f736974696f6e3a20666f726d2d646174613b206e616d653d2274657374220d0a0d0ac3a6c2b5c28bc3a8c2afc2950d0a2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d4e4f44454e4545444c4548545450434c49454e542d2d') + done(); + }) + }) + + + }) + + describe('post request', function() { + + it('sends request', function(done) { + spystub_request(); + + post({ foo: 'bar', test: '测试' }, { multipart: true }, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('writes string as buffer', function(done) { + spystub_request(); + + post({ foo: 'bar' }, { multipart: true }, function(err, resp) { + spy.called.should.be.true; + spy.args[0][0].should.be.an.instanceof(String); + spy.args[0][0].toString().should.equal(multiparts.join('\r\n')); + resp.body.body.should.eql(multiparts.join('\r\n')); + done(); + }) + }) + + it('writes japanese chars correctly as binary', function(done) { + spystub_request(); + + post({ foo: 'bar', test: '测试' }, { multipart: true }, function(err, resp) { + spy.called.should.be.true; + spy.args[0][0].should.be.an.instanceof(String); + Buffer.from(spy.args[0][0]).toString('hex').should.eql('2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d4e4f44454e4545444c4548545450434c49454e540d0a436f6e74656e742d446973706f736974696f6e3a20666f726d2d646174613b206e616d653d22666f6f220d0a0d0a6261720d0a2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d4e4f44454e4545444c4548545450434c49454e540d0a436f6e74656e742d446973706f736974696f6e3a20666f726d2d646174613b206e616d653d2274657374220d0a0d0ac3a6c2b5c28bc3a8c2afc2950d0a2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d4e4f44454e4545444c4548545450434c49454e542d2d') + done(); + }) + }) + + }) + + }) + + describe('when stream', function() { + + var stream_for_multipart; + + before(function() { + stream_for_multipart = new stream.Readable(); + stream_for_multipart._read = function() { + this.push('foobar'); + this.push(null); + } + }) + + it('explodes', function() { + (function() { + post(stream_for_multipart, { multipart: true }) + }).should.throw() + }) + + }) + + }) + + describe('non multipart', function() { + + describe('when null', function() { + + describe('get request', function() { + + it('sends request', function(done) { + spystub_request(); + + get(null, {}, function(err, resp) { + check_request('get'); + done(); + }) + }) + + it('doesnt write anything', function(done) { + spystub_request(); + + get(null, {}, function(err, resp) { + spy.called.should.be.false; + resp.body.body.should.eql(''); + done(); + }) + }) + + }) + + describe('post request', function() { + + it('sends request', function(done) { + spystub_request(); + + post(null, {}, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('doesnt write anything', function(done) { + spystub_request(); + + post(null, {}, function(err, resp) { + spy.called.should.be.false; + resp.body.body.should.eql(''); + done(); + }) + }) + + }) + + }) + + describe('when string with no equal sign', function() { + + describe('get request', function() { + + it('explodes', function() { + (function() { + get('foobar', {}) + }).should.throw() + }) + + }) + + describe('post request', function() { + + it('sends request', function(done) { + spystub_request(); + + post('foobar', {}, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('writes string as buffer', function(done) { + spystub_request(); + + post('foobar', {}, function(err, resp) { + spy.called.should.be.true; + spy.args[0][0].should.be.an.instanceof(Buffer); + spy.args[0][0].toString().should.equal('foobar'); + resp.body.body.should.eql('foobar'); + done(); + }) + }) + + }) + + }) + + describe('when string WITH equal sign', function() { + + describe('get request', function() { + + describe('with json: false (default)', function() { + + it('sends request, adding data as querystring', function(done) { + spystub_request(); + + get('foo=bar', { json: false }, function(err, resp) { + check_request('get'); + stub.args[0][0]['path'].should.equal('/?foo=bar') + done(); + }) + }) + + it('doesnt set Content-Type header', function(done) { + get('foo=bar', { json: false }, function(err, resp) { + // resp.body contains 'header' and 'body', mirroring what we sent + should.not.exist(resp.body.headers['content-type']); + done(); + }) + }) + + it('doesnt change default Accept header', function(done) { + get('foo=bar', { json: false }, function(err, resp) { + // resp.body contains 'header' and 'body', mirroring what we sent + resp.body.headers['accept'].should.equal('*/*'); + done(); + }) + }) + + it('doesnt write anything', function(done) { + get('foo=bar', { json: false }, function(err, resp) { + spy.called.should.be.false; + resp.body.body.should.eql(''); + done(); + }) + }) + + }) + + describe('with json: true', function() { + + it('sends request, without setting a querystring', function(done) { + spystub_request(); + + get('foo=bar', { json: true }, function(err, resp) { + check_request('get'); + stub.args[0][0]['path'].should.equal('/') + done(); + }) + }) + + it('sets Content-Type header', function(done) { + get('foo=bar', { json: true }, function(err, resp) { + resp.body.headers['content-type'].should.equal('application/json; charset=utf-8'); + done(); + }) + }) + + it('set Accept header to application/json', function(done) { + get('foo=bar', { json: true }, function(err, resp) { + resp.body.headers['accept'].should.equal('application/json'); + done(); + }) + }) + + it('writes raw string (assuming it already is JSON, so no JSON.stringify)', function(done) { + get('foo=bar', { json: true }, function(err, resp) { + spy.called.should.be.true; + spy.args[0][0].toString().should.eql('foo=bar') + resp.body.body.should.eql('foo=bar'); + done(); + }) + }) + + }) + + }) + + describe('post request', function() { + + describe('with json: false (default)', function() { + + it('sends request', function(done) { + spystub_request(); + + post('foo=bar', { json: false }, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('sets Content-Type header to www-form-urlencoded', function(done) { + post('foo=bar', { json: false }, function(err, resp) { + resp.body.headers['content-type'].should.equal('application/x-www-form-urlencoded'); + done(); + }) + }) + + it('doesnt change default Accept header', function(done) { + post('foo=bar', { json: false }, function(err, resp) { + // resp.body contains 'header' and 'body', mirroring what we sent + resp.body.headers['accept'].should.equal('*/*'); + done(); + }) + }) + + it('writes as buffer', function(done) { + post('foo=bar', { json: false }, function(err, resp) { + spy.called.should.be.true; + spy.args[0][0].should.be.an.instanceof(Buffer); + spy.args[0][0].toString().should.equal('foo=bar'); + resp.body.body.should.eql('foo=bar'); + done(); + }) + }) + + }) + + describe('with json: true', function() { + + it('sends request', function(done) { + spystub_request(); + + post('foo=bar', { json: true }, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('sets Content-Type header', function(done) { + post('foo=bar', { json: true }, function(err, resp) { + resp.body.headers['content-type'].should.equal('application/json; charset=utf-8'); + done(); + }) + }) + + it('set Accept header to application/json', function(done) { + post('foo=bar', { json: true }, function(err, resp) { + resp.body.headers['accept'].should.equal('application/json'); + done(); + }) + }) + + it('writes raw string (assuming it already is JSON, so no JSON.stringify)', function(done) { + post('foo=bar', { json: true }, function(err, resp) { + spy.called.should.be.true; + var json = JSON.stringify('foo=bar'); + spy.args[0][0].toString().should.eql('foo=bar') + resp.body.body.should.eql('foo=bar'); + done(); + }) + }) + + }) + + }) + + }) + + describe('when object', function() { + + describe('get request', function() { + + describe('with json: false (default)', function() { + + it('sends request, adding data as querystring', function(done) { + spystub_request(); + + get({ foo: 'bar', test: '测试' }, { json: false }, function(err, resp) { + check_request('get'); + stub.args[0][0]['path'].should.equal('/?foo=bar&test=%E6%B5%8B%E8%AF%95') + done(); + }) + }) + + it('doesnt set Content-Type header', function(done) { + get({ foo: 'bar', test: '测试' }, { json: false }, function(err, resp) { + // resp.body contains 'header' and 'body', mirroring what we sent + should.not.exist(resp.body.headers['content-type']); + done(); + }) + }) + + it('doesnt change default Accept header', function(done) { + get({ foo: 'bar', test: '测试' }, { json: false }, function(err, resp) { + // resp.body contains 'header' and 'body', mirroring what we sent + resp.body.headers['accept'].should.equal('*/*'); + done(); + }) + }) + + it('doesnt write anything', function(done) { + get({ foo: 'bar', test: '测试' }, { json: false }, function(err, resp) { + spy.called.should.be.false; + resp.body.body.should.eql(''); + done(); + }) + }) + + }) + + describe('with json: true', function() { + + it('sends request, without setting a querystring', function(done) { + spystub_request(); + + get({ foo: 'bar', test: '测试' }, { json: true }, function(err, resp) { + check_request('get'); + stub.args[0][0]['path'].should.equal('/') + done(); + }) + }) + + it('sets Content-Type header', function(done) { + get({ foo: 'bar', test: '测试' }, { json: true }, function(err, resp) { + resp.body.headers['content-type'].should.equal('application/json; charset=utf-8'); + done(); + }) + }) + + it('set Accept header to application/json', function(done) { + get({ foo: 'bar', test: '测试' }, { json: true }, function(err, resp) { + resp.body.headers['accept'].should.equal('application/json'); + done(); + }) + }) + + it('writes JSON.stringify version of object', function(done) { + get({ foo: 'bar', test: '测试' }, { json: true }, function(err, resp) { + spy.called.should.be.true; + var json = JSON.stringify({ foo: 'bar', test: '测试' }) + spy.args[0][0].toString().should.eql(json) + resp.body.body.should.eql(json); + done(); + }) + }) + + }) + + }) + + describe('post request', function() { + + describe('with json: false (default)', function() { + + it('sends request', function(done) { + spystub_request(); + + post({ foo: 'bar', test: '测试' }, { json: false }, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('sets Content-Type header to www-form-urlencoded', function(done) { + post({ foo: 'bar', test: '测试' }, { json: false }, function(err, resp) { + resp.body.headers['content-type'].should.equal('application/x-www-form-urlencoded'); + done(); + }) + }) + + it('doesnt change default Accept header', function(done) { + post({ foo: 'bar', test: '测试' }, { json: false }, function(err, resp) { + // resp.body contains 'header' and 'body', mirroring what we sent + resp.body.headers['accept'].should.equal('*/*'); + done(); + }) + }) + + it('writes as buffer', function(done) { + post({ foo: 'bar', test: '测试' }, { json: false }, function(err, resp) { + spy.called.should.be.true; + spy.args[0][0].should.be.an.instanceof(Buffer); + spy.args[0][0].toString().should.equal('foo=bar&test=%E6%B5%8B%E8%AF%95'); + resp.body.body.should.eql('foo=bar&test=%E6%B5%8B%E8%AF%95'); + done(); + }) + }) + + }) + + describe('with json: false and content_type = "application/json"', function() { + + var opts = { json: false, content_type: 'application/json' }; + + it('sends request', function(done) { + spystub_request(); + + post({ foo: 'bar', test: '测试' }, opts, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('sets Content-Type header to application/json', function(done) { + post({ foo: 'bar', test: '测试' }, opts, function(err, resp) { + resp.body.headers['content-type'].should.equal('application/json'); + done(); + }) + }) + + it('doesnt change default Accept header', function(done) { + post({ foo: 'bar', test: '测试' }, opts, function(err, resp) { + // resp.body contains 'header' and 'body', mirroring what we sent + resp.body.headers['accept'].should.equal('*/*'); + done(); + }) + }) + + it('writes as buffer', function(done) { + post({ foo: 'bar', test: '测试' }, opts, function(err, resp) { + spy.called.should.be.true; + spy.args[0][0].constructor.name.should.eql('Buffer'); + spy.args[0][0].toString().should.equal('foo=bar&test=%E6%B5%8B%E8%AF%95'); + resp.body.body.should.eql('foo=bar&test=%E6%B5%8B%E8%AF%95'); + done(); + }) + }) + + }) + + describe('with json: undefined but content-type = application/json', function() { + + var opts = { headers: { 'content-type': 'application/json' } }; + + it('sends request', function(done) { + spystub_request(); + + post({ foo: 'bar', test: '测试' }, opts, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('doesnt change Content-Type header', function(done) { + post({ foo: 'bar', test: '测试' }, opts, function(err, resp) { + resp.body.headers['content-type'].should.equal('application/json'); + done(); + }) + }) + + it('leaves default Accept header', function(done) { + post({ foo: 'bar', test: '测试' }, opts, function(err, resp) { + resp.body.headers['accept'].should.equal('*/*'); + done(); + }) + }) + + it('writes JSON.stringified object', function(done) { + post({ foo: 'bar', test: '测试' }, opts, function(err, resp) { + spy.called.should.be.true; + var json = JSON.stringify({ foo: 'bar', test: '测试' }) + spy.args[0][0].toString().should.eql(json) + resp.body.body.should.eql(json); + done(); + }) + }) + }) + + describe('with json: true', function() { + + it('sends request', function(done) { + spystub_request(); + + post({ foo: 'bar', test: '测试' }, { json: true }, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('sets Content-Type header', function(done) { + post({ foo: 'bar', test: '测试' }, { json: true }, function(err, resp) { + resp.body.headers['content-type'].should.equal('application/json; charset=utf-8'); + done(); + }) + }) + + it('set Accept header to application/json', function(done) { + post({ foo: 'bar', test: '测试' }, { json: true }, function(err, resp) { + resp.body.headers['accept'].should.equal('application/json'); + done(); + }) + }) + + it('writes JSON.stringified object', function(done) { + post({ foo: 'bar', test: '测试' }, { json: true }, function(err, resp) { + spy.called.should.be.true; + var json = JSON.stringify({ foo: 'bar', test: '测试' }) + spy.args[0][0].toString().should.eql(json) + resp.body.body.should.eql(json); + done(); + }) + }) + + }) + + + describe('with json: true and content_type: */* (passed, not default)', function() { + + var opts = { json: true, accept: '*/*' }; + + it('sends request', function(done) { + spystub_request(); + + post({ foo: 'bar', test: '测试' }, opts, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('sets Content-Type header to application/json', function(done) { + post({ foo: 'bar', test: '测试' }, opts, function(err, resp) { + resp.body.headers['content-type'].should.equal('application/json; charset=utf-8'); + done(); + }) + }) + + it('respects Accept header set by user', function(done) { + post({ foo: 'bar', test: '测试' }, opts, function(err, resp) { + resp.body.headers['accept'].should.equal('*/*'); + done(); + }) + }) + + it('writes JSON.stringified object', function(done) { + post({ foo: 'bar', test: '测试' }, opts, function(err, resp) { + spy.called.should.be.true; + var json = JSON.stringify({ foo: 'bar', test: '测试' }) + spy.args[0][0].toString().should.eql(json) + resp.body.body.should.eql(json); + done(); + }) + }) + + }) + + }) + + }) + + describe('when buffer', function() { + + describe('get request', function() { + + describe('with json: false (default)', function() { + + it('sends request', function(done) { + spystub_request(); + + get(Buffer.from('foobar'), { json: false }, function(err, resp) { + check_request('get'); + done(); + }) + }) + + it('sets Content-Type header', function(done) { + get(Buffer.from('foobar'), { json: false }, function(err, resp) { + // should.not.exist(resp.body.headers['content-type']); + resp.body.headers['content-type'].should.equal('application/x-www-form-urlencoded'); + + done(); + }) + }) + + it('doesnt change default Accept header', function(done) { + get(Buffer.from('foobar'), { json: false }, function(err, resp) { + // resp.body contains 'header' and 'body', mirroring what we sent + resp.body.headers['accept'].should.equal('*/*'); + done(); + }) + }) + + it('writes as buffer', function(done) { + get(Buffer.from('foobar'), { json: false }, function(err, resp) { + spy.called.should.be.true; + spy.args[0][0].should.be.an.instanceof(Buffer); + spy.args[0][0].toString().should.equal('foobar'); + resp.body.body.should.eql('foobar'); + done(); + }) + }) + + }) + + describe('with json: true', function() { + + it('sends request, without setting a querystring', function(done) { + spystub_request(); + + get(Buffer.from('foobar'), { json: true }, function(err, resp) { + check_request('get'); + done(); + }) + }) + + it('sets Content-Type header', function(done) { + get(Buffer.from('foobar'), { json: true }, function(err, resp) { + resp.body.headers['content-type'].should.equal('application/json; charset=utf-8'); + done(); + }) + }) + + it('set Accept header to application/json', function(done) { + get(Buffer.from('foobar'), { json: true }, function(err, resp) { + resp.body.headers['accept'].should.equal('application/json'); + done(); + }) + }) + + it('writes JSON.stringify version of object', function(done) { + get(Buffer.from('foobar'), { json: true }, function(err, resp) { + spy.called.should.be.true; + spy.args[0][0].toString().should.eql('foobar') + resp.body.body.should.eql('foobar'); + done(); + }) + }) + + }) + + }) + + describe('post request', function() { + + describe('with json: false (default)', function() { + + it('sends request', function(done) { + spystub_request(); + + post(Buffer.from('foobar'), { json: false }, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('sets Content-Type header to www-form-urlencoded', function(done) { + post(Buffer.from('foobar'), { json: false }, function(err, resp) { + resp.body.headers['content-type'].should.equal('application/x-www-form-urlencoded'); + done(); + }) + }) + + it('doesnt change default Accept header', function(done) { + post(Buffer.from('foobar'), { json: false }, function(err, resp) { + // resp.body contains 'header' and 'body', mirroring what we sent + resp.body.headers['accept'].should.equal('*/*'); + done(); + }) + }) + + it('writes as buffer', function(done) { + post(Buffer.from('foobar'), { json: false }, function(err, resp) { + spy.called.should.be.true; + spy.args[0][0].should.be.an.instanceof(Buffer); + spy.args[0][0].toString().should.equal('foobar'); + resp.body.body.should.eql('foobar'); + done(); + }) + }) + + }) + + describe('with json: true', function() { + + it('sends request', function(done) { + spystub_request(); + + post(Buffer.from('foobar'), { json: true }, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('sets Content-Type header', function(done) { + post(Buffer.from('foobar'), { json: true }, function(err, resp) { + resp.body.headers['content-type'].should.equal('application/json; charset=utf-8'); + done(); + }) + }) + + it('set Accept header to application/json', function(done) { + post(Buffer.from('foobar'), { json: true }, function(err, resp) { + resp.body.headers['accept'].should.equal('application/json'); + done(); + }) + }) + + it('passes raw buffer (assuming its a JSON string beneath)', function(done) { + post(Buffer.from('foobar'), { json: true }, function(err, resp) { + spy.called.should.be.true; + spy.args[0][0].toString().should.eql('foobar') + resp.body.body.should.eql('foobar'); + done(); + }) + }) + + }) + + }) + + }) + + describe('when stream', function() { + + var input_stream; + + beforeEach(function() { + input_stream = new stream.Readable(); + input_stream._read = function() { + this.push('foobar'); + this.push(null); + } + }) + + describe('get request', function() { + + it('explodes', function() { + (function() { + get(input_stream, {}) + }).should.throw() + }) + + }); + + describe('post request', function() { + + describe('with json: false (default)', function() { + + it('sends request', function(done) { + spystub_request(); + + post(input_stream, { json: false }, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('sets Content-Type header to www-form-urlencoded', function(done) { + post(input_stream, { json: false }, function(err, resp) { + resp.body.headers['content-type'].should.equal('application/x-www-form-urlencoded'); + done(); + }) + }) + + it('doesnt change default Accept header', function(done) { + post(input_stream, { json: false }, function(err, resp) { + // resp.body contains 'header' and 'body', mirroring what we sent + resp.body.headers['accept'].should.equal('*/*'); + done(); + }) + }) + + it('writes as buffer', function(done) { + post(input_stream, { json: false }, function(err, resp) { + spy.called.should.be.true; + spy.args[0][0].should.be.an.instanceof(Buffer); + spy.args[0][0].toString().should.equal('foobar'); + resp.body.body.should.eql('foobar'); + done(); + }) + }) + + }) + + describe('with json: true', function() { + + it('sends request', function(done) { + spystub_request(); + + post(input_stream, { json: true }, function(err, resp) { + check_request('post'); + done(); + }) + }) + + it('sets Content-Type header', function(done) { + post(input_stream, { json: true }, function(err, resp) { + resp.body.headers['content-type'].should.equal('application/json; charset=utf-8'); + done(); + }) + }) + + it('set Accept header to application/json', function(done) { + post(input_stream, { json: true }, function(err, resp) { + resp.body.headers['accept'].should.equal('application/json'); + done(); + }) + }) + + it('writes JSON.stringified object', function(done) { + post(input_stream, { json: true }, function(err, resp) { + spy.called.should.be.true; + spy.args[0][0].toString().should.eql('foobar') + resp.body.body.should.eql('foobar'); + done(); + }) + }) + + }) + + }) + + }) + + }) + +}) diff --git a/node_modules/needle/test/proxy_spec.js b/node_modules/needle/test/proxy_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..9526e7f7a6468f4a1f9d1603b0bf3a5cc872b094 --- /dev/null +++ b/node_modules/needle/test/proxy_spec.js @@ -0,0 +1,202 @@ +var helpers = require('./helpers'), + should = require('should'), + sinon = require('sinon'), + http = require('http'), + needle = require('./../'); + +var port = 7707; +var url = 'localhost:' + port; +var nonexisting_host = 'awepfokawepofawe.com'; + +describe('proxy option', function() { + + var spy, opts; + + function send_request(opts, done) { + if (spy) spy.restore(); + spy = sinon.spy(http, 'request'); + needle.get(url, opts, done); + } + + ////////////////////// + // proxy opts helpers + + function not_proxied(done) { + return function(err, resp) { + var path = spy.args[0][0].path; + path.should.eql('/'); // not the full original URI + spy.restore(); + done(); + } + } + + function proxied(host, port, done) { + return function(err, resp) { + var path = spy.args[0][0].path; + path.should.eql('http://' + url); // the full original URI + + var http_host = spy.args[0][0].host; + if (http_host) http_host.should.eql(host); + + var http_port = spy.args[0][0].port; + if (http_port) http_port.should.eql(port); + + spy.restore(); + done(); + } + } + + ////////////////////// + // auth helpers + + function get_auth(header) { + var token = header.split(/\s+/).pop(); + return token && Buffer.from(token, 'base64').toString().split(':'); + } + + function no_proxy_auth(done) { + return function(err, resp) { + var headers = spy.args[0][0].headers; + Object.keys(headers).should.not.containEql('proxy-authorization'); + done(); + } + } + + function header_set(name, user, pass, done) { + return function(err, resp) { + var headers = spy.args[0][0].headers; + var auth = get_auth(headers[name]); + auth[0].should.eql(user); + auth[1].should.eql(pass); + done(); + } + } + + function proxy_auth_set(user, pass, done) { + return header_set('proxy-authorization', user, pass, done); + } + + function basic_auth_set(user, pass, done) { + return header_set('authorization', user, pass, done); + } + + after(function() { + spy.restore(); + }) + + describe('when null proxy is passed', function() { + + it('does not proxy', function(done) { + send_request({ proxy: null }, not_proxied(done)) + }) + + describe('but defaults has been set', function() { + + before(function() { + needle.defaults({ proxy: 'foobar' }); + }) + + after(function() { + needle.defaults({ proxy: null }); + }) + + it('tries to proxy anyway', function(done) { + send_request({}, proxied('foobar', 80, done)) + }) + + }) + + }) + + describe('when weird string is passed', function() { + + it('tries to proxy anyway', function(done) { + send_request({ proxy: 'alfalfa' }, proxied('alfalfa', 80, done)) + }) + }) + + describe('when valid url is passed', function() { + + it('proxies request', function(done) { + send_request({ proxy: nonexisting_host + ':123/done' }, proxied(nonexisting_host, '123', done)) + }) + + it('does not set a Proxy-Authorization header', function(done) { + send_request({ proxy: nonexisting_host + ':123/done' }, no_proxy_auth(done)); + }) + + describe('and proxy url contains user:pass', function() { + + before(function() { + opts = { + proxy: 'http://mj:x@' + nonexisting_host + ':123/done' + } + }) + + it('proxies request', function(done) { + send_request(opts, proxied(nonexisting_host, '123', done)) + }) + + it('sets Proxy-Authorization header', function(done) { + send_request(opts, proxy_auth_set('mj', 'x', done)); + }) + + }) + + describe('and a proxy_user is passed', function() { + + before(function() { + opts = { + proxy: nonexisting_host + ':123', + proxy_user: 'someone', + proxy_pass: 'else' + } + }) + + it('proxies request', function(done) { + send_request(opts, proxied(nonexisting_host, '123', done)) + }) + + it('sets Proxy-Authorization header', function(done) { + send_request(opts, proxy_auth_set('someone', 'else', done)); + }) + + describe('and url also contains user:pass', function() { + + it('url user:pass wins', function(done) { + var opts = { + proxy: 'http://xxx:yyy@' + nonexisting_host + ':123', + proxy_user: 'someone', + proxy_pass: 'else' + } + + send_request(opts, proxy_auth_set('xxx', 'yyy', done)); + }) + + }) + + describe('and options.username is also present', function() { + + before(function() { + opts = { proxy_user: 'foobar', username: 'someone' }; + }) + + it('a separate Authorization header is set', function(done) { + var opts = { + proxy: nonexisting_host + ':123', + proxy_user: 'someone', + proxy_pass: 'else', + username: 'test', + password: 'X' + } + + send_request(opts, basic_auth_set('test', 'X', done)); + }) + + }) + + }) + + }) + +}) diff --git a/node_modules/needle/test/querystring_spec.js b/node_modules/needle/test/querystring_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..34c1748c6f2fd986c08722583b1577046c14b75b --- /dev/null +++ b/node_modules/needle/test/querystring_spec.js @@ -0,0 +1,128 @@ +var should = require('should'), + stringify = require('../lib/querystring').build; + +describe('stringify', function() { + + describe('with null', function() { + + it('throws', function() { + (function() { + var res = stringify(null); + }).should.throw(); + }) + + }) + + describe('with a number', function() { + + it('throws', function() { + (function() { + var res = stringify(100); + }).should.throw(); + }) + + }) + + describe('with a string', function() { + + describe('that is empty', function() { + + it('throws', function() { + (function() { + var res = stringify(''); + }).should.throw(); + }) + + }) + + describe('that doesnt contain an equal sign', function() { + + it('throws', function() { + (function() { + var res = stringify('boomshagalaga'); + }).should.throw(); + }) + + }) + + describe('that contains an equal sign', function() { + + it('works', function() { + var res = stringify('hello=123'); + res.should.eql('hello=123'); + }) + + }) + + }) + + describe('with an array', function() { + + describe('with key val objects', function() { + + it('works', function() { + var res = stringify([ {foo: 'bar'} ]); + res.should.eql('foo=bar'); + }) + + }) + + describe('where all elements are strings with an equal sign', function() { + + it('works', function() { + var res = stringify([ 'bar=123', 'quux=' ]); + res.should.eql('bar=123&quux='); + }) + + }) + + describe('with random words', function() { + + it('throws', function() { + (function() { + var res = stringify(['hello', 'there']); + }).should.throw(); + }) + + }) + + describe('with integers', function() { + + it('throws', function() { + (function() { + var res = stringify([123, 432]); + }).should.throw(); + }) + + }) + + }) + + describe('with an object', function() { + + it('works', function() { + var res = stringify({ test: 100 }); + res.should.eql('test=100'); + }) + + describe('with object where val is an array', function() { + + it('works', function() { + var res = stringify({ foo: ['bar', 'baz'] }); + res.should.eql('foo[]=bar&foo[]=baz'); + }) + + }) + + describe('with object where val is an array of key val objects', function() { + + it('works', function() { + var res = stringify({ foo: [{'1': 'bar'}, {'2': 'baz'}] }); + res.should.eql('foo[][1]=bar&foo[][2]=baz'); + }) + + }) + + }) + +}) diff --git a/node_modules/needle/test/redirect_spec.js b/node_modules/needle/test/redirect_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..c3942e279b29ea1c5909a72f9f59b7d31a56161d --- /dev/null +++ b/node_modules/needle/test/redirect_spec.js @@ -0,0 +1,394 @@ +var helpers = require('./helpers'), + should = require('should'), + sinon = require('sinon'), + needle = require('./../'); + +var ports = { + http : 8888, + https : 9999 +} + +var protocols = { + http : require('http'), + https : require('https') +} + +var code = 301; +var location; // var to set the response location + +function response_code() { + return code; +} + +function response_headers() { + return { 'Content-Type': 'text/plain', 'Location': location } +} + +describe('redirects', function() { + + var spies = {}, + servers = {}; + + var current_protocol; + var hostname = require('os').hostname(); + + // open two servers, one that responds to a redirect + before(function(done) { + + var conf = { + port : ports.http, + code : response_code, + headers : response_headers + } + + servers.http = helpers.server(conf, function() { + conf.port = ports.https; + conf.protocol = 'https'; + servers.https = helpers.server(conf, done); + }); + }) + + after(function(done) { + servers.http.close(function() { + servers.https.close(done); + }); + }) + + var prots = {'http': 'https'}; + Object.keys(prots).forEach(function(protocol) { + + current_protocol = protocol; + var other_protocol = protocol == 'http' ? 'https' : 'http'; + + var opts, // each test will modify this + host = '127.0.0.1', + url = protocol + '://' + host + ':' + ports[protocol] + '/hello'; + + function send_request(opts, cb) { + opts.rejectUnauthorized = false; + // console.log(' -- sending request ' + url + ' -- redirect to ' + location); + needle.post(url, { foo: 'bar' }, opts, cb); + } + + function not_followed(done) { + send_request(opts, function(err, resp) { + resp.statusCode.should.eql(301); + if (current_protocol == 'http') { + spies.http.callCount.should.eql(1); // only original request + spies.https.callCount.should.eql(0); + } else { + spies.http.callCount.should.eql(0); + spies.https.callCount.should.eql(1); // only original request + } + done(); + }) + } + + function followed_same_protocol(done) { + send_request(opts, function(err, resp) { + // the original request plus the redirect one + spies[current_protocol].callCount.should.eql(2); + done(); + }) + + } + + function followed_other_protocol(done) { + send_request(opts, function(err, resp) { + // on new-ish node versions, https.request calls http.request internally, + // so we need to amount for that additional call. + // update: this doesn't happen on node > 10.x + + var node_major_ver = process.version.split('.')[0].replace('v', ''); + var http_calls = protocols.http.Agent.defaultMaxSockets == Infinity && parseInt(node_major_ver) < 10 ? 2 : 1; + + spies.http.callCount.should.eql(http_calls); // the one(s) from http.request + spies.https.callCount.should.eql(1); // the one from https.request (redirect) + done(); + }) + } + + // set a spy on [protocol].request + // so we can see how many times a request was made + before(function() { + spies.http = sinon.spy(protocols.http, 'request'); + spies.https = sinon.spy(protocols.https, 'request'); + }) + + // and make sure it is restored after each test + afterEach(function() { + spies.http.reset(); + spies.https.reset(); + }) + + after(function() { + spies.http.restore(); + spies.https.restore(); + }) + + describe('when overriding defaults', function() { + + before(function() { + needle.defaults({ follow_max: 10 }); + opts = {}; + }) + + after(function() { + // reset values to previous + needle.defaults({ follow_max: 0 }); + }) + + describe('and redirected to the same path on same host and protocol', function() { + before(function() { + location = url; + }) + it('does not follow redirect', not_followed); + }) + + describe('and redirected to the same path on same host and different protocol', function() { + before(function() { + location = url.replace(protocol, other_protocol).replace(ports[protocol], ports[other_protocol]); + }) + + it('follows redirect', followed_other_protocol); + }) + + describe('and redirected to a different path on same host, same protocol', function() { + before(function() { + location = url.replace('/hello', '/goodbye'); + }) + it('follows redirect', followed_same_protocol); + }) + + describe('and redirected to a different path on same host, different protocol', function() { + before(function() { + location = url.replace('/hello', '/goodbye').replace(protocol, other_protocol).replace(ports[protocol], ports[other_protocol]); + }) + it('follows redirect', followed_other_protocol); + }) + + describe('and redirected to same path on another host, same protocol', function() { + before(function() { + location = url.replace(host, hostname); + }) + it('follows redirect', followed_same_protocol); + }) + + describe('and redirected to same path on another host, different protocol', function() { + before(function() { + location = url.replace(host, hostname).replace(protocol, other_protocol).replace(ports[protocol], ports[other_protocol]); + }) + it('follows redirect', followed_other_protocol); + }) + + }) + + // false and null have the same result + var values = [false, null]; + values.forEach(function(value) { + + describe('when follow is ' + value, function() { + + before(function() { + opts = { follow: value }; + }) + + + + describe('and redirected to the same path on same host and protocol', function() { + before(function() { + location = url; + }) + + it('throws an error', function() { + (function() { + send_request(opts, function() { }); + }).should.throw; + }) + + }) + + }) + + }) + + describe('when follow is true', function() { + + before(function() { + opts = { follow: true }; + }) + + describe('and redirected to the same path on same host and protocol', function() { + before(function() { location = url }) + + it('throws an error', function() { + (function() { + send_request(opts, function() { }); + }).should.throw; + }) + + }) + + }) + + describe('when follow is > 0', function() { + + before(function() { + needle.defaults({ follow: 10 }); + }) + + after(function() { + needle.defaults({ follow: 0 }); + }) + + describe('when keep_method is false', function() { + + before(function() { + opts = { follow_keep_method: false }; + }) + + // defaults to follow host and protocol + describe('and redirected to the same path on same host and different protocol', function() { + + before(function() { + location = url.replace(protocol, other_protocol); + }) + + it('follows redirect', followed_other_protocol); + + it('sends a GET request with no data', function(done) { + send_request(opts, function(err, resp) { + spies.http.args[0][0].method.should.eql('GET'); + // spy.args[0][3].should.eql(null); + done(); + }) + }) + + }) + + }) + + describe('and set_referer is true', function() { + + before(function() { + opts = { follow_set_referer: true }; + }) + + // defaults to follow host and protocol + describe('and redirected to the same path on same host and different protocol', function() { + + before(function() { + location = url.replace(protocol, other_protocol); + }) + + it('follows redirect', followed_other_protocol); + + it('sets Referer header when following redirect', function(done) { + send_request(opts, function(err, resp) { + spies.http.args[0][0].headers['referer'].should.eql("http://" + host + ":8888/hello"); + // spies.http.args[0][3].should.eql({ foo: 'bar'}); + done(); + }) + }) + + }) + + }) + + describe('and keep_method is true', function() { + + before(function() { + opts = { follow_keep_method: true }; + }) + + // defaults to follow host and protocol + describe('and redirected to the same path on same host and different protocol', function() { + + before(function() { + location = url.replace(protocol, other_protocol); + }) + + it('follows redirect', followed_other_protocol); + + it('sends a POST request with the original data', function(done) { + send_request(opts, function(err, resp) { + spies.http.args[0][0].method.should.eql('post'); + // spies.http.args[0][3].should.eql({ foo: 'bar'}); + done(); + }) + }) + + }) + + }) + + describe('and if_same_host is false', function() { + + before(function() { + opts = { follow_if_same_host: false }; + }) + + // by default it will follow other protocols + describe('and redirected to same path on another domain, same protocol', function() { + before(function() { + location = url.replace(host, hostname); + }) + it('follows redirect', followed_same_protocol); + }) + + }) + + describe('and if_same_host is true', function() { + + before(function() { + opts = { follow_if_same_host: true }; + }) + + // by default it will follow other protocols + describe('and redirected to same path on another domain, same protocol', function() { + before(function() { + location = url.replace(host, hostname); + }) + + it('does not follow redirect', not_followed); + }) + + }) + + describe('and if_same_protocol is false', function() { + + before(function() { + opts = { follow_if_same_protocol: false }; + }) + + // by default it will follow other hosts + describe('and redirected to same path on another domain, different protocol', function() { + before(function() { + location = url.replace(host, hostname).replace(protocol, other_protocol).replace(ports[protocol], ports[other_protocol]); + }) + it('follows redirect', followed_other_protocol); + }) + + }) + + describe('and if_same_protocol is true', function() { + + before(function() { + opts = { follow_if_same_protocol: true }; + }) + + // by default it will follow other hosts + describe('and redirected to same path on another domain, different protocol', function() { + before(function() { + location = url.replace(host, hostname).replace(protocol, other_protocol).replace(ports[protocol], ports[other_protocol]); + }) + it('does not follow redirect', not_followed); + }) + + }) + + }) + + }) + +}); diff --git a/node_modules/needle/test/redirect_with_timeout.js b/node_modules/needle/test/redirect_with_timeout.js new file mode 100644 index 0000000000000000000000000000000000000000..7e8e02e630e83c814cbf920e80f9f0ce6c2094b7 --- /dev/null +++ b/node_modules/needle/test/redirect_with_timeout.js @@ -0,0 +1,45 @@ +var should = require('should') +var needle = require('./../') + +describe('follow redirects when read_timeout is set', function () { + + it('clear timeout before following redirect', function (done) { + var opts = { + open_timeout: 1000, + read_timeout: 3000, + follow: 5, + user_agent: 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36' + } + + var timedOut = 0 + var redirects = 0 + + var timer = setTimeout(function () { + var hasRedirects = redirects > 0 + hasRedirects.should.equal(true) + done() + }, opts.read_timeout || 3000) + + var resp = needle.get('http://google.com/', opts, function (err, resp, body) { + var noErr = err === null + var hasBody = body.length > 0 + noErr.should.equal(true); + hasBody.should.equal(true); + }); + + resp.on('redirect', function (location) { + redirects++ + // console.info(' Redirected to ', location) + }) + + resp.on('timeout', function (type) { + timedOut++ + timedOut.should.equal(0) + // console.error(' ', type, 'timeout') + clearTimeout(timer) + done() + }) + + }).timeout(30000) + +}) \ No newline at end of file diff --git a/node_modules/needle/test/request_stream_spec.js b/node_modules/needle/test/request_stream_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..0dfcb791d89cffd07a464c4f310fda60b31da87a --- /dev/null +++ b/node_modules/needle/test/request_stream_spec.js @@ -0,0 +1,237 @@ +var fs = require('fs'), + needle = require('..'), + stream = require('stream'), + http = require('http'), + should = require('should'), + sinon = require('sinon'); + +var port = 2233; + +var node_major_ver = parseInt(process.version.split('.')[0].replace('v', '')); +var node_minor_ver = parseInt(process.version.split('.')[1]); + +describe('request stream length', function() { + + var server, writable; + + function createServer() { + return http.createServer(function(req, res) { + + req.on('data', function(chunk) { + // console.log(chunk.length); + }) + + req.on('end', function() { + res.writeHeader(200, { 'Content-Type': 'application/json'}) + res.end(JSON.stringify({ headers: req.headers })) + }) + + }) + } + + before(function(done) { + server = createServer(); + server.listen(port, done) + }) + + beforeEach(function() { + writable = new stream.Readable(); + writable._read = function() { + this.push('hello world'); + this.push(null); + } + }) + + after(function(done) { + server.close(done) + }) + + function send_request(opts, cb) { + needle.post('http://localhost:' + port, writable, opts, cb) + } + + describe('no stream_length set', function() { + + it('doesnt set Content-Length header', function(done) { + send_request({}, function(err, resp) { + should.not.exist(resp.body.headers['content-length']); + done() + }) + }) + + if (node_major_ver >= 10) { + it('returns 400 if Transfer-Encoding is set to a blank string', function(done) { + send_request({ headers: { 'Transfer-Encoding': '' }}, function(err, resp) { + should.not.exist(err); + resp.statusCode.should.eql(400); + done() + }) + }) + } else { + it('doesnt work if Transfer-Encoding is set to a blank string', function(done) { + send_request({ headers: { 'Transfer-Encoding': '' }}, function(err, resp) { + err.code.should.eql('ECONNRESET'); + done() + }) + }) + } + + it('works if Transfer-Encoding is not set', function(done) { + send_request({}, function(err, resp) { + should.not.exist(err); + resp.statusCode.should.eql(200); + done() + }) + }) + + }) + + describe('stream_length set to invalid value', function() { + + if (node_major_ver >= 10) { + + it('returns 400 if Transfer-Encoding is set to a blank string', function(done) { + send_request({ stream_length: 5, headers: { 'Transfer-Encoding': '' }}, function(err, resp) { + should.not.exist(err); + resp.statusCode.should.eql(400); + done() + }) + }) + + it('returns 400 if Transfer-Encoding is not set', function(done) { + send_request({ stream_length: 5 }, function(err, resp) { + should.not.exist(err); + resp.statusCode.should.eql(400); + done() + }) + }) + + } else { + + it('doesnt work if Transfer-Encoding is set to a blank string', function(done) { + send_request({ stream_length: 5, headers: { 'Transfer-Encoding': '' }}, function(err, resp) { + err.code.should.eql('ECONNRESET'); + done() + }) + }) + it('doesnt work if Transfer-Encoding is not set', function(done) { + send_request({ stream_length: 5 }, function(err, resp) { + err.code.should.eql('ECONNRESET'); + done() + }) + }) + + } + + }) + + describe('stream_length is set to valid value', function() { + + it('sets Content-Length header to that value', function(done) { + send_request({ stream_length: 11 }, function(err, resp) { + resp.body.headers['content-length'].should.eql('11'); + done() + }) + }) + + it('works if Transfer-Encoding is set to a blank string', function(done) { + send_request({ stream_length: 11, headers: { 'Transfer-Encoding': '' }}, function(err, resp) { + should.not.exist(err); + var code = node_major_ver == 10 && node_minor_ver > 15 ? 400 : 200; + resp.statusCode.should.eql(code); + done() + }) + }) + + it('works if Transfer-Encoding is not set', function(done) { + send_request({ stream_length: 11 }, function(err, resp) { + should.not.exist(err); + resp.statusCode.should.eql(200); + done() + }) + }) + + }) + + + describe('stream_length set to 0', function() { + + describe('stream with path', function() { + + var stub; + + beforeEach(function() { + writable.path = '/foo/bar'; + stub = sinon.stub(fs, 'stat').callsFake(function(path, cb) { + cb(null, { size: 11 }) + }) + }) + + afterEach(function() { + stub.restore(); + }) + + it('sets Content-Length header to streams length', function(done) { + send_request({ stream_length: 0 }, function(err, resp) { + resp.body.headers['content-length'].should.eql('11'); + done() + }) + }) + + it('works if Transfer-Encoding is set to a blank string', function(done) { + send_request({ stream_length: 0, headers: { 'Transfer-Encoding': '' }}, function(err, resp) { + should.not.exist(err); + var code = node_major_ver == 10 && node_minor_ver > 15 ? 400 : 200; + resp.statusCode.should.eql(code); + done() + }) + }) + + it('works if Transfer-Encoding is not set', function(done) { + send_request({ stream_length: 0 }, function(err, resp) { + should.not.exist(err); + resp.statusCode.should.eql(200); + done() + }) + }) + + }) + + describe('stream without path', function() { + + it('does not set Content-Length header', function(done) { + send_request({ stream_length: 0 }, function(err, resp) { + should.not.exist(resp.body.headers['content-length']); + done() + }) + }) + + if (node_major_ver >= 10) { + it('returns 400 if Transfer-Encoding is set to a blank string', function(done) { + send_request({ stream_length: 0, headers: { 'Transfer-Encoding': '' }}, function(err, resp) { + should.not.exist(err); + resp.statusCode.should.eql(400); + done() + }) + }) + } else { + it('throws ECONNRESET if Transfer-Encoding is set to a blank string', function(done) { + send_request({ stream_length: 0, headers: { 'Transfer-Encoding': '' }}, function(err, resp) { + err.code.should.eql('ECONNRESET'); + done() + }) + }) + } + + it('works if Transfer-Encoding is not set', function(done) { + send_request({ stream_length: 0 }, function(err, resp) { + should.not.exist(err); + resp.statusCode.should.eql(200); + done() + }) + }) + }) + + }) + +}) diff --git a/node_modules/needle/test/response_stream_spec.js b/node_modules/needle/test/response_stream_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..a0ccef8e40a4e8dca7ca6a48ed5a115258df0c80 --- /dev/null +++ b/node_modules/needle/test/response_stream_spec.js @@ -0,0 +1,138 @@ +var should = require('should'), + needle = require('./../'), + http = require('http'), + stream = require('stream'), + fs = require('fs'), + port = 11111, + server; + +describe('response streams', function() { + + describe('when the server sends back json', function(){ + + before(function(done) { + server = http.createServer(function(req, res) { + res.setHeader('Content-Type', 'application/json') + res.end('{"foo":"bar"}') + }).listen(port, done); + }); + + after(function(done) { + server.close(done); + }) + + describe('and the client uses streams', function(){ + + it('creates a proper streams2 stream', function(done) { + var stream = needle.get('localhost:' + port) + + // newer node versions set this to null instead of false + var bool = !!stream._readableState.flowing; + should.equal(false, bool); + + var readableCalled = false; + stream.on('readable', function() { + readableCalled = true; + }) + + stream.on('finish', function() { + readableCalled.should.be.true; + done(); + }); + + stream.resume(); + }) + + it('emits a single data item which is our JSON object', function(done) { + var stream = needle.get('localhost:' + port) + + var chunks = []; + stream.on('readable', function () { + while (chunk = this.read()) { + chunk.should.be.an.Object; + chunks.push(chunk); + } + }) + + stream.on('done', function () { + chunks.should.have.length(1) + chunks[0].should.have.property('foo', 'bar'); + done(); + }); + }) + + it('emits a raw buffer if we do not want to parse JSON', function(done) { + var stream = needle.get('localhost:' + port, { parse: false }) + + var chunks = []; + stream.on('readable', function () { + while (chunk = this.read()) { + Buffer.isBuffer(chunk).should.be.true; + chunks.push(chunk); + } + }) + + stream.on('done', function() { + var body = Buffer.concat(chunks).toString(); + body.should.equal('{"foo":"bar"}') + done(); + }); + }) + + }) + }) + + describe('when the server sends back what was posted to it', function () { + var file = 'asdf.txt'; + + before(function(done){ + server = http.createServer(function(req, res) { + res.setHeader('Content-Type', 'application/octet') + req.pipe(res); + }).listen(port); + + fs.writeFile(file, 'contents of stream', done); + }); + + after(function(done){ + server.close(); + fs.unlink(file, done); + }) + + it('can PUT a stream', function (done) { + var stream = needle.put('localhost:' + port, fs.createReadStream(file), { stream: true }); + + var chunks = []; + stream.on('readable', function () { + while (chunk = this.read()) { + Buffer.isBuffer(chunk).should.be.true; + chunks.push(chunk); + } + }) + + stream.on('end', function () { + var body = Buffer.concat(chunks).toString(); + body.should.equal('contents of stream') + done(); + }); + }); + + it('can PATCH a stream', function (done) { + var stream = needle.patch('localhost:' + port, fs.createReadStream(file), { stream: true }); + + var chunks = []; + stream.on('readable', function () { + while (chunk = this.read()) { + Buffer.isBuffer(chunk).should.be.true; + chunks.push(chunk); + } + }) + + stream.on('end', function () { + var body = Buffer.concat(chunks).toString(); + body.should.equal('contents of stream') + done(); + }); + }); + }) +}) diff --git a/node_modules/needle/test/socket_cleanup_spec.js b/node_modules/needle/test/socket_cleanup_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..483b4620ec03de2e26202f49777d2714b4a41f0c --- /dev/null +++ b/node_modules/needle/test/socket_cleanup_spec.js @@ -0,0 +1,79 @@ +var should = require('should'), + needle = require('./../'), + fs = require('fs'), + https = require('https'), + stream = require('stream'); + +describe('socket cleanup', function(){ + + var outFile = 'test/tmp'; + var httpAgent, readStream, writeStream + + var file = 'ubuntu-21.04-desktop-amd64.iso', + url = 'https://releases.ubuntu.com/21.04/' + file; + + function getActiveSockets() { + return Object.keys(httpAgent.sockets).length + } + + before(function() { + httpAgent = new https.Agent({ + keepAlive : true, + maxSockets : 1 + }); + }) + + after(function() { + httpAgent.destroy() + fs.unlinkSync(outFile); + }) + + it('should cleanup sockets on ERR_STREAM_PREMATURE_CLOSE (using .pipe)', function(done) { + getActiveSockets().should.eql(0); + + var resp = needle.get(url, { agent: httpAgent }); + var writable = fs.createWriteStream(outFile); + resp.pipe(writable); + + writable.on('close', function(e) { + if (!resp.done) resp.abort(); + }) + + setTimeout(function() { + getActiveSockets().should.eql(1); + writable.destroy(); + }, 50); + + setTimeout(function() { + getActiveSockets().should.eql(0); + done(); + }, 500); // takes a bit + }) + + it('should cleanup sockets on ERR_STREAM_PREMATURE_CLOSE (using stream.pipeline)', function(done) { + if (!stream.pipeline) + return done() + + getActiveSockets().should.eql(0); + + var resp = needle.get(url, { agent: httpAgent }); + var writable = fs.createWriteStream(outFile); + + stream.pipeline(resp, writable, function(err) { + err.code.should.eql('ERR_STREAM_PREMATURE_CLOSE') + // if (err) resp.request.destroy(); + }); + + setTimeout(function() { + getActiveSockets().should.eql(1); + writable.destroy(); + }, 50); + + setTimeout(function() { + getActiveSockets().should.eql(0); + done(); + }, 1000); // takes a bit + + }) + +}) \ No newline at end of file diff --git a/node_modules/needle/test/socket_pool_spec.js b/node_modules/needle/test/socket_pool_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..75080bdfb6e5fb45d20dcfd345b1d9b6309aeedd --- /dev/null +++ b/node_modules/needle/test/socket_pool_spec.js @@ -0,0 +1,67 @@ +var needle = require('../'), + should = require('should'), + http = require('http'); + +var server, port = 11112; + +describe('socket reuse', function() { + + var httpAgent = new http.Agent({ + keepAlive : true, + maxSockets : 1 + }); + + before(function(done) { + server = http.createServer(function(req, res) { + res.setHeader('Content-Type', 'application/json'); + setTimeout(function() { + res.end('{"foo":"bar"}'); + }, 50); + }).listen(port, done); + }); + + after(function(done) { + httpAgent.destroy(); + server.close(done); + }); + + describe('when sockets are reused', function() { + + it('does not duplicate listeners on .end', function(done) { + + var last_error; + var count = 10; + + function completed(err) { + --count || done(last_error); + } + + function send() { + needle.get('localhost:' + port, { agent: httpAgent }, function(err, resp) { + if (err) + throw new Error("Unexpected error: " + err); + + // lets go through all sockets and inspect all socket objects + for (hostTarget in httpAgent.sockets) { + httpAgent.sockets[hostTarget].forEach(function(socket) { + // normally, there are 2 internal listeners and 1 needle sets up, + // but to be sure the test does not fail even if newer node versions + // introduce additional listeners, we use a higher limit. + try { + socket.listeners('end').length.should.be.below(5, "too many listeners on the socket object's end event"); + } catch (e) { + last_error = e; + } + }); + } + + completed(); + }); + } + + for (var i = 0; i < count; i++) { + send(); + } + }); + }); +}); diff --git a/node_modules/needle/test/stream_events_spec.js b/node_modules/needle/test/stream_events_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..57ef994651f6d60f8ba5b706f45a5a35ff9e7406 --- /dev/null +++ b/node_modules/needle/test/stream_events_spec.js @@ -0,0 +1,144 @@ +var needle = require('../'), + fs = require('fs'), + should = require('should'), + helpers = require('./helpers'); + +describe('stream events', function() { + + var server, + port = 3456, + responseData, + serverOpts = {}, + requestHandler = function(req, res) { res.end('OK') } + + before(function() { + var opts = { + port: port, + handler: function(req, res) { requestHandler(req, res) } + } + server = helpers.server(opts); + }) + + after(function() { + server.close(); + }) + + beforeEach(function() { + responseData = ''; + }) + + describe('when consuming data directly', function() { + + function send_request(opts, cb) { + return needle + .get('http://localhost:' + port, opts) + .on('data', function(data) { responseData += data }) + } + + describe('and request stream fails', function() { + + it('emits done event with error', function(done) { + requestHandler = function(req, res) { req.socket.destroy() } + + send_request({}).on('done', function(err) { + err.code.should.eql('ECONNRESET'); + responseData.should.eql(''); + done() + }) + }) + + }) + + describe('and request succeeds but decoding fails', function() { + + it('emits done event without error', function(done) { + requestHandler = function(req, res) { + res.setHeader('Content-Type', 'application/json') + res.end('invalid:json') + } + + send_request({ json: true }).on('done', function(err) { + should.not.exist(err); + responseData.should.eql('invalid:json'); + done() + }) + }) + + }) + + describe('and request succeeds and pipeline works ok', function() { + + it('emits done event without error', function(done) { + requestHandler = function(req, res) { res.end('{"ok":1}') } + + send_request({ json: true }).on('done', function(err) { + should.not.exist(err); + responseData.should.eql('{"ok":1}'); + done() + }) + }) + + }) + + }) + + describe('when piping to a fs writableStream', function() { + + var outFile = 'test/tmp.dat'; + + function send_request(opts, cb) { + return needle + .get('http://localhost:' + port, opts) + .pipe(fs.createWriteStream(outFile)) + .on('data', function(data) { responseData += data }) + } + + after(function(done) { + fs.unlink(outFile, done) + }) + + describe('and request stream fails', function() { + + it('final stream emits done event with error', function(done) { + requestHandler = function(req, res) { req.socket.destroy() } + + send_request({}).on('done', function(err) { + err.code.should.eql('ECONNRESET'); + done() + }) + }) + + }) + + describe('and request succeeds but decoding fails', function() { + + it('final stream emits done event without error', function(done) { + requestHandler = function(req, res) { + res.setHeader('Content-Type', 'application/json') + res.end('invalid:json') + } + + send_request({ json: true }).on('done', function(err) { + should.not.exist(err); + done() + }) + }) + + }) + + describe('and request succeeds and pipeline works ok', function() { + + it('final stream emits done event without error', function(done) { + requestHandler = function(req, res) { res.end('{"ok":1}') } + + send_request({ json: true }).on('done', function(err) { + should.not.exist(err); + done() + }) + }) + + }) + + }) + +}) \ No newline at end of file diff --git a/node_modules/needle/test/uri_modifier_spec.js b/node_modules/needle/test/uri_modifier_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..1a12a36caf36e03d05cb03d33309648fc2256e2a --- /dev/null +++ b/node_modules/needle/test/uri_modifier_spec.js @@ -0,0 +1,46 @@ +var needle = require('../'), + sinon = require('sinon'), + should = require('should'), + http = require('http'), + helpers = require('./helpers'); + +var port = 3456; + +describe('uri_modifier config parameter function', function() { + + var server, uri; + + function send_request(mw, cb) { + needle.get(uri, { uri_modifier: mw }, cb); + } + + before(function(done){ + server = helpers.server({ port: port }, done); + }) + + after(function(done) { + server.close(done); + }) + + describe('modifies uri', function() { + + var path = '/foo/replace'; + + before(function() { + uri = 'localhost:' + port + path + }); + + it('should modify path', function(done) { + send_request(function(uri) { + return uri.replace('/replace', ''); + }, function(err, res) { + should.not.exist(err); + should(res.req.path).be.exactly('/foo'); + done(); + }); + + }); + + }) + +}) diff --git a/node_modules/needle/test/url_spec.js b/node_modules/needle/test/url_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..5154d5849aa0096e4f857cb9ad2f265f53d55b49 --- /dev/null +++ b/node_modules/needle/test/url_spec.js @@ -0,0 +1,155 @@ +var needle = require('../'), + sinon = require('sinon'), + should = require('should'), + http = require('http'), + helpers = require('./helpers'); + +var port = 3456; + +describe('urls', function() { + + var server, url; + + function send_request(cb) { + return needle.get(url, cb); + } + + before(function(done){ + server = helpers.server({ port: port }, done); + }) + + after(function(done) { + server.close(done); + }) + + describe('null URL', function(){ + + it('throws', function(){ + (function() { + send_request() + }).should.throw(); + }) + + }) + + describe('invalid protocol', function(){ + + before(function() { + url = 'foo://google.com/what' + }) + + it('does not throw', function(done) { + (function() { + send_request(function(err) { + done(); + }) + }).should.not.throw() + }) + + it('returns an error', function(done) { + send_request(function(err) { + err.should.be.an.Error; + err.code.should.match(/ENOTFOUND|EADDRINFO|EAI_AGAIN/) + done(); + }) + }) + + }) + + describe('invalid host', function(){ + + before(function() { + url = 'http://s1\\\u0002.com/' + }) + + it('fails', function(done) { + (function() { + send_request(function(){ }) + }.should.throw(TypeError)) + done() + }) + + }) + +/* + describe('invalid path', function(){ + + before(function() { + url = 'http://www.google.com\\\/x\\\ %^&*() /x2.com/' + }) + + it('fails', function(done) { + send_request(function(err) { + err.should.be.an.Error; + done(); + }) + }) + + }) +*/ + + describe('valid protocol and path', function() { + + before(function() { + url = 'http://localhost:' + port + '/foo'; + }) + + it('works', function(done) { + send_request(function(err){ + should.not.exist(err); + done(); + }) + }) + + }) + + describe('no protocol but with slashes and valid path', function() { + + before(function() { + url = '//localhost:' + port + '/foo'; + }) + + it('works', function(done) { + send_request(function(err){ + should.not.exist(err); + done(); + }) + }) + + }) + + describe('no protocol nor slashes and valid path', function() { + + before(function() { + url = 'localhost:' + port + '/foo'; + }) + + it('works', function(done) { + send_request(function(err){ + should.not.exist(err); + done(); + }) + }) + + }) + + describe('double encoding', function() { + + var path = '/foo?email=' + encodeURIComponent('what-ever@Example.Com'); + + before(function() { + url = 'localhost:' + port + path + }); + + it('should not occur', function(done) { + send_request(function(err, res) { + should.not.exist(err); + should(res.req.path).be.exactly(path); + done(); + }); + + }); + + }) + +}) diff --git a/node_modules/needle/test/utils/formidable.js b/node_modules/needle/test/utils/formidable.js new file mode 100644 index 0000000000000000000000000000000000000000..ba1d983e2c16778fc6486f01e7797362865972a5 --- /dev/null +++ b/node_modules/needle/test/utils/formidable.js @@ -0,0 +1,17 @@ +var formidable = require('formidable'), + http = require('http'), + util = require('util'); + +var port = process.argv[2] || 8888; + +http.createServer(function(req, res) { + var form = new formidable.IncomingForm(); + form.parse(req, function(err, fields, files) { + res.writeHead(200, {'content-type': 'text/plain'}); + res.write('received upload:\n\n'); + console.log(util.inspect({fields: fields, files: files})) + res.end(util.inspect({fields: fields, files: files})); + }); +}).listen(port); + +console.log('HTTP server listening on port ' + port); \ No newline at end of file diff --git a/node_modules/needle/test/utils/proxy.js b/node_modules/needle/test/utils/proxy.js new file mode 100644 index 0000000000000000000000000000000000000000..531bf49354cb80d16fc964cce7a9c9127e82eb41 --- /dev/null +++ b/node_modules/needle/test/utils/proxy.js @@ -0,0 +1,62 @@ +var http = require('http'), + https = require('https'), + url = require('url'); + +var port = 1234, + log = true, + request_auth = false; + +http.createServer(function(request, response) { + + console.log(request.headers); + console.log("Got request: " + request.url); + console.log("Forwarding request to " + request.headers['host']); + + if (request_auth) { + if (!request.headers['proxy-authorization']) { + response.writeHead(407, {'Proxy-Authenticate': 'Basic realm="proxy.com"'}) + return response.end('Hello.'); + } + } + + var remote = url.parse(request.url); + var protocol = remote.protocol == 'https:' ? https : http; + + var opts = { + host: request.headers['host'], + port: remote.port || (remote.protocol == 'https:' ? 443 : 80), + method: request.method, + path: remote.pathname, + headers: request.headers + } + + var proxy_request = protocol.request(opts, function(proxy_response){ + + proxy_response.on('data', function(chunk) { + if (log) console.log(chunk.toString()); + response.write(chunk, 'binary'); + }); + proxy_response.on('end', function() { + response.end(); + }); + + response.writeHead(proxy_response.statusCode, proxy_response.headers); + }); + + request.on('data', function(chunk) { + if (log) console.log(chunk.toString()); + proxy_request.write(chunk, 'binary'); + }); + + request.on('end', function() { + proxy_request.end(); + }); + +}).listen(port); + +process.on('uncaughtException', function(err){ + console.log('Uncaught exception!'); + console.log(err); +}); + +console.log("Proxy server listening on port " + port); diff --git a/node_modules/needle/test/utils/test.js b/node_modules/needle/test/utils/test.js new file mode 100644 index 0000000000000000000000000000000000000000..8d58d70f2ae296f92fa7c9b849026ba46a5bdfc6 --- /dev/null +++ b/node_modules/needle/test/utils/test.js @@ -0,0 +1,104 @@ +// TODO: write specs. :) + +var fs = require('fs'), + client = require('./../../'); + +process.env.DEBUG = true; + +var response_callback = function(err, resp, body){ + console.log(err); + if(resp) console.log("Got status code " + resp.statusCode) + console.log(body); +} + +function simple_head(){ + client.head('http://www.amazon.com', response_callback); +} + +function simple_get(){ + client.get('http://www.nodejs.org', response_callback); +} + +function proxy_get(){ + client.get('https://www.google.com/search?q=nodejs', {proxy: 'http://localhost:1234'}, response_callback); +} + +function auth_get(){ + client.get('https://www.twitter.com', {username: 'asd', password: '123'}, response_callback); +} + +function simple_post(url){ + + var data = { + foo: 'bar', + baz: { + nested: 'attribute' + } + } + + client.post(url, data, response_callback); + +} + +function multipart_post(url){ + + var filename = 'test_file.txt'; + var data = 'Plain text data.\nLorem ipsum dolor sit amet.\nBla bla bla.\n'; + fs.writeFileSync(filename, data); + + var black_pixel = Buffer.from("data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=".replace(/^data:image\/\w+;base64,/, ""), "base64"); + + var data = { + foo: 'bar', + bar: 'baz', + nested: { + my_document: { file: filename, content_type: 'text/plain' }, + even: { + more: 'nesting' + } + }, + pixel: { filename: 'black_pixel.gif', buffer: black_pixel, content_type: 'image/gif' }, + field2: {value: JSON.stringify({"json":[ {"one":1}, {"two":2} ]}), content_type: 'application/json' } + } + + client.post(url, data, {multipart: true}, function(err, resp, body){ + + console.log(err); + console.log("Got status code " + resp.statusCode) + console.log(body); + fs.unlink(filename); + + }); + +} + +switch(process.argv[2]){ + case 'head': + simple_head(); + break; + case 'get': + simple_get(); + break; + case 'auth': + auth_get(); + break; + case 'proxy': + proxy_get(); + break; + case 'post': + simple_post(process.argv[3] || 'http://posttestserver.com/post.php'); + break; + case 'multipart': + multipart_post(process.argv[3] || 'http://posttestserver.com/post.php?dir=example'); + break; + case 'all': + simple_head(); + simple_get(); + auth_get(); + proxy_get(); + simple_post(process.argv[3] || 'http://posttestserver.com/post.php'); + multipart_post(process.argv[3] || 'http://posttestserver.com/post.php?dir=example'); + break; + default: + console.log("Usage: ./test.js [head|get|auth|proxy|multipart]") +} diff --git a/node_modules/negotiator/HISTORY.md b/node_modules/negotiator/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..63d537d3f681143b17f9250b199a865297b020be --- /dev/null +++ b/node_modules/negotiator/HISTORY.md @@ -0,0 +1,114 @@ +1.0.0 / 2024-08-31 +================== + + * Drop support for node <18 + * Added an option preferred encodings array #59 + +0.6.3 / 2022-01-22 +================== + + * Revert "Lazy-load modules from main entry point" + +0.6.2 / 2019-04-29 +================== + + * Fix sorting charset, encoding, and language with extra parameters + +0.6.1 / 2016-05-02 +================== + + * perf: improve `Accept` parsing speed + * perf: improve `Accept-Charset` parsing speed + * perf: improve `Accept-Encoding` parsing speed + * perf: improve `Accept-Language` parsing speed + +0.6.0 / 2015-09-29 +================== + + * Fix including type extensions in parameters in `Accept` parsing + * Fix parsing `Accept` parameters with quoted equals + * Fix parsing `Accept` parameters with quoted semicolons + * Lazy-load modules from main entry point + * perf: delay type concatenation until needed + * perf: enable strict mode + * perf: hoist regular expressions + * perf: remove closures getting spec properties + * perf: remove a closure from media type parsing + * perf: remove property delete from media type parsing + +0.5.3 / 2015-05-10 +================== + + * Fix media type parameter matching to be case-insensitive + +0.5.2 / 2015-05-06 +================== + + * Fix comparing media types with quoted values + * Fix splitting media types with quoted commas + +0.5.1 / 2015-02-14 +================== + + * Fix preference sorting to be stable for long acceptable lists + +0.5.0 / 2014-12-18 +================== + + * Fix list return order when large accepted list + * Fix missing identity encoding when q=0 exists + * Remove dynamic building of Negotiator class + +0.4.9 / 2014-10-14 +================== + + * Fix error when media type has invalid parameter + +0.4.8 / 2014-09-28 +================== + + * Fix all negotiations to be case-insensitive + * Stable sort preferences of same quality according to client order + * Support Node.js 0.6 + +0.4.7 / 2014-06-24 +================== + + * Handle invalid provided languages + * Handle invalid provided media types + +0.4.6 / 2014-06-11 +================== + + * Order by specificity when quality is the same + +0.4.5 / 2014-05-29 +================== + + * Fix regression in empty header handling + +0.4.4 / 2014-05-29 +================== + + * Fix behaviors when headers are not present + +0.4.3 / 2014-04-16 +================== + + * Handle slashes on media params correctly + +0.4.2 / 2014-02-28 +================== + + * Fix media type sorting + * Handle media types params strictly + +0.4.1 / 2014-01-16 +================== + + * Use most specific matches + +0.4.0 / 2014-01-09 +================== + + * Remove preferred prefix from methods diff --git a/node_modules/negotiator/LICENSE b/node_modules/negotiator/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ea6b9e2e9ac251526c95df2dd995cf5f1e861854 --- /dev/null +++ b/node_modules/negotiator/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Federico Romero +Copyright (c) 2012-2014 Isaac Z. Schlueter +Copyright (c) 2014-2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/negotiator/README.md b/node_modules/negotiator/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6fb7f2db31e670a487e3aa21a99fdc9c3978e6be --- /dev/null +++ b/node_modules/negotiator/README.md @@ -0,0 +1,212 @@ +# negotiator + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +An HTTP content negotiator for Node.js + +## Installation + +```sh +$ npm install negotiator +``` + +## API + +```js +var Negotiator = require('negotiator') +``` + +### Accept Negotiation + +```js +availableMediaTypes = ['text/html', 'text/plain', 'application/json'] + +// The negotiator constructor receives a request object +negotiator = new Negotiator(request) + +// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' + +negotiator.mediaTypes() +// -> ['text/html', 'image/jpeg', 'application/*'] + +negotiator.mediaTypes(availableMediaTypes) +// -> ['text/html', 'application/json'] + +negotiator.mediaType(availableMediaTypes) +// -> 'text/html' +``` + +You can check a working example at `examples/accept.js`. + +#### Methods + +##### mediaType() + +Returns the most preferred media type from the client. + +##### mediaType(availableMediaType) + +Returns the most preferred media type from a list of available media types. + +##### mediaTypes() + +Returns an array of preferred media types ordered by the client preference. + +##### mediaTypes(availableMediaTypes) + +Returns an array of preferred media types ordered by priority from a list of +available media types. + +### Accept-Language Negotiation + +```js +negotiator = new Negotiator(request) + +availableLanguages = ['en', 'es', 'fr'] + +// Let's say Accept-Language header is 'en;q=0.8, es, pt' + +negotiator.languages() +// -> ['es', 'pt', 'en'] + +negotiator.languages(availableLanguages) +// -> ['es', 'en'] + +language = negotiator.language(availableLanguages) +// -> 'es' +``` + +You can check a working example at `examples/language.js`. + +#### Methods + +##### language() + +Returns the most preferred language from the client. + +##### language(availableLanguages) + +Returns the most preferred language from a list of available languages. + +##### languages() + +Returns an array of preferred languages ordered by the client preference. + +##### languages(availableLanguages) + +Returns an array of preferred languages ordered by priority from a list of +available languages. + +### Accept-Charset Negotiation + +```js +availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' + +negotiator.charsets() +// -> ['utf-8', 'iso-8859-1', 'utf-7'] + +negotiator.charsets(availableCharsets) +// -> ['utf-8', 'iso-8859-1'] + +negotiator.charset(availableCharsets) +// -> 'utf-8' +``` + +You can check a working example at `examples/charset.js`. + +#### Methods + +##### charset() + +Returns the most preferred charset from the client. + +##### charset(availableCharsets) + +Returns the most preferred charset from a list of available charsets. + +##### charsets() + +Returns an array of preferred charsets ordered by the client preference. + +##### charsets(availableCharsets) + +Returns an array of preferred charsets ordered by priority from a list of +available charsets. + +### Accept-Encoding Negotiation + +```js +availableEncodings = ['identity', 'gzip'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' + +negotiator.encodings() +// -> ['gzip', 'identity', 'compress'] + +negotiator.encodings(availableEncodings) +// -> ['gzip', 'identity'] + +negotiator.encoding(availableEncodings) +// -> 'gzip' +``` + +You can check a working example at `examples/encoding.js`. + +#### Methods + +##### encoding() + +Returns the most preferred encoding from the client. + +##### encoding(availableEncodings) + +Returns the most preferred encoding from a list of available encodings. + +##### encoding(availableEncodings, { preferred }) + +Returns the most preferred encoding from a list of available encodings, while prioritizing based on `preferred` array between same-quality encodings. + +##### encodings() + +Returns an array of preferred encodings ordered by the client preference. + +##### encodings(availableEncodings) + +Returns an array of preferred encodings ordered by priority from a list of +available encodings. + +##### encodings(availableEncodings, { preferred }) + +Returns an array of preferred encodings ordered by priority from a list of +available encodings, while prioritizing based on `preferred` array between same-quality encodings. + +## See Also + +The [accepts](https://npmjs.org/package/accepts#readme) module builds on +this module and provides an alternative interface, mime type validation, +and more. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/negotiator.svg +[npm-url]: https://npmjs.org/package/negotiator +[node-version-image]: https://img.shields.io/node/v/negotiator.svg +[node-version-url]: https://nodejs.org/en/download/ +[coveralls-image]: https://img.shields.io/coveralls/jshttp/negotiator/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/negotiator?branch=master +[downloads-image]: https://img.shields.io/npm/dm/negotiator.svg +[downloads-url]: https://npmjs.org/package/negotiator +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/jshttp/negotiator/ci/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/negotiator/actions/workflows/ci.yml diff --git a/node_modules/negotiator/index.js b/node_modules/negotiator/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4f51315d6af4bda48533904adf1c530d1ac95a4a --- /dev/null +++ b/node_modules/negotiator/index.js @@ -0,0 +1,83 @@ +/*! + * negotiator + * Copyright(c) 2012 Federico Romero + * Copyright(c) 2012-2014 Isaac Z. Schlueter + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +var preferredCharsets = require('./lib/charset') +var preferredEncodings = require('./lib/encoding') +var preferredLanguages = require('./lib/language') +var preferredMediaTypes = require('./lib/mediaType') + +/** + * Module exports. + * @public + */ + +module.exports = Negotiator; +module.exports.Negotiator = Negotiator; + +/** + * Create a Negotiator instance from a request. + * @param {object} request + * @public + */ + +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } + + this.request = request; +} + +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; + +Negotiator.prototype.charsets = function charsets(available) { + return preferredCharsets(this.request.headers['accept-charset'], available); +}; + +Negotiator.prototype.encoding = function encoding(available, opts) { + var set = this.encodings(available, opts); + return set && set[0]; +}; + +Negotiator.prototype.encodings = function encodings(available, options) { + var opts = options || {}; + return preferredEncodings(this.request.headers['accept-encoding'], available, opts.preferred); +}; + +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; + +Negotiator.prototype.languages = function languages(available) { + return preferredLanguages(this.request.headers['accept-language'], available); +}; + +Negotiator.prototype.mediaType = function mediaType(available) { + var set = this.mediaTypes(available); + return set && set[0]; +}; + +Negotiator.prototype.mediaTypes = function mediaTypes(available) { + return preferredMediaTypes(this.request.headers.accept, available); +}; + +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; diff --git a/node_modules/negotiator/lib/charset.js b/node_modules/negotiator/lib/charset.js new file mode 100644 index 0000000000000000000000000000000000000000..cdd014803474a4b76b981c475a32ebcaa81a36e5 --- /dev/null +++ b/node_modules/negotiator/lib/charset.js @@ -0,0 +1,169 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredCharsets; +module.exports.preferredCharsets = preferredCharsets; + +/** + * Module variables. + * @private + */ + +var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Charset header. + * @private + */ + +function parseAcceptCharset(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var charset = parseCharset(accepts[i].trim(), i); + + if (charset) { + accepts[j++] = charset; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a charset from the Accept-Charset header. + * @private + */ + +function parseCharset(str, i) { + var match = simpleCharsetRegExp.exec(str); + if (!match) return null; + + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + charset: charset, + q: q, + i: i + }; +} + +/** + * Get the priority of a charset. + * @private + */ + +function getCharsetPriority(charset, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(charset, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the charset. + * @private + */ + +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} + +/** + * Get the preferred charsets from an Accept-Charset header. + * @public + */ + +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all charsets + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullCharset); + } + + var priorities = provided.map(function getPriority(type, index) { + return getCharsetPriority(type, accepts, index); + }); + + // sorted list of accepted charsets + return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full charset string. + * @private + */ + +function getFullCharset(spec) { + return spec.charset; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/encoding.js b/node_modules/negotiator/lib/encoding.js new file mode 100644 index 0000000000000000000000000000000000000000..9ebb633d67743316863baf3504bfe1d47d53b033 --- /dev/null +++ b/node_modules/negotiator/lib/encoding.js @@ -0,0 +1,205 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredEncodings; +module.exports.preferredEncodings = preferredEncodings; + +/** + * Module variables. + * @private + */ + +var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Encoding header. + * @private + */ + +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; + + for (var i = 0, j = 0; i < accepts.length; i++) { + var encoding = parseEncoding(accepts[i].trim(), i); + + if (encoding) { + accepts[j++] = encoding; + hasIdentity = hasIdentity || specify('identity', encoding); + minQuality = Math.min(minQuality, encoding.q || 1); + } + } + + if (!hasIdentity) { + /* + * If identity doesn't explicitly appear in the accept-encoding header, + * it's added to the list of acceptable encoding with the lowest q + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse an encoding from the Accept-Encoding header. + * @private + */ + +function parseEncoding(str, i) { + var match = simpleEncodingRegExp.exec(str); + if (!match) return null; + + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + encoding: encoding, + q: q, + i: i + }; +} + +/** + * Get the priority of an encoding. + * @private + */ + +function getEncodingPriority(encoding, accepted, index) { + var priority = {encoding: encoding, o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(encoding, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the encoding. + * @private + */ + +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } + + return { + encoding: encoding, + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred encodings from an Accept-Encoding header. + * @public + */ + +function preferredEncodings(accept, provided, preferred) { + var accepts = parseAcceptEncoding(accept || ''); + + var comparator = preferred ? function comparator (a, b) { + if (a.q !== b.q) { + return b.q - a.q // higher quality first + } + + var aPreferred = preferred.indexOf(a.encoding) + var bPreferred = preferred.indexOf(b.encoding) + + if (aPreferred === -1 && bPreferred === -1) { + // consider the original specifity/order + return (b.s - a.s) || (a.o - b.o) || (a.i - b.i) + } + + if (aPreferred !== -1 && bPreferred !== -1) { + return aPreferred - bPreferred // consider the preferred order + } + + return aPreferred === -1 ? 1 : -1 // preferred first + } : compareSpecs; + + if (!provided) { + // sorted list of all encodings + return accepts + .filter(isQuality) + .sort(comparator) + .map(getFullEncoding); + } + + var priorities = provided.map(function getPriority(type, index) { + return getEncodingPriority(type, accepts, index); + }); + + // sorted list of accepted encodings + return priorities.filter(isQuality).sort(comparator).map(function getEncoding(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i); +} + +/** + * Get full encoding string. + * @private + */ + +function getFullEncoding(spec) { + return spec.encoding; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/language.js b/node_modules/negotiator/lib/language.js new file mode 100644 index 0000000000000000000000000000000000000000..a23167252719be841ad570eb655a703a4ae8fe9e --- /dev/null +++ b/node_modules/negotiator/lib/language.js @@ -0,0 +1,179 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredLanguages; +module.exports.preferredLanguages = preferredLanguages; + +/** + * Module variables. + * @private + */ + +var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Language header. + * @private + */ + +function parseAcceptLanguage(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var language = parseLanguage(accepts[i].trim(), i); + + if (language) { + accepts[j++] = language; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a language from the Accept-Language header. + * @private + */ + +function parseLanguage(str, i) { + var match = simpleLanguageRegExp.exec(str); + if (!match) return null; + + var prefix = match[1] + var suffix = match[2] + var full = prefix + + if (suffix) full += "-" + suffix; + + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} + +/** + * Get the priority of a language. + * @private + */ + +function getLanguagePriority(language, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(language, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the language. + * @private + */ + +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred languages from an Accept-Language header. + * @public + */ + +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all languages + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullLanguage); + } + + var priorities = provided.map(function getPriority(type, index) { + return getLanguagePriority(type, accepts, index); + }); + + // sorted list of accepted languages + return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full language string. + * @private + */ + +function getFullLanguage(spec) { + return spec.full; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/mediaType.js b/node_modules/negotiator/lib/mediaType.js new file mode 100644 index 0000000000000000000000000000000000000000..8e402ea88394c040bf5964f65b8eba33b50bd4a1 --- /dev/null +++ b/node_modules/negotiator/lib/mediaType.js @@ -0,0 +1,294 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredMediaTypes; +module.exports.preferredMediaTypes = preferredMediaTypes; + +/** + * Module variables. + * @private + */ + +var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept header. + * @private + */ + +function parseAccept(accept) { + var accepts = splitMediaTypes(accept); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var mediaType = parseMediaType(accepts[i].trim(), i); + + if (mediaType) { + accepts[j++] = mediaType; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a media type from the Accept header. + * @private + */ + +function parseMediaType(str, i) { + var match = simpleMediaTypeRegExp.exec(str); + if (!match) return null; + + var params = Object.create(null); + var q = 1; + var subtype = match[2]; + var type = match[1]; + + if (match[3]) { + var kvps = splitParameters(match[3]).map(splitKeyValuePair); + + for (var j = 0; j < kvps.length; j++) { + var pair = kvps[j]; + var key = pair[0].toLowerCase(); + var val = pair[1]; + + // get the value, unwrapping quotes + var value = val && val[0] === '"' && val[val.length - 1] === '"' + ? val.slice(1, -1) + : val; + + if (key === 'q') { + q = parseFloat(value); + break; + } + + // store parameter + params[key] = value; + } + } + + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i + }; +} + +/** + * Get the priority of a media type. + * @private + */ + +function getMediaTypePriority(type, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(type, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the media type. + * @private + */ + +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; + } + + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } +} + +/** + * Get the preferred media types from an Accept header. + * @public + */ + +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + + if (!provided) { + // sorted list of all types + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullType); + } + + var priorities = provided.map(function getPriority(type, index) { + return getMediaTypePriority(type, accepts, index); + }); + + // sorted list of accepted types + return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full type string. + * @private + */ + +function getFullType(spec) { + return spec.type + '/' + spec.subtype; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} + +/** + * Count the number of quotes in a string. + * @private + */ + +function quoteCount(string) { + var count = 0; + var index = 0; + + while ((index = string.indexOf('"', index)) !== -1) { + count++; + index++; + } + + return count; +} + +/** + * Split a key value pair. + * @private + */ + +function splitKeyValuePair(str) { + var index = str.indexOf('='); + var key; + var val; + + if (index === -1) { + key = str; + } else { + key = str.slice(0, index); + val = str.slice(index + 1); + } + + return [key, val]; +} + +/** + * Split an Accept header into media types. + * @private + */ + +function splitMediaTypes(accept) { + var accepts = accept.split(','); + + for (var i = 1, j = 0; i < accepts.length; i++) { + if (quoteCount(accepts[j]) % 2 == 0) { + accepts[++j] = accepts[i]; + } else { + accepts[j] += ',' + accepts[i]; + } + } + + // trim accepts + accepts.length = j + 1; + + return accepts; +} + +/** + * Split a string of parameters. + * @private + */ + +function splitParameters(str) { + var parameters = str.split(';'); + + for (var i = 1, j = 0; i < parameters.length; i++) { + if (quoteCount(parameters[j]) % 2 == 0) { + parameters[++j] = parameters[i]; + } else { + parameters[j] += ';' + parameters[i]; + } + } + + // trim parameters + parameters.length = j + 1; + + for (var i = 0; i < parameters.length; i++) { + parameters[i] = parameters[i].trim(); + } + + return parameters; +} diff --git a/node_modules/negotiator/package.json b/node_modules/negotiator/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e4bdc1ef4f74812bfc15dbd980eab1f57282b753 --- /dev/null +++ b/node_modules/negotiator/package.json @@ -0,0 +1,43 @@ +{ + "name": "negotiator", + "description": "HTTP content negotiation", + "version": "1.0.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Federico Romero ", + "Isaac Z. Schlueter (http://blog.izs.me/)" + ], + "license": "MIT", + "keywords": [ + "http", + "content negotiation", + "accept", + "accept-language", + "accept-encoding", + "accept-charset" + ], + "repository": "jshttp/negotiator", + "devDependencies": { + "eslint": "7.32.0", + "eslint-plugin-markdown": "2.2.1", + "mocha": "9.1.3", + "nyc": "15.1.0" + }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "index.js", + "README.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test:debug": "mocha --reporter spec --check-leaks --inspect --inspect-brk test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/next-tick/.editorconfig b/node_modules/next-tick/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..bd6d81eee2df1f0a051e6f998dc13f5c79872593 --- /dev/null +++ b/node_modules/next-tick/.editorconfig @@ -0,0 +1,16 @@ +# EditorConfig is awesome: http://EditorConfig.org + +# top-most EditorConfig file +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +trim_trailing_whitespace = true + +[*.md] +indent_size = 2 +indent_style = space +trim_trailing_whitespace = false diff --git a/node_modules/next-tick/.github/FUNDING.yml b/node_modules/next-tick/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..270b1ddf50fb80c3bdcae558168062414cd79d8d --- /dev/null +++ b/node_modules/next-tick/.github/FUNDING.yml @@ -0,0 +1 @@ +tidelift: "npm/next-tick" diff --git a/node_modules/next-tick/.lint b/node_modules/next-tick/.lint new file mode 100644 index 0000000000000000000000000000000000000000..ac7ad3a13a6f208639a7286d104ae94166cfbc26 --- /dev/null +++ b/node_modules/next-tick/.lint @@ -0,0 +1,16 @@ +@root + +module +es5 + +indent 2 +maxlen 100 +tabs + +ass +bitwise +nomen +plusplus +vars + +predef+ queueMicrotask, process, setImmediate, setTimeout, clearTimeout, document, MutationObserver, WebKitMutationObserver diff --git a/node_modules/next-tick/CHANGELOG.md b/node_modules/next-tick/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..f990e1c02cc5f15e0b4376506977ef17dfdfa5ac --- /dev/null +++ b/node_modules/next-tick/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [1.1.0](https://github.com/medikoo/next-tick/compare/v1.0.0...v1.1.0) (2020-02-11) + +### Features + +* Add support for queueMicrotask (Closes [#13](https://github.com/medikoo/next-tick/issues/13)) ([471986e](https://github.com/medikoo/next-tick/commit/471986ee5f7179a498850cc03138a5ed5b9a248c)) + +## Changelog for previous versions + +See `CHANGES` file diff --git a/node_modules/next-tick/CHANGES b/node_modules/next-tick/CHANGES new file mode 100644 index 0000000000000000000000000000000000000000..931a8a431370efc2221f104e7ae06eb5387d508a --- /dev/null +++ b/node_modules/next-tick/CHANGES @@ -0,0 +1,28 @@ +For recent changelog see CHANGELOG.md + +----- + +v1.0.0 -- 2016.06.09 +* In case MutationObserver based solution ensure all callbacks are propagated + even if any on the way crashes (fixes #3) +* Support older engines (as IE8) which see typeof setTimeout as 'object' +* Fix spelling of LICENSE +* Configure lint scripts + +v0.2.2 -- 2014.04.18 +- Do not rely on es5-ext's valid-callable. Replace it with simple internal function +- In MutationObserver fallback rely on text node instead of attribute and assure + mutation event is invoked by real change of data + +v0.2.1 -- 2014.02.24 +- Fix case in import path + +v0.2.0 -- 2014.02.24 +- Assure microtask resultion if MutationObserver is available (thanks @Raynos) #1 +- Unify validation of callback. TypeError is throw for any non callable input +- Move main module from `lib` to root directory +- Improve documentation +- Remove Makefile (it's environment agnostic pacakge) + +v0.1.0 -- 2012.08.29 +Initial diff --git a/node_modules/next-tick/LICENSE b/node_modules/next-tick/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..cfd3994f9d5d42ff7a8ad143253216761666c001 --- /dev/null +++ b/node_modules/next-tick/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2012-2020, Mariusz Nowak, @medikoo, medikoo.com + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/next-tick/README.md b/node_modules/next-tick/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7878e90bccba09921a35a1d60bcf376ad2a1eff6 --- /dev/null +++ b/node_modules/next-tick/README.md @@ -0,0 +1,41 @@ +# next-tick +## Environment agnostic nextTick polyfill + +To be used in environment agnostic modules that need nextTick functionality. + +- When run in Node.js `process.nextTick` is used +- In modern engines, microtask resolution is guaranteed by `queueMicrotask` +- In older browsers, `MutationObserver` is used as a fallback +- In other engines `setImmediate` or `setTimeout(fn, 0)` is used as fallback. +- If none of the above is supported module resolves to `null` + +## Installation +### NPM + +In your project path: + + $ npm install next-tick + +#### Browser + +To port it to Browser or any other (non CJS) environment, use your favorite CJS bundler. No favorite yet? Try: [Browserify](http://browserify.org/), [Webmake](https://github.com/medikoo/modules-webmake) or [Webpack](http://webpack.github.io/) + +## Tests [![Build Status](https://api.travis-ci.org/medikoo/next-tick.png?branch=master)](https://travis-ci.org/medikoo/next-tick) + + $ npm test + +## Security contact information + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. + +--- + +
+ + Get professional support for d with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/next-tick/index.js b/node_modules/next-tick/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4e3b2805b6f603c34fc22a5b074d80ef059b6383 --- /dev/null +++ b/node_modules/next-tick/index.js @@ -0,0 +1,74 @@ +'use strict'; + +var ensureCallable = function (fn) { + if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); + return fn; +}; + +var byObserver = function (Observer) { + var node = document.createTextNode(''), queue, currentQueue, i = 0; + new Observer(function () { + var callback; + if (!queue) { + if (!currentQueue) return; + queue = currentQueue; + } else if (currentQueue) { + queue = currentQueue.concat(queue); + } + currentQueue = queue; + queue = null; + if (typeof currentQueue === 'function') { + callback = currentQueue; + currentQueue = null; + callback(); + return; + } + node.data = (i = ++i % 2); // Invoke other batch, to handle leftover callbacks in case of crash + while (currentQueue) { + callback = currentQueue.shift(); + if (!currentQueue.length) currentQueue = null; + callback(); + } + }).observe(node, { characterData: true }); + return function (fn) { + ensureCallable(fn); + if (queue) { + if (typeof queue === 'function') queue = [queue, fn]; + else queue.push(fn); + return; + } + queue = fn; + node.data = (i = ++i % 2); + }; +}; + +module.exports = (function () { + // Node.js + if ((typeof process === 'object') && process && (typeof process.nextTick === 'function')) { + return process.nextTick; + } + + // queueMicrotask + if (typeof queueMicrotask === "function") { + return function (cb) { queueMicrotask(ensureCallable(cb)); }; + } + + // MutationObserver + if ((typeof document === 'object') && document) { + if (typeof MutationObserver === 'function') return byObserver(MutationObserver); + if (typeof WebKitMutationObserver === 'function') return byObserver(WebKitMutationObserver); + } + + // W3C Draft + // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html + if (typeof setImmediate === 'function') { + return function (cb) { setImmediate(ensureCallable(cb)); }; + } + + // Wide available standard + if ((typeof setTimeout === 'function') || (typeof setTimeout === 'object')) { + return function (cb) { setTimeout(ensureCallable(cb), 0); }; + } + + return null; +}()); diff --git a/node_modules/next-tick/package.json b/node_modules/next-tick/package.json new file mode 100644 index 0000000000000000000000000000000000000000..071c8ac6333b6d237e2e8d7e2af1077ada87cffa --- /dev/null +++ b/node_modules/next-tick/package.json @@ -0,0 +1,27 @@ +{ + "name": "next-tick", + "version": "1.1.0", + "description": "Environment agnostic nextTick polyfill", + "author": "Mariusz Nowak (http://www.medikoo.com/)", + "keywords": [ + "nexttick", + "setImmediate", + "setTimeout", + "async" + ], + "repository": { + "type": "git", + "url": "git://github.com/medikoo/next-tick.git" + }, + "devDependencies": { + "tad": "^3.0.1", + "xlint": "^0.2.2", + "xlint-jslint-medikoo": "^0.1.4" + }, + "scripts": { + "lint": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --no-cache --no-stream", + "lint-console": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --watch", + "test": "node node_modules/tad/bin/tad" + }, + "license": "ISC" +} diff --git a/node_modules/next-tick/test/index.js b/node_modules/next-tick/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6b22cf484c505f28063a8801b8d4c4c5ec44910c --- /dev/null +++ b/node_modules/next-tick/test/index.js @@ -0,0 +1,22 @@ +'use strict'; + +module.exports = function (t, a, d) { + var invoked; + + a(t(function () { + a(arguments.length, 0, "Arguments"); + invoked = true; + }), undefined, "Return"); + a(invoked, undefined, "Is not run immediately"); + setTimeout(function () { + a(invoked, true, "Run in next tick"); + invoked = []; + t(function () { invoked.push(0); }); + t(function () { invoked.push(1); }); + t(function () { invoked.push(2); }); + setTimeout(function () { + a.deep(invoked, [0, 1, 2], "Serial"); + d(); + }, 10); + }, 10); +}; diff --git a/node_modules/node-releases/LICENSE b/node_modules/node-releases/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ea39e4f9b798bd59194c506f5b711380affb3b29 --- /dev/null +++ b/node_modules/node-releases/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2017 Sergey Rubanov (https://github.com/chicoxyzzy) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/node-releases/README.md b/node_modules/node-releases/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d30d2003e4461f5bd3f920b86650bec997883f6b --- /dev/null +++ b/node_modules/node-releases/README.md @@ -0,0 +1,12 @@ +# Node.js releases data + +All data is located in `data` directory. + +`data/processed` contains `envs.json` with node.js releases data preprocessed to be used by [Browserslist](https://github.com/ai/browserslist) and other projects. Each version in this file contains only necessary info: version, release date, LTS flag/name, and security flag. + +`data/release-schedule` contains `release-schedule.json` with node.js releases date and end of life date. + +## Installation +```bash +npm install node-releases +``` diff --git a/node_modules/node-releases/data/processed/envs.json b/node_modules/node-releases/data/processed/envs.json new file mode 100644 index 0000000000000000000000000000000000000000..84ccb408184155b68e343b2040a037138056bedc --- /dev/null +++ b/node_modules/node-releases/data/processed/envs.json @@ -0,0 +1 @@ +[{"name":"nodejs","version":"0.2.0","date":"2011-08-26","lts":false,"security":false,"v8":"2.3.8.0"},{"name":"nodejs","version":"0.3.0","date":"2011-08-26","lts":false,"security":false,"v8":"2.5.1.0"},{"name":"nodejs","version":"0.4.0","date":"2011-08-26","lts":false,"security":false,"v8":"3.1.2.0"},{"name":"nodejs","version":"0.5.0","date":"2011-08-26","lts":false,"security":false,"v8":"3.1.8.25"},{"name":"nodejs","version":"0.6.0","date":"2011-11-04","lts":false,"security":false,"v8":"3.6.6.6"},{"name":"nodejs","version":"0.7.0","date":"2012-01-17","lts":false,"security":false,"v8":"3.8.6.0"},{"name":"nodejs","version":"0.8.0","date":"2012-06-22","lts":false,"security":false,"v8":"3.11.10.10"},{"name":"nodejs","version":"0.9.0","date":"2012-07-20","lts":false,"security":false,"v8":"3.11.10.15"},{"name":"nodejs","version":"0.10.0","date":"2013-03-11","lts":false,"security":false,"v8":"3.14.5.8"},{"name":"nodejs","version":"0.11.0","date":"2013-03-28","lts":false,"security":false,"v8":"3.17.13.0"},{"name":"nodejs","version":"0.12.0","date":"2015-02-06","lts":false,"security":false,"v8":"3.28.73.0"},{"name":"nodejs","version":"4.0.0","date":"2015-09-08","lts":false,"security":false,"v8":"4.5.103.30"},{"name":"nodejs","version":"4.1.0","date":"2015-09-17","lts":false,"security":false,"v8":"4.5.103.33"},{"name":"nodejs","version":"4.2.0","date":"2015-10-12","lts":"Argon","security":false,"v8":"4.5.103.35"},{"name":"nodejs","version":"4.3.0","date":"2016-02-09","lts":"Argon","security":false,"v8":"4.5.103.35"},{"name":"nodejs","version":"4.4.0","date":"2016-03-08","lts":"Argon","security":false,"v8":"4.5.103.35"},{"name":"nodejs","version":"4.5.0","date":"2016-08-16","lts":"Argon","security":false,"v8":"4.5.103.37"},{"name":"nodejs","version":"4.6.0","date":"2016-09-27","lts":"Argon","security":true,"v8":"4.5.103.37"},{"name":"nodejs","version":"4.7.0","date":"2016-12-06","lts":"Argon","security":false,"v8":"4.5.103.43"},{"name":"nodejs","version":"4.8.0","date":"2017-02-21","lts":"Argon","security":false,"v8":"4.5.103.45"},{"name":"nodejs","version":"4.9.0","date":"2018-03-28","lts":"Argon","security":true,"v8":"4.5.103.53"},{"name":"nodejs","version":"5.0.0","date":"2015-10-29","lts":false,"security":false,"v8":"4.6.85.28"},{"name":"nodejs","version":"5.1.0","date":"2015-11-17","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.2.0","date":"2015-12-09","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.3.0","date":"2015-12-15","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.4.0","date":"2016-01-06","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.5.0","date":"2016-01-21","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.6.0","date":"2016-02-09","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.7.0","date":"2016-02-23","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.8.0","date":"2016-03-09","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.9.0","date":"2016-03-16","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.10.0","date":"2016-04-01","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.11.0","date":"2016-04-21","lts":false,"security":false,"v8":"4.6.85.31"},{"name":"nodejs","version":"5.12.0","date":"2016-06-23","lts":false,"security":false,"v8":"4.6.85.32"},{"name":"nodejs","version":"6.0.0","date":"2016-04-26","lts":false,"security":false,"v8":"5.0.71.35"},{"name":"nodejs","version":"6.1.0","date":"2016-05-05","lts":false,"security":false,"v8":"5.0.71.35"},{"name":"nodejs","version":"6.2.0","date":"2016-05-17","lts":false,"security":false,"v8":"5.0.71.47"},{"name":"nodejs","version":"6.3.0","date":"2016-07-06","lts":false,"security":false,"v8":"5.0.71.52"},{"name":"nodejs","version":"6.4.0","date":"2016-08-12","lts":false,"security":false,"v8":"5.0.71.60"},{"name":"nodejs","version":"6.5.0","date":"2016-08-26","lts":false,"security":false,"v8":"5.1.281.81"},{"name":"nodejs","version":"6.6.0","date":"2016-09-14","lts":false,"security":false,"v8":"5.1.281.83"},{"name":"nodejs","version":"6.7.0","date":"2016-09-27","lts":false,"security":true,"v8":"5.1.281.83"},{"name":"nodejs","version":"6.8.0","date":"2016-10-12","lts":false,"security":false,"v8":"5.1.281.84"},{"name":"nodejs","version":"6.9.0","date":"2016-10-18","lts":"Boron","security":false,"v8":"5.1.281.84"},{"name":"nodejs","version":"6.10.0","date":"2017-02-21","lts":"Boron","security":false,"v8":"5.1.281.93"},{"name":"nodejs","version":"6.11.0","date":"2017-06-06","lts":"Boron","security":false,"v8":"5.1.281.102"},{"name":"nodejs","version":"6.12.0","date":"2017-11-06","lts":"Boron","security":false,"v8":"5.1.281.108"},{"name":"nodejs","version":"6.13.0","date":"2018-02-10","lts":"Boron","security":false,"v8":"5.1.281.111"},{"name":"nodejs","version":"6.14.0","date":"2018-03-28","lts":"Boron","security":true,"v8":"5.1.281.111"},{"name":"nodejs","version":"6.15.0","date":"2018-11-27","lts":"Boron","security":true,"v8":"5.1.281.111"},{"name":"nodejs","version":"6.16.0","date":"2018-12-26","lts":"Boron","security":false,"v8":"5.1.281.111"},{"name":"nodejs","version":"6.17.0","date":"2019-02-28","lts":"Boron","security":true,"v8":"5.1.281.111"},{"name":"nodejs","version":"7.0.0","date":"2016-10-25","lts":false,"security":false,"v8":"5.4.500.36"},{"name":"nodejs","version":"7.1.0","date":"2016-11-08","lts":false,"security":false,"v8":"5.4.500.36"},{"name":"nodejs","version":"7.2.0","date":"2016-11-22","lts":false,"security":false,"v8":"5.4.500.43"},{"name":"nodejs","version":"7.3.0","date":"2016-12-20","lts":false,"security":false,"v8":"5.4.500.45"},{"name":"nodejs","version":"7.4.0","date":"2017-01-04","lts":false,"security":false,"v8":"5.4.500.45"},{"name":"nodejs","version":"7.5.0","date":"2017-01-31","lts":false,"security":false,"v8":"5.4.500.48"},{"name":"nodejs","version":"7.6.0","date":"2017-02-21","lts":false,"security":false,"v8":"5.5.372.40"},{"name":"nodejs","version":"7.7.0","date":"2017-02-28","lts":false,"security":false,"v8":"5.5.372.41"},{"name":"nodejs","version":"7.8.0","date":"2017-03-29","lts":false,"security":false,"v8":"5.5.372.43"},{"name":"nodejs","version":"7.9.0","date":"2017-04-11","lts":false,"security":false,"v8":"5.5.372.43"},{"name":"nodejs","version":"7.10.0","date":"2017-05-02","lts":false,"security":false,"v8":"5.5.372.43"},{"name":"nodejs","version":"8.0.0","date":"2017-05-30","lts":false,"security":false,"v8":"5.8.283.41"},{"name":"nodejs","version":"8.1.0","date":"2017-06-08","lts":false,"security":false,"v8":"5.8.283.41"},{"name":"nodejs","version":"8.2.0","date":"2017-07-19","lts":false,"security":false,"v8":"5.8.283.41"},{"name":"nodejs","version":"8.3.0","date":"2017-08-08","lts":false,"security":false,"v8":"6.0.286.52"},{"name":"nodejs","version":"8.4.0","date":"2017-08-15","lts":false,"security":false,"v8":"6.0.286.52"},{"name":"nodejs","version":"8.5.0","date":"2017-09-12","lts":false,"security":false,"v8":"6.0.287.53"},{"name":"nodejs","version":"8.6.0","date":"2017-09-26","lts":false,"security":false,"v8":"6.0.287.53"},{"name":"nodejs","version":"8.7.0","date":"2017-10-11","lts":false,"security":false,"v8":"6.1.534.42"},{"name":"nodejs","version":"8.8.0","date":"2017-10-24","lts":false,"security":false,"v8":"6.1.534.42"},{"name":"nodejs","version":"8.9.0","date":"2017-10-31","lts":"Carbon","security":false,"v8":"6.1.534.46"},{"name":"nodejs","version":"8.10.0","date":"2018-03-06","lts":"Carbon","security":false,"v8":"6.2.414.50"},{"name":"nodejs","version":"8.11.0","date":"2018-03-28","lts":"Carbon","security":true,"v8":"6.2.414.50"},{"name":"nodejs","version":"8.12.0","date":"2018-09-10","lts":"Carbon","security":false,"v8":"6.2.414.66"},{"name":"nodejs","version":"8.13.0","date":"2018-11-20","lts":"Carbon","security":false,"v8":"6.2.414.72"},{"name":"nodejs","version":"8.14.0","date":"2018-11-27","lts":"Carbon","security":true,"v8":"6.2.414.72"},{"name":"nodejs","version":"8.15.0","date":"2018-12-26","lts":"Carbon","security":false,"v8":"6.2.414.75"},{"name":"nodejs","version":"8.16.0","date":"2019-04-16","lts":"Carbon","security":false,"v8":"6.2.414.77"},{"name":"nodejs","version":"8.17.0","date":"2019-12-17","lts":"Carbon","security":true,"v8":"6.2.414.78"},{"name":"nodejs","version":"9.0.0","date":"2017-10-31","lts":false,"security":false,"v8":"6.2.414.32"},{"name":"nodejs","version":"9.1.0","date":"2017-11-07","lts":false,"security":false,"v8":"6.2.414.32"},{"name":"nodejs","version":"9.2.0","date":"2017-11-14","lts":false,"security":false,"v8":"6.2.414.44"},{"name":"nodejs","version":"9.3.0","date":"2017-12-12","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.4.0","date":"2018-01-10","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.5.0","date":"2018-01-31","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.6.0","date":"2018-02-21","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.7.0","date":"2018-03-01","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.8.0","date":"2018-03-07","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.9.0","date":"2018-03-21","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.10.0","date":"2018-03-28","lts":false,"security":true,"v8":"6.2.414.46"},{"name":"nodejs","version":"9.11.0","date":"2018-04-04","lts":false,"security":false,"v8":"6.2.414.46"},{"name":"nodejs","version":"10.0.0","date":"2018-04-24","lts":false,"security":false,"v8":"6.6.346.24"},{"name":"nodejs","version":"10.1.0","date":"2018-05-08","lts":false,"security":false,"v8":"6.6.346.27"},{"name":"nodejs","version":"10.2.0","date":"2018-05-23","lts":false,"security":false,"v8":"6.6.346.32"},{"name":"nodejs","version":"10.3.0","date":"2018-05-29","lts":false,"security":false,"v8":"6.6.346.32"},{"name":"nodejs","version":"10.4.0","date":"2018-06-06","lts":false,"security":false,"v8":"6.7.288.43"},{"name":"nodejs","version":"10.5.0","date":"2018-06-20","lts":false,"security":false,"v8":"6.7.288.46"},{"name":"nodejs","version":"10.6.0","date":"2018-07-04","lts":false,"security":false,"v8":"6.7.288.46"},{"name":"nodejs","version":"10.7.0","date":"2018-07-18","lts":false,"security":false,"v8":"6.7.288.49"},{"name":"nodejs","version":"10.8.0","date":"2018-08-01","lts":false,"security":false,"v8":"6.7.288.49"},{"name":"nodejs","version":"10.9.0","date":"2018-08-15","lts":false,"security":false,"v8":"6.8.275.24"},{"name":"nodejs","version":"10.10.0","date":"2018-09-06","lts":false,"security":false,"v8":"6.8.275.30"},{"name":"nodejs","version":"10.11.0","date":"2018-09-19","lts":false,"security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.12.0","date":"2018-10-10","lts":false,"security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.13.0","date":"2018-10-30","lts":"Dubnium","security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.14.0","date":"2018-11-27","lts":"Dubnium","security":true,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.15.0","date":"2018-12-26","lts":"Dubnium","security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.16.0","date":"2019-05-28","lts":"Dubnium","security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.17.0","date":"2019-10-22","lts":"Dubnium","security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.18.0","date":"2019-12-17","lts":"Dubnium","security":true,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.19.0","date":"2020-02-05","lts":"Dubnium","security":true,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.20.0","date":"2020-03-26","lts":"Dubnium","security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.21.0","date":"2020-06-02","lts":"Dubnium","security":true,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.22.0","date":"2020-07-21","lts":"Dubnium","security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.23.0","date":"2020-10-27","lts":"Dubnium","security":false,"v8":"6.8.275.32"},{"name":"nodejs","version":"10.24.0","date":"2021-02-23","lts":"Dubnium","security":true,"v8":"6.8.275.32"},{"name":"nodejs","version":"11.0.0","date":"2018-10-23","lts":false,"security":false,"v8":"7.0.276.28"},{"name":"nodejs","version":"11.1.0","date":"2018-10-30","lts":false,"security":false,"v8":"7.0.276.32"},{"name":"nodejs","version":"11.2.0","date":"2018-11-15","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.3.0","date":"2018-11-27","lts":false,"security":true,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.4.0","date":"2018-12-07","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.5.0","date":"2018-12-18","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.6.0","date":"2018-12-26","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.7.0","date":"2019-01-17","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.8.0","date":"2019-01-24","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.9.0","date":"2019-01-30","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.10.0","date":"2019-02-14","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.11.0","date":"2019-03-05","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.12.0","date":"2019-03-14","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.13.0","date":"2019-03-28","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.14.0","date":"2019-04-10","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"11.15.0","date":"2019-04-30","lts":false,"security":false,"v8":"7.0.276.38"},{"name":"nodejs","version":"12.0.0","date":"2019-04-23","lts":false,"security":false,"v8":"7.4.288.21"},{"name":"nodejs","version":"12.1.0","date":"2019-04-29","lts":false,"security":false,"v8":"7.4.288.21"},{"name":"nodejs","version":"12.2.0","date":"2019-05-07","lts":false,"security":false,"v8":"7.4.288.21"},{"name":"nodejs","version":"12.3.0","date":"2019-05-21","lts":false,"security":false,"v8":"7.4.288.27"},{"name":"nodejs","version":"12.4.0","date":"2019-06-04","lts":false,"security":false,"v8":"7.4.288.27"},{"name":"nodejs","version":"12.5.0","date":"2019-06-26","lts":false,"security":false,"v8":"7.5.288.22"},{"name":"nodejs","version":"12.6.0","date":"2019-07-03","lts":false,"security":false,"v8":"7.5.288.22"},{"name":"nodejs","version":"12.7.0","date":"2019-07-23","lts":false,"security":false,"v8":"7.5.288.22"},{"name":"nodejs","version":"12.8.0","date":"2019-08-06","lts":false,"security":false,"v8":"7.5.288.22"},{"name":"nodejs","version":"12.9.0","date":"2019-08-20","lts":false,"security":false,"v8":"7.6.303.29"},{"name":"nodejs","version":"12.10.0","date":"2019-09-04","lts":false,"security":false,"v8":"7.6.303.29"},{"name":"nodejs","version":"12.11.0","date":"2019-09-25","lts":false,"security":false,"v8":"7.7.299.11"},{"name":"nodejs","version":"12.12.0","date":"2019-10-11","lts":false,"security":false,"v8":"7.7.299.13"},{"name":"nodejs","version":"12.13.0","date":"2019-10-21","lts":"Erbium","security":false,"v8":"7.7.299.13"},{"name":"nodejs","version":"12.14.0","date":"2019-12-17","lts":"Erbium","security":true,"v8":"7.7.299.13"},{"name":"nodejs","version":"12.15.0","date":"2020-02-05","lts":"Erbium","security":true,"v8":"7.7.299.13"},{"name":"nodejs","version":"12.16.0","date":"2020-02-11","lts":"Erbium","security":false,"v8":"7.8.279.23"},{"name":"nodejs","version":"12.17.0","date":"2020-05-26","lts":"Erbium","security":false,"v8":"7.8.279.23"},{"name":"nodejs","version":"12.18.0","date":"2020-06-02","lts":"Erbium","security":true,"v8":"7.8.279.23"},{"name":"nodejs","version":"12.19.0","date":"2020-10-06","lts":"Erbium","security":false,"v8":"7.8.279.23"},{"name":"nodejs","version":"12.20.0","date":"2020-11-24","lts":"Erbium","security":false,"v8":"7.8.279.23"},{"name":"nodejs","version":"12.21.0","date":"2021-02-23","lts":"Erbium","security":true,"v8":"7.8.279.23"},{"name":"nodejs","version":"12.22.0","date":"2021-03-30","lts":"Erbium","security":false,"v8":"7.8.279.23"},{"name":"nodejs","version":"13.0.0","date":"2019-10-22","lts":false,"security":false,"v8":"7.8.279.17"},{"name":"nodejs","version":"13.1.0","date":"2019-11-05","lts":false,"security":false,"v8":"7.8.279.17"},{"name":"nodejs","version":"13.2.0","date":"2019-11-21","lts":false,"security":false,"v8":"7.9.317.23"},{"name":"nodejs","version":"13.3.0","date":"2019-12-03","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.4.0","date":"2019-12-17","lts":false,"security":true,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.5.0","date":"2019-12-18","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.6.0","date":"2020-01-07","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.7.0","date":"2020-01-21","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.8.0","date":"2020-02-05","lts":false,"security":true,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.9.0","date":"2020-02-18","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.10.0","date":"2020-03-04","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.11.0","date":"2020-03-12","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.12.0","date":"2020-03-26","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.13.0","date":"2020-04-14","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"13.14.0","date":"2020-04-29","lts":false,"security":false,"v8":"7.9.317.25"},{"name":"nodejs","version":"14.0.0","date":"2020-04-21","lts":false,"security":false,"v8":"8.1.307.30"},{"name":"nodejs","version":"14.1.0","date":"2020-04-29","lts":false,"security":false,"v8":"8.1.307.31"},{"name":"nodejs","version":"14.2.0","date":"2020-05-05","lts":false,"security":false,"v8":"8.1.307.31"},{"name":"nodejs","version":"14.3.0","date":"2020-05-19","lts":false,"security":false,"v8":"8.1.307.31"},{"name":"nodejs","version":"14.4.0","date":"2020-06-02","lts":false,"security":true,"v8":"8.1.307.31"},{"name":"nodejs","version":"14.5.0","date":"2020-06-30","lts":false,"security":false,"v8":"8.3.110.9"},{"name":"nodejs","version":"14.6.0","date":"2020-07-20","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.7.0","date":"2020-07-29","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.8.0","date":"2020-08-11","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.9.0","date":"2020-08-27","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.10.0","date":"2020-09-08","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.11.0","date":"2020-09-15","lts":false,"security":true,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.12.0","date":"2020-09-22","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.13.0","date":"2020-09-29","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.14.0","date":"2020-10-15","lts":false,"security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.15.0","date":"2020-10-27","lts":"Fermium","security":false,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.16.0","date":"2021-02-23","lts":"Fermium","security":true,"v8":"8.4.371.19"},{"name":"nodejs","version":"14.17.0","date":"2021-05-11","lts":"Fermium","security":false,"v8":"8.4.371.23"},{"name":"nodejs","version":"14.18.0","date":"2021-09-28","lts":"Fermium","security":false,"v8":"8.4.371.23"},{"name":"nodejs","version":"14.19.0","date":"2022-02-01","lts":"Fermium","security":false,"v8":"8.4.371.23"},{"name":"nodejs","version":"14.20.0","date":"2022-07-07","lts":"Fermium","security":true,"v8":"8.4.371.23"},{"name":"nodejs","version":"14.21.0","date":"2022-11-01","lts":"Fermium","security":false,"v8":"8.4.371.23"},{"name":"nodejs","version":"15.0.0","date":"2020-10-20","lts":false,"security":false,"v8":"8.6.395.16"},{"name":"nodejs","version":"15.1.0","date":"2020-11-04","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.2.0","date":"2020-11-10","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.3.0","date":"2020-11-24","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.4.0","date":"2020-12-09","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.5.0","date":"2020-12-22","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.6.0","date":"2021-01-14","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.7.0","date":"2021-01-25","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.8.0","date":"2021-02-02","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.9.0","date":"2021-02-18","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.10.0","date":"2021-02-23","lts":false,"security":true,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.11.0","date":"2021-03-03","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.12.0","date":"2021-03-17","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.13.0","date":"2021-03-31","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"15.14.0","date":"2021-04-06","lts":false,"security":false,"v8":"8.6.395.17"},{"name":"nodejs","version":"16.0.0","date":"2021-04-20","lts":false,"security":false,"v8":"9.0.257.17"},{"name":"nodejs","version":"16.1.0","date":"2021-05-04","lts":false,"security":false,"v8":"9.0.257.24"},{"name":"nodejs","version":"16.2.0","date":"2021-05-19","lts":false,"security":false,"v8":"9.0.257.25"},{"name":"nodejs","version":"16.3.0","date":"2021-06-03","lts":false,"security":false,"v8":"9.0.257.25"},{"name":"nodejs","version":"16.4.0","date":"2021-06-23","lts":false,"security":false,"v8":"9.1.269.36"},{"name":"nodejs","version":"16.5.0","date":"2021-07-14","lts":false,"security":false,"v8":"9.1.269.38"},{"name":"nodejs","version":"16.6.0","date":"2021-07-29","lts":false,"security":true,"v8":"9.2.230.21"},{"name":"nodejs","version":"16.7.0","date":"2021-08-18","lts":false,"security":false,"v8":"9.2.230.21"},{"name":"nodejs","version":"16.8.0","date":"2021-08-25","lts":false,"security":false,"v8":"9.2.230.21"},{"name":"nodejs","version":"16.9.0","date":"2021-09-07","lts":false,"security":false,"v8":"9.3.345.16"},{"name":"nodejs","version":"16.10.0","date":"2021-09-22","lts":false,"security":false,"v8":"9.3.345.19"},{"name":"nodejs","version":"16.11.0","date":"2021-10-08","lts":false,"security":false,"v8":"9.4.146.19"},{"name":"nodejs","version":"16.12.0","date":"2021-10-20","lts":false,"security":false,"v8":"9.4.146.19"},{"name":"nodejs","version":"16.13.0","date":"2021-10-26","lts":"Gallium","security":false,"v8":"9.4.146.19"},{"name":"nodejs","version":"16.14.0","date":"2022-02-08","lts":"Gallium","security":false,"v8":"9.4.146.24"},{"name":"nodejs","version":"16.15.0","date":"2022-04-26","lts":"Gallium","security":false,"v8":"9.4.146.24"},{"name":"nodejs","version":"16.16.0","date":"2022-07-07","lts":"Gallium","security":true,"v8":"9.4.146.24"},{"name":"nodejs","version":"16.17.0","date":"2022-08-16","lts":"Gallium","security":false,"v8":"9.4.146.26"},{"name":"nodejs","version":"16.18.0","date":"2022-10-12","lts":"Gallium","security":false,"v8":"9.4.146.26"},{"name":"nodejs","version":"16.19.0","date":"2022-12-13","lts":"Gallium","security":false,"v8":"9.4.146.26"},{"name":"nodejs","version":"16.20.0","date":"2023-03-28","lts":"Gallium","security":false,"v8":"9.4.146.26"},{"name":"nodejs","version":"17.0.0","date":"2021-10-19","lts":false,"security":false,"v8":"9.5.172.21"},{"name":"nodejs","version":"17.1.0","date":"2021-11-09","lts":false,"security":false,"v8":"9.5.172.25"},{"name":"nodejs","version":"17.2.0","date":"2021-11-30","lts":false,"security":false,"v8":"9.6.180.14"},{"name":"nodejs","version":"17.3.0","date":"2021-12-17","lts":false,"security":false,"v8":"9.6.180.15"},{"name":"nodejs","version":"17.4.0","date":"2022-01-18","lts":false,"security":false,"v8":"9.6.180.15"},{"name":"nodejs","version":"17.5.0","date":"2022-02-10","lts":false,"security":false,"v8":"9.6.180.15"},{"name":"nodejs","version":"17.6.0","date":"2022-02-22","lts":false,"security":false,"v8":"9.6.180.15"},{"name":"nodejs","version":"17.7.0","date":"2022-03-09","lts":false,"security":false,"v8":"9.6.180.15"},{"name":"nodejs","version":"17.8.0","date":"2022-03-22","lts":false,"security":false,"v8":"9.6.180.15"},{"name":"nodejs","version":"17.9.0","date":"2022-04-07","lts":false,"security":false,"v8":"9.6.180.15"},{"name":"nodejs","version":"18.0.0","date":"2022-04-18","lts":false,"security":false,"v8":"10.1.124.8"},{"name":"nodejs","version":"18.1.0","date":"2022-05-03","lts":false,"security":false,"v8":"10.1.124.8"},{"name":"nodejs","version":"18.2.0","date":"2022-05-17","lts":false,"security":false,"v8":"10.1.124.8"},{"name":"nodejs","version":"18.3.0","date":"2022-06-02","lts":false,"security":false,"v8":"10.2.154.4"},{"name":"nodejs","version":"18.4.0","date":"2022-06-16","lts":false,"security":false,"v8":"10.2.154.4"},{"name":"nodejs","version":"18.5.0","date":"2022-07-06","lts":false,"security":true,"v8":"10.2.154.4"},{"name":"nodejs","version":"18.6.0","date":"2022-07-13","lts":false,"security":false,"v8":"10.2.154.13"},{"name":"nodejs","version":"18.7.0","date":"2022-07-26","lts":false,"security":false,"v8":"10.2.154.13"},{"name":"nodejs","version":"18.8.0","date":"2022-08-24","lts":false,"security":false,"v8":"10.2.154.13"},{"name":"nodejs","version":"18.9.0","date":"2022-09-07","lts":false,"security":false,"v8":"10.2.154.15"},{"name":"nodejs","version":"18.10.0","date":"2022-09-28","lts":false,"security":false,"v8":"10.2.154.15"},{"name":"nodejs","version":"18.11.0","date":"2022-10-13","lts":false,"security":false,"v8":"10.2.154.15"},{"name":"nodejs","version":"18.12.0","date":"2022-10-25","lts":"Hydrogen","security":false,"v8":"10.2.154.15"},{"name":"nodejs","version":"18.13.0","date":"2023-01-05","lts":"Hydrogen","security":false,"v8":"10.2.154.23"},{"name":"nodejs","version":"18.14.0","date":"2023-02-01","lts":"Hydrogen","security":false,"v8":"10.2.154.23"},{"name":"nodejs","version":"18.15.0","date":"2023-03-05","lts":"Hydrogen","security":false,"v8":"10.2.154.26"},{"name":"nodejs","version":"18.16.0","date":"2023-04-12","lts":"Hydrogen","security":false,"v8":"10.2.154.26"},{"name":"nodejs","version":"18.17.0","date":"2023-07-18","lts":"Hydrogen","security":false,"v8":"10.2.154.26"},{"name":"nodejs","version":"18.18.0","date":"2023-09-18","lts":"Hydrogen","security":false,"v8":"10.2.154.26"},{"name":"nodejs","version":"18.19.0","date":"2023-11-29","lts":"Hydrogen","security":false,"v8":"10.2.154.26"},{"name":"nodejs","version":"18.20.0","date":"2024-03-26","lts":"Hydrogen","security":false,"v8":"10.2.154.26"},{"name":"nodejs","version":"19.0.0","date":"2022-10-17","lts":false,"security":false,"v8":"10.7.193.13"},{"name":"nodejs","version":"19.1.0","date":"2022-11-14","lts":false,"security":false,"v8":"10.7.193.20"},{"name":"nodejs","version":"19.2.0","date":"2022-11-29","lts":false,"security":false,"v8":"10.8.168.20"},{"name":"nodejs","version":"19.3.0","date":"2022-12-14","lts":false,"security":false,"v8":"10.8.168.21"},{"name":"nodejs","version":"19.4.0","date":"2023-01-05","lts":false,"security":false,"v8":"10.8.168.25"},{"name":"nodejs","version":"19.5.0","date":"2023-01-24","lts":false,"security":false,"v8":"10.8.168.25"},{"name":"nodejs","version":"19.6.0","date":"2023-02-01","lts":false,"security":false,"v8":"10.8.168.25"},{"name":"nodejs","version":"19.7.0","date":"2023-02-21","lts":false,"security":false,"v8":"10.8.168.25"},{"name":"nodejs","version":"19.8.0","date":"2023-03-14","lts":false,"security":false,"v8":"10.8.168.25"},{"name":"nodejs","version":"19.9.0","date":"2023-04-10","lts":false,"security":false,"v8":"10.8.168.25"},{"name":"nodejs","version":"20.0.0","date":"2023-04-17","lts":false,"security":false,"v8":"11.3.244.4"},{"name":"nodejs","version":"20.1.0","date":"2023-05-03","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.2.0","date":"2023-05-16","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.3.0","date":"2023-06-08","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.4.0","date":"2023-07-04","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.5.0","date":"2023-07-19","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.6.0","date":"2023-08-23","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.7.0","date":"2023-09-18","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.8.0","date":"2023-09-28","lts":false,"security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.9.0","date":"2023-10-24","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.10.0","date":"2023-11-22","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.11.0","date":"2024-01-09","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.12.0","date":"2024-03-26","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.13.0","date":"2024-05-07","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.14.0","date":"2024-05-28","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.15.0","date":"2024-06-20","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.16.0","date":"2024-07-24","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.17.0","date":"2024-08-21","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.18.0","date":"2024-10-03","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"20.19.0","date":"2025-03-13","lts":"Iron","security":false,"v8":"11.3.244.8"},{"name":"nodejs","version":"21.0.0","date":"2023-10-17","lts":false,"security":false,"v8":"11.8.172.13"},{"name":"nodejs","version":"21.1.0","date":"2023-10-24","lts":false,"security":false,"v8":"11.8.172.15"},{"name":"nodejs","version":"21.2.0","date":"2023-11-14","lts":false,"security":false,"v8":"11.8.172.17"},{"name":"nodejs","version":"21.3.0","date":"2023-11-30","lts":false,"security":false,"v8":"11.8.172.17"},{"name":"nodejs","version":"21.4.0","date":"2023-12-05","lts":false,"security":false,"v8":"11.8.172.17"},{"name":"nodejs","version":"21.5.0","date":"2023-12-19","lts":false,"security":false,"v8":"11.8.172.17"},{"name":"nodejs","version":"21.6.0","date":"2024-01-14","lts":false,"security":false,"v8":"11.8.172.17"},{"name":"nodejs","version":"21.7.0","date":"2024-03-06","lts":false,"security":false,"v8":"11.8.172.17"},{"name":"nodejs","version":"22.0.0","date":"2024-04-24","lts":false,"security":false,"v8":"12.4.254.14"},{"name":"nodejs","version":"22.1.0","date":"2024-05-02","lts":false,"security":false,"v8":"12.4.254.14"},{"name":"nodejs","version":"22.2.0","date":"2024-05-15","lts":false,"security":false,"v8":"12.4.254.14"},{"name":"nodejs","version":"22.3.0","date":"2024-06-11","lts":false,"security":false,"v8":"12.4.254.20"},{"name":"nodejs","version":"22.4.0","date":"2024-07-02","lts":false,"security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.5.0","date":"2024-07-17","lts":false,"security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.6.0","date":"2024-08-06","lts":false,"security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.7.0","date":"2024-08-21","lts":false,"security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.8.0","date":"2024-09-03","lts":false,"security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.9.0","date":"2024-09-17","lts":false,"security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.10.0","date":"2024-10-16","lts":false,"security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.11.0","date":"2024-10-29","lts":"Jod","security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.12.0","date":"2024-12-02","lts":"Jod","security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.13.0","date":"2025-01-06","lts":"Jod","security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.14.0","date":"2025-02-11","lts":"Jod","security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.15.0","date":"2025-04-22","lts":"Jod","security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.16.0","date":"2025-05-20","lts":"Jod","security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.17.0","date":"2025-06-24","lts":"Jod","security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.18.0","date":"2025-07-31","lts":"Jod","security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.19.0","date":"2025-08-28","lts":"Jod","security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.20.0","date":"2025-09-24","lts":"Jod","security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"22.21.0","date":"2025-10-20","lts":"Jod","security":false,"v8":"12.4.254.21"},{"name":"nodejs","version":"23.0.0","date":"2024-10-16","lts":false,"security":false,"v8":"12.9.202.26"},{"name":"nodejs","version":"23.1.0","date":"2024-10-24","lts":false,"security":false,"v8":"12.9.202.28"},{"name":"nodejs","version":"23.2.0","date":"2024-11-11","lts":false,"security":false,"v8":"12.9.202.28"},{"name":"nodejs","version":"23.3.0","date":"2024-11-20","lts":false,"security":false,"v8":"12.9.202.28"},{"name":"nodejs","version":"23.4.0","date":"2024-12-10","lts":false,"security":false,"v8":"12.9.202.28"},{"name":"nodejs","version":"23.5.0","date":"2024-12-19","lts":false,"security":false,"v8":"12.9.202.28"},{"name":"nodejs","version":"23.6.0","date":"2025-01-07","lts":false,"security":false,"v8":"12.9.202.28"},{"name":"nodejs","version":"23.7.0","date":"2025-01-30","lts":false,"security":false,"v8":"12.9.202.28"},{"name":"nodejs","version":"23.8.0","date":"2025-02-13","lts":false,"security":false,"v8":"12.9.202.28"},{"name":"nodejs","version":"23.9.0","date":"2025-02-26","lts":false,"security":false,"v8":"12.9.202.28"},{"name":"nodejs","version":"23.10.0","date":"2025-03-13","lts":false,"security":false,"v8":"12.9.202.28"},{"name":"nodejs","version":"23.11.0","date":"2025-04-01","lts":false,"security":false,"v8":"12.9.202.28"},{"name":"nodejs","version":"24.0.0","date":"2025-05-06","lts":false,"security":false,"v8":"13.6.233.8"},{"name":"nodejs","version":"24.1.0","date":"2025-05-20","lts":false,"security":false,"v8":"13.6.233.10"},{"name":"nodejs","version":"24.2.0","date":"2025-06-09","lts":false,"security":false,"v8":"13.6.233.10"},{"name":"nodejs","version":"24.3.0","date":"2025-06-24","lts":false,"security":false,"v8":"13.6.233.10"},{"name":"nodejs","version":"24.4.0","date":"2025-07-09","lts":false,"security":false,"v8":"13.6.233.10"},{"name":"nodejs","version":"24.5.0","date":"2025-07-31","lts":false,"security":false,"v8":"13.6.233.10"},{"name":"nodejs","version":"24.6.0","date":"2025-08-14","lts":false,"security":false,"v8":"13.6.233.10"},{"name":"nodejs","version":"24.7.0","date":"2025-08-27","lts":false,"security":false,"v8":"13.6.233.10"},{"name":"nodejs","version":"24.8.0","date":"2025-09-10","lts":false,"security":false,"v8":"13.6.233.10"},{"name":"nodejs","version":"24.9.0","date":"2025-09-25","lts":false,"security":false,"v8":"13.6.233.10"},{"name":"nodejs","version":"24.10.0","date":"2025-10-08","lts":false,"security":false,"v8":"13.6.233.10"},{"name":"nodejs","version":"24.11.0","date":"2025-10-28","lts":"Krypton","security":false,"v8":"13.6.233.10"},{"name":"nodejs","version":"25.0.0","date":"2025-10-15","lts":false,"security":false,"v8":"14.1.146.11"},{"name":"nodejs","version":"25.1.0","date":"2025-10-28","lts":false,"security":false,"v8":"14.1.146.11"}] \ No newline at end of file diff --git a/node_modules/node-releases/data/release-schedule/release-schedule.json b/node_modules/node-releases/data/release-schedule/release-schedule.json new file mode 100644 index 0000000000000000000000000000000000000000..da063e4d91eda716963db683c827db96368894e4 --- /dev/null +++ b/node_modules/node-releases/data/release-schedule/release-schedule.json @@ -0,0 +1 @@ +{"v0.8":{"start":"2012-06-25","end":"2014-07-31"},"v0.10":{"start":"2013-03-11","end":"2016-10-31"},"v0.12":{"start":"2015-02-06","end":"2016-12-31"},"v4":{"start":"2015-09-08","lts":"2015-10-12","maintenance":"2017-04-01","end":"2018-04-30","codename":"Argon"},"v5":{"start":"2015-10-29","maintenance":"2016-04-30","end":"2016-06-30"},"v6":{"start":"2016-04-26","lts":"2016-10-18","maintenance":"2018-04-30","end":"2019-04-30","codename":"Boron"},"v7":{"start":"2016-10-25","maintenance":"2017-04-30","end":"2017-06-30"},"v8":{"start":"2017-05-30","lts":"2017-10-31","maintenance":"2019-01-01","end":"2019-12-31","codename":"Carbon"},"v9":{"start":"2017-10-01","maintenance":"2018-04-01","end":"2018-06-30"},"v10":{"start":"2018-04-24","lts":"2018-10-30","maintenance":"2020-05-19","end":"2021-04-30","codename":"Dubnium"},"v11":{"start":"2018-10-23","maintenance":"2019-04-22","end":"2019-06-01"},"v12":{"start":"2019-04-23","lts":"2019-10-21","maintenance":"2020-11-30","end":"2022-04-30","codename":"Erbium"},"v13":{"start":"2019-10-22","maintenance":"2020-04-01","end":"2020-06-01"},"v14":{"start":"2020-04-21","lts":"2020-10-27","maintenance":"2021-10-19","end":"2023-04-30","codename":"Fermium"},"v15":{"start":"2020-10-20","maintenance":"2021-04-01","end":"2021-06-01"},"v16":{"start":"2021-04-20","lts":"2021-10-26","maintenance":"2022-10-18","end":"2023-09-11","codename":"Gallium"},"v17":{"start":"2021-10-19","maintenance":"2022-04-01","end":"2022-06-01"},"v18":{"start":"2022-04-19","lts":"2022-10-25","maintenance":"2023-10-18","end":"2025-04-30","codename":"Hydrogen"},"v19":{"start":"2022-10-18","maintenance":"2023-04-01","end":"2023-06-01"},"v20":{"start":"2023-04-18","lts":"2023-10-24","maintenance":"2024-10-22","end":"2026-04-30","codename":"Iron"},"v21":{"start":"2023-10-17","maintenance":"2024-04-01","end":"2024-06-01"},"v22":{"start":"2024-04-24","lts":"2024-10-29","maintenance":"2025-10-21","end":"2027-04-30","codename":"Jod"},"v23":{"start":"2024-10-16","maintenance":"2025-04-01","end":"2025-06-01"},"v24":{"start":"2025-05-06","lts":"2025-10-28","maintenance":"2026-10-20","end":"2028-04-30","codename":"Krypton"},"v25":{"start":"2025-10-15","maintenance":"2026-04-01","end":"2026-06-01"},"v26":{"start":"2026-04-22","lts":"2026-10-28","maintenance":"2027-10-20","end":"2029-04-30","codename":""}} \ No newline at end of file diff --git a/node_modules/node-releases/package.json b/node_modules/node-releases/package.json new file mode 100644 index 0000000000000000000000000000000000000000..310a981fb4613c1408d0e41baf0104f72d4435f9 --- /dev/null +++ b/node_modules/node-releases/package.json @@ -0,0 +1,22 @@ +{ + "name": "node-releases", + "version": "2.0.27", + "description": "Node.js releases data", + "type": "module", + "scripts": { + "build": "node scripts/build.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/chicoxyzzy/node-releases.git" + }, + "keywords": [ + "nodejs", + "releases" + ], + "author": "Sergey Rubanov ", + "license": "MIT", + "devDependencies": { + "semver": "^7.3.5" + } +} diff --git a/node_modules/node-stdlib-browser/CHANGELOG.md b/node_modules/node-stdlib-browser/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..d89d60c56474483255d10301e3052d3b522913e6 --- /dev/null +++ b/node_modules/node-stdlib-browser/CHANGELOG.md @@ -0,0 +1,64 @@ +# Changelog + +## [Unreleased][] + +## [1.3.1][] - 2025-02-04 + +### Changed + +- Update `crypto-browserify` + ([#41](https://github.com/niksy/node-stdlib-browser/pull/41)) + +## [1.3.0][] - 2024-11-21 + +### Changed + +- Pin `domain-browser` to 4.22.0 +- Add `require` check for path resolver +- Proxy `process` with additional exports + ([#34](https://github.com/niksy/node-stdlib-browser/pull/34)) + +## [1.2.1][] - 2024-09-16 + +### Added + +- Support information and instructions for Vite +- Update dependencies + +## [1.2.0][] - 2021-12-08 + +### Added + +- Support for `node:` protocol in Webpack + ([#12](https://github.com/niksy/node-stdlib-browser/issues/12)) +- Rollup warning helper function + +## [1.1.0][] - 2021-11-16 + +### Added + +- Note regarding `URL` and `URLSearchParams` polyfilling +- Support for esbuild + +### Changed + +- Improve Rollup global variable injecting +- Use `path.resolve` for URL methods + +### Fixed + +- `url.format` to handle `URL` + +## [1.0.0][] - 2021-11-13 + +### Added + +- Initial implementation + +[1.0.0]: https://github.com/niksy/node-stdlib-browser/tree/v1.0.0 +[1.1.0]: https://github.com/niksy/node-stdlib-browser/tree/v1.1.0 +[1.2.0]: https://github.com/niksy/node-stdlib-browser/tree/v1.2.0 +[Unreleased]: https://github.com/niksy/node-stdlib-browser/compare/v1.3.1...HEAD +[1.3.1]: https://github.com/niksy/node-stdlib-browser/compare/v1.3.0...v1.3.1 +[1.3.0]: https://github.com/niksy/node-stdlib-browser/compare/v1.2.1...v1.3.0 +[1.2.1]: https://github.com/niksy/node-stdlib-browser/tree/v1.2.1 diff --git a/node_modules/node-stdlib-browser/LICENSE.md b/node_modules/node-stdlib-browser/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..146bc72c264e44858c80a0bae930717a92db95bc --- /dev/null +++ b/node_modules/node-stdlib-browser/LICENSE.md @@ -0,0 +1,18 @@ +Copyright (c) Ivan Nikolić Copyright (c) Tobias Koppers + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/node-stdlib-browser/README.md b/node_modules/node-stdlib-browser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6be0ccd6ce281101a6e29098c275bf6759766390 --- /dev/null +++ b/node_modules/node-stdlib-browser/README.md @@ -0,0 +1,352 @@ +# node-stdlib-browser + +[![Build Status][ci-img]][ci] + +[Node standard library](https://nodejs.org/docs/latest/api/) for browser. + +Features: + +- Based on [`node-libs-browser`](https://github.com/webpack/node-libs-browser) + for Webpack +- Maintained with newer versions and modern implementations +- Works with Webpack, Rollup, Vite, esbuild and Browserify, but should also + work with other bundlers +- Exports implementation with [`node:` protocol][node-protocol-imports] which + allows for builtin modules to be referenced by valid absolute URL strings + +Check [example](/example) to see how modules work in browser environment. + +## Install + +```sh +npm install node-stdlib-browser --save-dev +``` + +## Usage + +### Webpack + +
+ +Show me + +As of Webpack 5, aliases and globals provider need to be explicitly configured. +If you want to handle [`node:` protocol][node-protocol-imports] imports, you +need to provide helper plugin. + +```js +// webpack.config.js +const stdLibBrowser = require('node-stdlib-browser'); +const { + NodeProtocolUrlPlugin +} = require('node-stdlib-browser/helpers/webpack/plugin'); +const webpack = require('webpack'); + +module.exports = { + // ... + resolve: { + alias: stdLibBrowser + }, + plugins: [ + new NodeProtocolUrlPlugin(), + new webpack.ProvidePlugin({ + process: stdLibBrowser.process, + Buffer: [stdLibBrowser.buffer, 'Buffer'] + }) + ] +}; +``` + +If you’re using ESM config, additional configuration is needed to handle +unspecified extensions: + +```js +// webpack.config.js +module.exports = { + // ... + module: { + rules: [ + { + test: /\.m?js$/, + resolve: { + fullySpecified: false + } + } + ] + } +}; +``` + +
+ +### Rollup + +
+ +Show me + +Since many packages expose only CommonJS implementation, you need to apply +plugins to handle CommonJS exports. Those packages could have dependencies +installed with npm so they need to be properly resolved (taking into account +browser-specific implementations). + +Some dependencies can have circular dependencies and Rollup will warn you about +that. You can ignore these warnings with helper function +([reference](<(https://github.com/rollup/rollup/issues/1089#issuecomment-635564942)>)). + +```js +// rollup.config.js +const stdLibBrowser = require('node-stdlib-browser'); +const { + handleCircularDependancyWarning +} = require('node-stdlib-browser/helpers/rollup/plugin'); +const { default: resolve } = require('@rollup/plugin-node-resolve'); +const commonjs = require('@rollup/plugin-commonjs'); +const json = require('@rollup/plugin-json'); +const alias = require('@rollup/plugin-alias'); +const inject = require('@rollup/plugin-inject'); + +module.exports = { + // ... + plugins: [ + alias({ + entries: stdLibBrowser + }), + resolve({ + browser: true + }), + commonjs(), + json(), + inject({ + process: stdLibBrowser.process, + Buffer: [stdLibBrowser.buffer, 'Buffer'] + }) + ], + onwarn: (warning, rollupWarn) => { + handleCircularDependancyWarning(warning, rollupWarn); + } +}; +``` + +
+ +### Vite + +
+ +Show me + +Vite config uses combination of Rollup and esbuild plugins. It’s **important** +to use dynamic import when using CommonJS configuration so ESM version of +modules is picked up. This allows Vite bundling to use our mocking +implementation and implement heuristics such as proper tree-shaking and dead +code removal marking. + +```js +const inject = require('@rollup/plugin-inject'); + +const esbuildShim = require.resolve('node-stdlib-browser/helpers/esbuild/shim'); + +module.exports = async () => { + const { default: stdLibBrowser } = await import('node-stdlib-browser'); + return { + resolve: { + alias: stdLibBrowser + }, + optimizeDeps: { + include: ['buffer', 'process'] + }, + plugins: [ + { + ...inject({ + global: [esbuildShim, 'global'], + process: [esbuildShim, 'process'], + Buffer: [esbuildShim, 'Buffer'] + }), + enforce: 'post' + } + ] + }; +}; +``` + +#### Vite plugins + +If you wish to use simpler configuration, you can use one of the available Vite +plugins which use this package under the hood: + +- https://github.com/sodatea/vite-plugin-node-stdlib-browser +- https://github.com/davidmyersdev/vite-plugin-node-polyfills + +
+ +### esbuild + +
+ +Show me + +Using esbuild requires you to use helper utilities and plugins. + +```js +const path = require('path'); +const esbuild = require('esbuild'); +const plugin = require('node-stdlib-browser/helpers/esbuild/plugin'); +const stdLibBrowser = require('node-stdlib-browser'); + +(async () => { + await esbuild.build({ + // ... + inject: [require.resolve('node-stdlib-browser/helpers/esbuild/shim')], + define: { + global: 'global', + process: 'process', + Buffer: 'Buffer' + }, + plugins: [plugin(stdLibBrowser)] + }); +})(); +``` + +
+ +### Browserify + +
+ +Show me + +Bundling ES modules is currently not supported natively in Browserify, but you +can try using [esmify](https://github.com/mattdesl/esmify) or +[babelify](https://github.com/babel/babelify) for transforming to CommonJS +first. + +```js +const fs = require('fs'); +const path = require('path'); +const browserify = require('browserify'); +const aliasify = require('aliasify'); +const stdLibBrowser = require('node-stdlib-browser'); + +const b = browserify( + [ + /* ... */ + ], + { + // ... + transform: [[aliasify, { aliases: stdLibBrowser }]], + insertGlobalVars: { + process: () => { + return `require('${stdLibBrowser.process}')`; + }, + Buffer: () => { + return `require('${stdLibBrowser.buffer}').Buffer`; + } + } + } +); +``` + +
+ +## Package contents + +| Module | Browser implementation | Mock implementation | Notes | +| --------------------- | --------------------------------------------------------------------------------- | -------------------------- | ----------------------------------------------------------------------------------------------------- | +| `assert` | [assert](https://github.com/browserify/commonjs-assert) | | +| `buffer` | [buffer](https://github.com/feross/buffer) | [buffer](mock/buffer.js) | `buffer@5` for IE 11 support | +| `child_process` | | | +| `cluster` | | | +| `console` | [console-browserify](https://github.com/browserify/console-browserify) | [console](mock/console.js) | +| `constants` | [constants-browserify](https://github.com/juliangruber/constants-browserify) | | +| `crypto` | [crypto-browserify](https://github.com/crypto-browserify/crypto-browserify) | | +| `dgram` | | | +| `dns` | | [dns](mock/dns.js) | +| `domain` | [domain-browser](https://github.com/bevry/domain-browser) | | +| `events` | [events](https://github.com/browserify/events) | | +| `fs` | | | [Mocking `fs`](#mocking-fs) | +| `http` | [stream-http](https://github.com/jhiesey/stream-http) | | +| `https` | [https-browserify](https://github.com/substack/https-browserify) | | +| `module` | | | +| `net` | | [net](mock/net.js) | +| `os` | [os-browserify](https://github.com/CoderPuppy/os-browserify) | | +| `path` | [path-browserify](https://github.com/browserify/path-browserify) | | +| `process` | [process](https://github.com/defunctzombie/node-process) | [process](mock/process.js) | Contains additional exports from newer Node | +| `punycode` | [punycode](https://github.com/bestiejs/punycode.js) | | `punycode@1` for browser support | +| `querystring` | [querystring-es3](https://github.com/mike-spainhower/querystring) | | Contains additional exports from newer Node versions | +| `readline` | | | +| `repl` | | | +| `stream` | [stream-browserify](https://github.com/browserify/stream-browserify) | | +| `string_decoder` | [string_decoder](https://github.com/nodejs/string_decoder) | | +| `sys` | [util](https://github.com/browserify/node-util) | | +| `timers` | [timers-browserify](https://github.com/browserify/timers-browserify) | | +| `timers/promises` | [isomorphic-timers-promises](https://github.com/niksy/isomorphic-timers-promises) | | +| `tls` | | [tls](mock/tls.js) | +| `tty` | [tty-browserify](https://github.com/browserify/tty-browserify) | [tty](mock/tty.js) | +| `url` | [node-url](https://github.com/defunctzombie/node-url) | | Contains additional exports from newer Node versions (`URL` and `URLSearchParams` are not polyfilled) | +| `util` | [util](https://github.com/browserify/node-util) | | +| `vm` | [vm-browserify](https://github.com/browserify/vm-browserify) | | +| `zlib` | [browserify-zlib](https://github.com/browserify/browserify-zlib) | | +| `_stream_duplex` | [readable-stream](https://github.com/nodejs/readable-stream) | | +| `_stream_passthrough` | [readable-stream](https://github.com/nodejs/readable-stream) | | +| `_stream_readable` | [readable-stream](https://github.com/nodejs/readable-stream) | | +| `_stream_transform` | [readable-stream](https://github.com/nodejs/readable-stream) | | +| `_stream_writable` | [readable-stream](https://github.com/nodejs/readable-stream) | | + +## API + +### packages + +Returns: `object` + +Exports absolute paths to each module directory (where `package.json` is +located), keyed by module names. Modules without browser replacements return +module with default export `null`. + +Some modules have mocks in the mock directory. These are replacements with +minimal functionality. + +## Tips + +### Mocking `fs` + +`fs` package doesn’t return anything since there are many different ways you can +implement file system functionality in browser. + +Examples of implementations: + +- [`BrowserFS`](https://github.com/jvilk/BrowserFS) +- [`fs-web`](https://github.com/matthewp/fs) +- [`browserify-fs`](https://github.com/mafintosh/browserify-fs) +- [`mock-fs`](https://github.com/tschaub/mock-fs) +- [`memfs`](https://github.com/streamich/memfs) + +## Node support + +Minimum supported version should be Node 10. + +If you’re using ESM in Node < 12.20, note that +[subpath patterns](https://nodejs.org/api/packages.html#packages_subpath_patterns) +are not supported so mocks can’t be handled. In that case, it’s recommended to +use CommonJS implementation. + +## Browser support + +Minimum supported version should be Internet Explorer 11, but most modules +support even Internet Explorer 9. + +## Types + +You can use default `@types/node` types. + +## License + +MIT © [Ivan Nikolić](http://ivannikolic.com) + + + +[ci]: https://github.com/niksy/node-stdlib-browser/actions?query=workflow%3ACI +[ci-img]: https://github.com/niksy/node-stdlib-browser/workflows/CI/badge.svg?branch=master +[node-protocol-imports]: https://nodejs.org/api/esm.html#node-imports + + diff --git a/node_modules/node-stdlib-browser/cjs/index.d.ts b/node_modules/node-stdlib-browser/cjs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..608db0a6b8f4666be727e6e8b4edbe55f889a2ce --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/index.d.ts @@ -0,0 +1,170 @@ +declare const _default: { + "node:assert": string; + "node:buffer": string; + "node:child_process": string; + "node:cluster": string; + "node:console": string; + "node:constants": string; + "node:crypto": string; + "node:dgram": string; + "node:dns": string; + "node:domain": string; + "node:events": string; + "node:fs": string; + "node:http": string; + "node:https": string; + "node:http2": string; + "node:module": string; + "node:net": string; + "node:os": string; + "node:path": string; + "node:punycode": string; + "node:process": string; + "node:querystring": string; + "node:readline": string; + "node:repl": string; + "node:stream": string; + "node:_stream_duplex": string; + "node:_stream_passthrough": string; + "node:_stream_readable": string; + "node:_stream_transform": string; + "node:_stream_writable": string; + "node:string_decoder": string; + "node:sys": string; + "node:timers/promises": string; + "node:timers": string; + "node:tls": string; + "node:tty": string; + "node:url": string; + "node:util": string; + "node:vm": string; + "node:zlib": string; + assert: string; + buffer: string; + child_process: string; + cluster: string; + console: string; + constants: string; + crypto: string; + dgram: string; + dns: string; + domain: string; + events: string; + fs: string; + http: string; + https: string; + http2: string; + module: string; + net: string; + os: string; + path: string; + punycode: string; + process: string; + querystring: string; + readline: string; + repl: string; + stream: string; + _stream_duplex: string; + _stream_passthrough: string; + _stream_readable: string; + _stream_transform: string; + _stream_writable: string; + string_decoder: string; + sys: string; + 'timers/promises': string; + timers: string; + tls: string; + tty: string; + url: string; + util: string; + vm: string; + zlib: string; +}; +export default _default; +export type Packages = typeof packages; +export type PackageNames = keyof Packages; +export type NodeProtocolPackages = { + "node:assert": string; + "node:buffer": string; + "node:child_process": string; + "node:cluster": string; + "node:console": string; + "node:constants": string; + "node:crypto": string; + "node:dgram": string; + "node:dns": string; + "node:domain": string; + "node:events": string; + "node:fs": string; + "node:http": string; + "node:https": string; + "node:http2": string; + "node:module": string; + "node:net": string; + "node:os": string; + "node:path": string; + "node:punycode": string; + "node:process": string; + "node:querystring": string; + "node:readline": string; + "node:repl": string; + "node:stream": string; + "node:_stream_duplex": string; + "node:_stream_passthrough": string; + "node:_stream_readable": string; + "node:_stream_transform": string; + "node:_stream_writable": string; + "node:string_decoder": string; + "node:sys": string; + "node:timers/promises": string; + "node:timers": string; + "node:tls": string; + "node:tty": string; + "node:url": string; + "node:util": string; + "node:vm": string; + "node:zlib": string; +}; +declare const packages: { + assert: string; + buffer: string; + child_process: string; + cluster: string; + console: string; + constants: string; + crypto: string; + dgram: string; + dns: string; + domain: string; + events: string; + fs: string; + http: string; + https: string; + http2: string; + module: string; + net: string; + os: string; + path: string; + punycode: string; + process: string; + querystring: string; + readline: string; + repl: string; + stream: string; + _stream_duplex: string; + _stream_passthrough: string; + _stream_readable: string; + _stream_transform: string; + _stream_writable: string; + string_decoder: string; + sys: string; + 'timers/promises': string; + timers: string; + tls: string; + tty: string; + url: string; + util: string; + vm: string; + zlib: string; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/index.d.ts.map b/node_modules/node-stdlib-browser/cjs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..91c567327bd05477a50b162bb0e7c4f552739c82 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBA8Gc,eAAe;2BACf,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA5C5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyCE"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/index.js b/node_modules/node-stdlib-browser/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4f8c41040f5406f6204a8fc6fc6cbde5ab303038 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/index.js @@ -0,0 +1,147 @@ +'use strict'; + +var createRequire = require('create-require'); +var pkgDir = require('pkg-dir'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var createRequire__default = /*#__PURE__*/_interopDefaultLegacy(createRequire); +var pkgDir__default = /*#__PURE__*/_interopDefaultLegacy(pkgDir); + +var _globalThis = function (Object) { + function get() { + var _global = this || self; + delete Object.prototype.__magic__; + return _global; + } + if (typeof globalThis === "object") { + return globalThis; + } + if (this) { + return get(); + } else { + Object.defineProperty(Object.prototype, "__magic__", { + configurable: true, + get: get + }); + var _global = __magic__; + return _global; + } +}(Object); + +/** + * @param {string} path + */ +const resolvePath = path => { + let resolvedPath; + try { + resolvedPath = require.resolve(path); + } catch { + var _globalThis$require; + resolvedPath = ((_globalThis$require = _globalThis.require) != null ? _globalThis$require : createRequire__default["default"]((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || new URL('index.js', document.baseURI).href)))).resolve(path); + } + if (!path.includes('./')) { + var _pkgDir$sync; + const directory = (_pkgDir$sync = pkgDir__default["default"].sync(resolvedPath)) != null ? _pkgDir$sync : ''; + return directory; + } + return resolvedPath; +}; +const assert = resolvePath('assert/'); +const buffer = resolvePath('buffer/'); +const child_process = resolvePath('./mock/empty.js'); +const cluster = resolvePath('./mock/empty.js'); +const _console = resolvePath('console-browserify'); +const constants = resolvePath('constants-browserify'); +const crypto = resolvePath('crypto-browserify'); +const dgram = resolvePath('./mock/empty.js'); +const dns = resolvePath('./mock/empty.js'); +const domain = resolvePath('domain-browser'); +const events = resolvePath('events/'); +const fs = resolvePath('./mock/empty.js'); +const http = resolvePath('stream-http'); +const https = resolvePath('https-browserify'); +const http2 = resolvePath('./mock/empty.js'); +const _module = resolvePath('./mock/empty.js'); +const net = resolvePath('./mock/empty.js'); +const os = resolvePath('os-browserify/browser.js'); +const path = resolvePath('path-browserify'); +const punycode = resolvePath('punycode/'); +const _process = resolvePath('./proxy/process').replace('.js', ''); +const querystring = resolvePath('./proxy/querystring.js'); +const readline = resolvePath('./mock/empty.js'); +const repl = resolvePath('./mock/empty.js'); +const stream = resolvePath('stream-browserify'); +const _stream_duplex = resolvePath('readable-stream/lib/_stream_duplex.js'); +const _stream_passthrough = resolvePath('readable-stream/lib/_stream_passthrough.js'); +const _stream_readable = resolvePath('readable-stream/lib/_stream_readable.js'); +const _stream_transform = resolvePath('readable-stream/lib/_stream_transform.js'); +const _stream_writable = resolvePath('readable-stream/lib/_stream_writable.js'); +const string_decoder = resolvePath('string_decoder/'); +const sys = resolvePath('util/util.js'); +const timers = resolvePath('timers-browserify'); +const timersPromises = resolvePath('isomorphic-timers-promises'); +const tls = resolvePath('./mock/empty.js'); +const tty = resolvePath('tty-browserify'); +const url = resolvePath('./proxy/url.js'); +const util = resolvePath('util/util.js'); +const vm = resolvePath('vm-browserify'); +const zlib = resolvePath('browserify-zlib'); +const packages = { + assert, + buffer, + child_process, + cluster, + console: _console, + constants, + crypto, + dgram, + dns, + domain, + events, + fs, + http, + https, + http2, + module: _module, + net, + os, + path, + punycode, + process: _process, + querystring, + readline, + repl, + stream, + _stream_duplex, + _stream_passthrough, + _stream_readable, + _stream_transform, + _stream_writable, + string_decoder, + sys, + 'timers/promises': timersPromises, + timers, + tls, + tty, + url, + util, + vm, + zlib +}; + +/** @typedef {typeof packages} Packages */ +/** @typedef {keyof Packages} PackageNames */ +/** @typedef {{ [Property in PackageNames as `node:${Property}`]: Packages[Property] }} NodeProtocolPackages */ + +const packagesWithNodeProtocol = /** @type NodeProtocolPackages */{}; +for (const [packageName, packagePath] of Object.entries(packages)) { + packagesWithNodeProtocol[`node:${(/** @type PackageNames */packageName)}`] = /** @type PackageNames */packagePath; +} +var index = { + ...packages, + ...packagesWithNodeProtocol +}; + +module.exports = index; +//# sourceMappingURL=index.js.map diff --git a/node_modules/node-stdlib-browser/cjs/index.js.map b/node_modules/node-stdlib-browser/cjs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..152b3589f1a91540c9afec2536fc63c796097638 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../index.js"],"sourcesContent":["import createRequire from 'create-require';\nimport pkgDir from 'pkg-dir';\n\n/**\n * @param {string} path\n */\nconst resolvePath = (path) => {\n\tlet resolvedPath;\n\ttry {\n\t\tresolvedPath = require.resolve(path);\n\t} catch {\n\t\tresolvedPath = (\n\t\t\tglobalThis.require ?? createRequire(import.meta.url)\n\t\t).resolve(path);\n\t}\n\tif (!path.includes('./')) {\n\t\tconst directory = pkgDir.sync(resolvedPath) ?? '';\n\t\treturn directory;\n\t}\n\treturn resolvedPath;\n};\n\nconst assert = resolvePath('assert/');\nconst buffer = resolvePath('buffer/');\nconst child_process = resolvePath('./mock/empty.js');\nconst cluster = resolvePath('./mock/empty.js');\nconst _console = resolvePath('console-browserify');\nconst constants = resolvePath('constants-browserify');\nconst crypto = resolvePath('crypto-browserify');\nconst dgram = resolvePath('./mock/empty.js');\nconst dns = resolvePath('./mock/empty.js');\nconst domain = resolvePath('domain-browser');\nconst events = resolvePath('events/');\nconst fs = resolvePath('./mock/empty.js');\nconst http = resolvePath('stream-http');\nconst https = resolvePath('https-browserify');\nconst http2 = resolvePath('./mock/empty.js');\nconst _module = resolvePath('./mock/empty.js');\nconst net = resolvePath('./mock/empty.js');\nconst os = resolvePath('os-browserify/browser.js');\nconst path = resolvePath('path-browserify');\nconst punycode = resolvePath('punycode/');\nconst _process = resolvePath('./proxy/process').replace('.js', '');\nconst querystring = resolvePath('./proxy/querystring.js');\nconst readline = resolvePath('./mock/empty.js');\nconst repl = resolvePath('./mock/empty.js');\nconst stream = resolvePath('stream-browserify');\nconst _stream_duplex = resolvePath('readable-stream/lib/_stream_duplex.js');\nconst _stream_passthrough = resolvePath(\n\t'readable-stream/lib/_stream_passthrough.js'\n);\nconst _stream_readable = resolvePath('readable-stream/lib/_stream_readable.js');\nconst _stream_transform = resolvePath(\n\t'readable-stream/lib/_stream_transform.js'\n);\nconst _stream_writable = resolvePath('readable-stream/lib/_stream_writable.js');\nconst string_decoder = resolvePath('string_decoder/');\nconst sys = resolvePath('util/util.js');\nconst timers = resolvePath('timers-browserify');\nconst timersPromises = resolvePath('isomorphic-timers-promises');\nconst tls = resolvePath('./mock/empty.js');\nconst tty = resolvePath('tty-browserify');\nconst url = resolvePath('./proxy/url.js');\nconst util = resolvePath('util/util.js');\nconst vm = resolvePath('vm-browserify');\nconst zlib = resolvePath('browserify-zlib');\n\nconst packages = {\n\tassert,\n\tbuffer,\n\tchild_process,\n\tcluster,\n\tconsole: _console,\n\tconstants,\n\tcrypto,\n\tdgram,\n\tdns,\n\tdomain,\n\tevents,\n\tfs,\n\thttp,\n\thttps,\n\thttp2,\n\tmodule: _module,\n\tnet,\n\tos,\n\tpath,\n\tpunycode,\n\tprocess: _process,\n\tquerystring,\n\treadline,\n\trepl,\n\tstream,\n\t_stream_duplex,\n\t_stream_passthrough,\n\t_stream_readable,\n\t_stream_transform,\n\t_stream_writable,\n\tstring_decoder,\n\tsys,\n\t'timers/promises': timersPromises,\n\ttimers,\n\ttls,\n\ttty,\n\turl,\n\tutil,\n\tvm,\n\tzlib\n};\n\n/** @typedef {typeof packages} Packages */\n/** @typedef {keyof Packages} PackageNames */\n/** @typedef {{ [Property in PackageNames as `node:${Property}`]: Packages[Property] }} NodeProtocolPackages */\n\nconst packagesWithNodeProtocol = /** @type NodeProtocolPackages */ ({});\nfor (const [packageName, packagePath] of Object.entries(packages)) {\n\tpackagesWithNodeProtocol[\n\t\t`node:${/** @type PackageNames */ (packageName)}`\n\t] = /** @type PackageNames */ packagePath;\n}\n\nexport default {\n\t...packages,\n\t...packagesWithNodeProtocol\n};\n"],"names":["resolvePath","path","resolvedPath","require","resolve","_globalThis$require","_globalThis","createRequire","import","includes","_pkgDir$sync","directory","pkgDir","sync","assert","buffer","child_process","cluster","_console","constants","crypto","dgram","dns","domain","events","fs","http","https","http2","_module","net","os","punycode","_process","replace","querystring","readline","repl","stream","_stream_duplex","_stream_passthrough","_stream_readable","_stream_transform","_stream_writable","string_decoder","sys","timers","timersPromises","tls","tty","url","util","vm","zlib","packages","console","module","process","packagesWithNodeProtocol","packageName","packagePath","Object","entries"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA;AACA;AACA;AACA,MAAMA,WAAW,GAAIC,IAAI,IAAK;AAC7B,EAAA,IAAIC,YAAY,CAAA;EAChB,IAAI;AACHA,IAAAA,YAAY,GAAGC,OAAO,CAACC,OAAO,CAACH,IAAI,CAAC,CAAA;AACrC,GAAC,CAAC,MAAM;AAAA,IAAA,IAAAI,mBAAA,CAAA;IACPH,YAAY,GAAG,EAAAG,mBAAA,GACdC,WAAA,CAAWH,OAAO,KAAAE,IAAAA,GAAAA,mBAAA,GAAIE,iCAAa,CAACC,gQAAe,CAAC,EACnDJ,OAAO,CAACH,IAAI,CAAC,CAAA;AAChB,GAAA;AACA,EAAA,IAAI,CAACA,IAAI,CAACQ,QAAQ,CAAC,IAAI,CAAC,EAAE;AAAA,IAAA,IAAAC,YAAA,CAAA;AACzB,IAAA,MAAMC,SAAS,GAAA,CAAAD,YAAA,GAAGE,0BAAM,CAACC,IAAI,CAACX,YAAY,CAAC,KAAAQ,IAAAA,GAAAA,YAAA,GAAI,EAAE,CAAA;AACjD,IAAA,OAAOC,SAAS,CAAA;AACjB,GAAA;AACA,EAAA,OAAOT,YAAY,CAA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AAMqD,IAAI,GAAGrD,WAAW,CAAC,iBAAiB,CAAC,CAAA;AAE3C,MAAMsD,QAAQ,GAAG;EAChBxC,MAAM;EACNC,MAAM;EACNC,aAAa;EACbC,OAAO;AACPsC,EAAAA,OAAO,EAAErC,QAAQ;EACjBC,SAAS;EACTC,MAAM;EACNC,KAAK;EACLC,GAAG;EACHC,MAAM;EACNC,MAAM;EACNC,EAAE;EACFC,IAAI;EACJC,KAAK;EACLC,KAAK;AACL4B,EAAAA,MAAM,EAAE3B,OAAO;EACfC,GAAG;EACHC,EAAE;EACF9B,IAAI;EACJ+B,QAAQ;AACRyB,EAAAA,OAAO,EAAExB,QAAQ;EACjBE,WAAW;EACXC,QAAQ;EACRC,IAAI;EACJC,MAAM;EACNC,cAAc;EACdC,mBAAmB;EACnBC,gBAAgB;EAChBC,iBAAiB;EACjBC,gBAAgB;EAChBC,cAAc;EACdC,GAAG;AACH,EAAA,iBAAiB,EAAEE,cAAc;EACjCD,MAAM;EACNE,GAAG;EACHC,GAAG;EACHC,GAAG;EACHC,IAAI;EACJC,EAAE;AACFC,EAAAA,IAAAA;AACD,CAAC,CAAA;;AAED;AACA;AACA;;AAEA,MAAMK,wBAAwB,oCAAsC,EAAG,CAAA;AACvE,KAAK,MAAM,CAACC,WAAW,EAAEC,WAAW,CAAC,IAAIC,MAAM,CAACC,OAAO,CAACR,QAAQ,CAAC,EAAE;EAClEI,wBAAwB,CACvB,kCAAmCC,WAAW,GAAG,CACjD,4BAA6BC,WAAW,CAAA;AAC1C,CAAA;AAEA,YAAe;AACd,EAAA,GAAGN,QAAQ;EACX,GAAGI,wBAAAA;AACJ,CAAC;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/buffer.d.ts b/node_modules/node-stdlib-browser/cjs/mock/buffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..35342fc09b28dc7f6a24f64a89714b5be06c4114 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/buffer.d.ts @@ -0,0 +1,7 @@ +export const INSPECT_MAX_BYTES: 50; +export function Buffer(): void; +export namespace Buffer { + function isBuffer(): boolean; +} +export { Buffer as SlowBuffer }; +//# sourceMappingURL=buffer.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/buffer.d.ts.map b/node_modules/node-stdlib-browser/cjs/mock/buffer.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..67d3a4b2a51fca145339bed8eda4945944d0afed --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/buffer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer.d.ts","sourceRoot":"","sources":["../../mock/buffer.js"],"names":[],"mappings":"AAOA,mCAA6B;AAP7B,+BAEC;;IACD,6BAEC"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/buffer.js b/node_modules/node-stdlib-browser/cjs/mock/buffer.js new file mode 100644 index 0000000000000000000000000000000000000000..89b725cd7a99fdd054c5f5a3a748a0e7c4cbafaf --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/buffer.js @@ -0,0 +1,16 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function Buffer() { + throw new Error('Buffer is not included.'); +} +Buffer.isBuffer = function () { + return false; +}; +var INSPECT_MAX_BYTES = 50; + +exports.Buffer = Buffer; +exports.INSPECT_MAX_BYTES = INSPECT_MAX_BYTES; +exports.SlowBuffer = Buffer; +//# sourceMappingURL=buffer.js.map diff --git a/node_modules/node-stdlib-browser/cjs/mock/buffer.js.map b/node_modules/node-stdlib-browser/cjs/mock/buffer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..070bddbb4e333fc5cfd06c1acf11ca292aa195fd --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/buffer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer.js","sources":["../../mock/buffer.js"],"sourcesContent":["function Buffer() {\n\tthrow new Error('Buffer is not included.');\n}\nBuffer.isBuffer = function () {\n\treturn false;\n};\n\nconst INSPECT_MAX_BYTES = 50;\n\nexport { INSPECT_MAX_BYTES, Buffer as SlowBuffer, Buffer };\n"],"names":["Buffer","Error","isBuffer","INSPECT_MAX_BYTES"],"mappings":";;;;AAAA,SAASA,MAAMA,GAAG;AACjB,EAAA,MAAM,IAAIC,KAAK,CAAC,yBAAyB,CAAC,CAAA;AAC3C,CAAA;AACAD,MAAM,CAACE,QAAQ,GAAG,YAAY;AAC7B,EAAA,OAAO,KAAK,CAAA;AACb,CAAC,CAAA;AAEKC,IAAAA,iBAAiB,GAAG;;;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/console.d.ts b/node_modules/node-stdlib-browser/cjs/mock/console.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..94757578e36b7845e721f3b0d1a689568289540b --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/console.d.ts @@ -0,0 +1,14 @@ +export default _console; +export type ConsoleApi = keyof { + log: number; + info: number; + error: number; + warn: number; + dir: number; + trace: number; + assert: number; + time: number; + timeEnd: number; +}; +declare const _console: Console; +//# sourceMappingURL=console.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/console.d.ts.map b/node_modules/node-stdlib-browser/cjs/mock/console.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..da89c58ba05bb1f9f31ecef5d2fdbdde3ff9af1e --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/console.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"console.d.ts","sourceRoot":"","sources":["../../mock/console.js"],"names":[],"mappings":";yBAcc;;;;;;;;;;CAAgB;AAd9B,gCAA0C"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/console.js b/node_modules/node-stdlib-browser/cjs/mock/console.js new file mode 100644 index 0000000000000000000000000000000000000000..3156ace2bee064768f29597c58a3de81b0ed4a49 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/console.js @@ -0,0 +1,46 @@ +'use strict'; + +var _globalThis$console; +var _globalThis = function (Object) { + function get() { + var _global = this || self; + delete Object.prototype.__magic__; + return _global; + } + if (typeof globalThis === "object") { + return globalThis; + } + if (this) { + return get(); + } else { + Object.defineProperty(Object.prototype, "__magic__", { + configurable: true, + get: get + }); + var _global = __magic__; + return _global; + } +}(Object); +var _console = (_globalThis$console = _globalThis.console) != null ? _globalThis$console : {}; +var consoleApi = { + log: 1, + info: 1, + error: 1, + warn: 1, + dir: 1, + trace: 1, + assert: 1, + time: 1, + timeEnd: 1 +}; + +/** @typedef {keyof consoleApi} ConsoleApi */ + +for (var property in consoleApi) { + if (!_console[(/** @type {ConsoleApi} */property)]) { + _console[(/** @type {ConsoleApi} */property)] = function () {}; + } +} + +module.exports = _console; +//# sourceMappingURL=console.js.map diff --git a/node_modules/node-stdlib-browser/cjs/mock/console.js.map b/node_modules/node-stdlib-browser/cjs/mock/console.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b3b980edf2e23644e41b97293836b8195285db4f --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/console.js.map @@ -0,0 +1 @@ +{"version":3,"file":"console.js","sources":["../../mock/console.js"],"sourcesContent":["const _console = globalThis.console ?? {};\n\nconst consoleApi = {\n\tlog: 1,\n\tinfo: 1,\n\terror: 1,\n\twarn: 1,\n\tdir: 1,\n\ttrace: 1,\n\tassert: 1,\n\ttime: 1,\n\ttimeEnd: 1\n};\n\n/** @typedef {keyof consoleApi} ConsoleApi */\n\nfor (const property in consoleApi) {\n\tif (!_console[/** @type {ConsoleApi} */ (property)]) {\n\t\t_console[/** @type {ConsoleApi} */ (property)] = function () {};\n\t}\n}\n\nexport default _console;\n"],"names":["_console","_globalThis$console","_globalThis","console","consoleApi","log","info","error","warn","dir","trace","assert","time","timeEnd","property"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAMA,IAAAA,QAAQ,GAAAC,CAAAA,mBAAA,GAAGC,WAAA,CAAWC,OAAO,KAAAF,IAAAA,GAAAA,mBAAA,GAAI,GAAE;AAEzC,IAAMG,UAAU,GAAG;AAClBC,EAAAA,GAAG,EAAE,CAAC;AACNC,EAAAA,IAAI,EAAE,CAAC;AACPC,EAAAA,KAAK,EAAE,CAAC;AACRC,EAAAA,IAAI,EAAE,CAAC;AACPC,EAAAA,GAAG,EAAE,CAAC;AACNC,EAAAA,KAAK,EAAE,CAAC;AACRC,EAAAA,MAAM,EAAE,CAAC;AACTC,EAAAA,IAAI,EAAE,CAAC;AACPC,EAAAA,OAAO,EAAE,CAAA;AACV,CAAC,CAAA;;AAED;;AAEA,KAAK,IAAMC,QAAQ,IAAIV,UAAU,EAAE;AAClC,EAAA,IAAI,CAACJ,QAAQ,2BAA4Bc,QAAQ,EAAE,EAAE;AACpDd,IAAAA,QAAQ,2BAA4Bc,QAAQ,EAAE,GAAG,YAAY,EAAE,CAAA;AAChE,GAAA;AACD;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/dns.d.ts b/node_modules/node-stdlib-browser/cjs/mock/dns.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ace59d7ae728339233c1a9fca7a89b90bfbbb97 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/dns.d.ts @@ -0,0 +1,6 @@ +/** + * @param {unknown[]} arguments_ + */ +declare function api(...arguments_: unknown[]): void; +export { api as lookup, api as resolve4, api as resolve6, api as resolveCname, api as resolveMx, api as resolveNs, api as resolveTxt, api as resolveSrv, api as resolveNaptr, api as reverse, api as resolve }; +//# sourceMappingURL=dns.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/dns.d.ts.map b/node_modules/node-stdlib-browser/cjs/mock/dns.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..a51b76c719f05114729ba7c027d2d2912583eba1 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/dns.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dns.d.ts","sourceRoot":"","sources":["../../mock/dns.js"],"names":[],"mappings":"AAEA;;GAEG;AACH,oCAFW,OAAO,EAAE,QAUnB"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/dns.js b/node_modules/node-stdlib-browser/cjs/mock/dns.js new file mode 100644 index 0000000000000000000000000000000000000000..ee9bfa0b2ee02500a7d2625ccd996173d0afff08 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/dns.js @@ -0,0 +1,32 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +/* globals unknown */ + +/** + * @param {unknown[]} arguments_ + */ +var api = function api() { + var _ref; + if (arguments.length === 0) { + return; + } + var callback = (_ref = arguments.length - 1, _ref < 0 || arguments.length <= _ref ? undefined : arguments[_ref]); + if (typeof callback === 'function') { + callback(null, '0.0.0.0'); + } +}; + +exports.lookup = api; +exports.resolve = api; +exports.resolve4 = api; +exports.resolve6 = api; +exports.resolveCname = api; +exports.resolveMx = api; +exports.resolveNaptr = api; +exports.resolveNs = api; +exports.resolveSrv = api; +exports.resolveTxt = api; +exports.reverse = api; +//# sourceMappingURL=dns.js.map diff --git a/node_modules/node-stdlib-browser/cjs/mock/dns.js.map b/node_modules/node-stdlib-browser/cjs/mock/dns.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a46baae4cd76d39c2746d5d798cf0e5e0514a162 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/dns.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dns.js","sources":["../../mock/dns.js"],"sourcesContent":["/* globals unknown */\n\n/**\n * @param {unknown[]} arguments_\n */\nconst api = function (...arguments_) {\n\tif (arguments_.length === 0) {\n\t\treturn;\n\t}\n\tconst callback = arguments_[arguments_.length - 1];\n\tif (typeof callback === 'function') {\n\t\tcallback(null, '0.0.0.0');\n\t}\n};\n\nexport {\n\tapi as lookup,\n\tapi as resolve4,\n\tapi as resolve6,\n\tapi as resolveCname,\n\tapi as resolveMx,\n\tapi as resolveNs,\n\tapi as resolveTxt,\n\tapi as resolveSrv,\n\tapi as resolveNaptr,\n\tapi as reverse,\n\tapi as resolve\n};\n"],"names":["api","_ref","arguments","length","callback","undefined"],"mappings":";;;;AAAA;;AAEA;AACA;AACA;AACA,IAAMA,GAAG,GAAG,SAANA,GAAGA,GAA4B;AAAA,EAAA,IAAAC,IAAA,CAAA;AACpC,EAAA,IAAIC,SAAA,CAAWC,MAAM,KAAK,CAAC,EAAE;AAC5B,IAAA,OAAA;AACD,GAAA;EACA,IAAMC,QAAQ,IAAAH,IAAA,GAAcC,SAAA,CAAWC,MAAM,GAAG,CAAC,EAAAF,IAAA,QAAAC,SAAA,CAAAC,MAAA,IAAAF,IAAA,GAAAI,SAAA,GAAAH,SAAA,CAAAD,IAAA,CAAC,CAAA,CAAA;AAClD,EAAA,IAAI,OAAOG,QAAQ,KAAK,UAAU,EAAE;AACnCA,IAAAA,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;AAC1B,GAAA;AACD;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/empty.d.ts b/node_modules/node-stdlib-browser/cjs/mock/empty.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..67b676d9ef871765c3878764215c9274d78a1e69 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/empty.d.ts @@ -0,0 +1,3 @@ +declare const _default: null; +export default _default; +//# sourceMappingURL=empty.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/empty.d.ts.map b/node_modules/node-stdlib-browser/cjs/mock/empty.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e355de3984d5f6872f525cedef7163049da14475 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/empty.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"empty.d.ts","sourceRoot":"","sources":["../../mock/empty.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/empty.js b/node_modules/node-stdlib-browser/cjs/mock/empty.js new file mode 100644 index 0000000000000000000000000000000000000000..87e67f61d1d3b57bef7ba8ac328776cde08c9868 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/empty.js @@ -0,0 +1,6 @@ +'use strict'; + +var empty = null; + +module.exports = empty; +//# sourceMappingURL=empty.js.map diff --git a/node_modules/node-stdlib-browser/cjs/mock/empty.js.map b/node_modules/node-stdlib-browser/cjs/mock/empty.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a5546df3e069c2a69fcb901a645d82a57543378b --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/empty.js.map @@ -0,0 +1 @@ +{"version":3,"file":"empty.js","sources":["../../mock/empty.js"],"sourcesContent":["export default null;\n"],"names":[],"mappings":";;AAAA,YAAe,IAAI;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/net.d.ts b/node_modules/node-stdlib-browser/cjs/mock/net.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..457f8879af60e14c17c4b730f9f1bd638abe826e --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/net.d.ts @@ -0,0 +1,4 @@ +declare function noop(): void; +declare function bool(): boolean; +export { noop as createServer, noop as createConnection, noop as connect, bool as isIP, bool as isIPv4, bool as isIPv6 }; +//# sourceMappingURL=net.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/net.d.ts.map b/node_modules/node-stdlib-browser/cjs/mock/net.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..c770b3f7d3af86623dffe9e7308939efb12d4336 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/net.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"net.d.ts","sourceRoot":"","sources":["../../mock/net.js"],"names":[],"mappings":"AAAA,8BAAkB;AAClB,iCAEC"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/net.js b/node_modules/node-stdlib-browser/cjs/mock/net.js new file mode 100644 index 0000000000000000000000000000000000000000..b621ec712e9f17a674e14a6c4ee41eb4cfe6295c --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/net.js @@ -0,0 +1,16 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function noop() {} +function bool() { + return true; +} + +exports.connect = noop; +exports.createConnection = noop; +exports.createServer = noop; +exports.isIP = bool; +exports.isIPv4 = bool; +exports.isIPv6 = bool; +//# sourceMappingURL=net.js.map diff --git a/node_modules/node-stdlib-browser/cjs/mock/net.js.map b/node_modules/node-stdlib-browser/cjs/mock/net.js.map new file mode 100644 index 0000000000000000000000000000000000000000..319767489bdb5e8a254a583333a3a6dec7506870 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/net.js.map @@ -0,0 +1 @@ +{"version":3,"file":"net.js","sources":["../../mock/net.js"],"sourcesContent":["function noop() {}\nfunction bool() {\n\treturn true;\n}\n\nexport {\n\tnoop as createServer,\n\tnoop as createConnection,\n\tnoop as connect,\n\tbool as isIP,\n\tbool as isIPv4,\n\tbool as isIPv6\n};\n"],"names":["noop","bool"],"mappings":";;;;AAAA,SAASA,IAAIA,GAAG,EAAC;AACjB,SAASC,IAAIA,GAAG;AACf,EAAA,OAAO,IAAI,CAAA;AACZ;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/process.d.ts b/node_modules/node-stdlib-browser/cjs/mock/process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6c2521fe1798b8af275463a324bd54a05f2fb871 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/process.d.ts @@ -0,0 +1,23 @@ +export const features: {}; +/** + * @param {unknown[]} arguments_ + */ +export function nextTick(...arguments_: unknown[]): void; +export const pid: 1; +export const browser: true; +declare const environment: {}; +/** @type {string[]} */ +export const argv: string[]; +/** + * @param {unknown} name + */ +export function binding(name: unknown): void; +declare function getCwd(): string; +/** + * @param {string} dir + */ +declare function getChdir(dir: string): void; +declare function noop(): void; +declare const platformName: "browser"; +export { environment as env, getCwd as cwd, getChdir as chdir, noop as exit, noop as kill, noop as umask, noop as dlopen, noop as uptime, noop as memoryUsage, noop as uvCounters, platformName as platform, platformName as arch, platformName as execPath, platformName as title }; +//# sourceMappingURL=process.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/process.d.ts.map b/node_modules/node-stdlib-browser/cjs/mock/process.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..adb32ac7abfb4e5aeb19d3013d6ef2485dfa4c0c --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/process.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"process.d.ts","sourceRoot":"","sources":["../../mock/process.js"],"names":[],"mappings":"AAyBA,0BAAoB;AApBpB;;GAEG;AACH,wCAFW,OAAO,EAAE,QAUnB;AAWD,oBAAc;AACd,2BAAqB;AACrB,8BAAuB;AACvB,uBAAuB;AACvB,mBADW,MAAM,EAAE,CACH;AAbhB;;GAEG;AACH,8BAFW,OAAO,QAIjB;AAWD,kCAEC;AACD;;GAEG;AACH,+BAFW,MAAM,QAIhB;AAtCD,8BAAkB;AAsBlB,sCAA+B"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/process.js b/node_modules/node-stdlib-browser/cjs/mock/process.js new file mode 100644 index 0000000000000000000000000000000000000000..72861763bd24dcea88a7d0fa3bea19d450b5db67 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/process.js @@ -0,0 +1,73 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var path = require('path'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var path__default = /*#__PURE__*/_interopDefaultLegacy(path); + +/* globals unknown */ +function noop() {} +/** + * @param {unknown[]} arguments_ + */ +function nextTick() { + for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) { + arguments_[_key] = arguments[_key]; + } + var function_ = arguments_[0]; + arguments_.shift(); + setTimeout(function () { + if (typeof function_ === 'function') { + function_.apply(null, arguments_); + } + }, 0); +} + +/** + * @param {unknown} name + */ +function binding(name) { + throw new Error('No such module. (Possibly not yet loaded)'); +} +var features = {}; +var platformName = 'browser'; +var pid = 1; +var browser = true; +var environment = {}; +/** @type {string[]} */ +var argv = []; +var cwd = '/'; +function getCwd() { + return cwd; +} +/** + * @param {string} dir + */ +function getChdir(dir) { + cwd = path__default["default"].resolve(dir, cwd); +} + +exports.arch = platformName; +exports.argv = argv; +exports.binding = binding; +exports.browser = browser; +exports.chdir = getChdir; +exports.cwd = getCwd; +exports.dlopen = noop; +exports.env = environment; +exports.execPath = platformName; +exports.exit = noop; +exports.features = features; +exports.kill = noop; +exports.memoryUsage = noop; +exports.nextTick = nextTick; +exports.pid = pid; +exports.platform = platformName; +exports.title = platformName; +exports.umask = noop; +exports.uptime = noop; +exports.uvCounters = noop; +//# sourceMappingURL=process.js.map diff --git a/node_modules/node-stdlib-browser/cjs/mock/process.js.map b/node_modules/node-stdlib-browser/cjs/mock/process.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bea937297231f59d72393196da530e75665d6224 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/process.js.map @@ -0,0 +1 @@ +{"version":3,"file":"process.js","sources":["../../mock/process.js"],"sourcesContent":["/* globals unknown */\n\nimport path from 'path';\n\nfunction noop() {}\n/**\n * @param {unknown[]} arguments_\n */\nfunction nextTick(...arguments_) {\n\tconst [function_] = arguments_;\n\targuments_.shift();\n\tsetTimeout(function () {\n\t\tif (typeof function_ === 'function') {\n\t\t\tfunction_.apply(null, arguments_);\n\t\t}\n\t}, 0);\n}\n\n/**\n * @param {unknown} name\n */\nfunction binding(name) {\n\tthrow new Error('No such module. (Possibly not yet loaded)');\n}\n\nconst features = {};\nconst platformName = 'browser';\nconst pid = 1;\nconst browser = true;\nconst environment = {};\n/** @type {string[]} */\nconst argv = [];\n\nlet cwd = '/';\nfunction getCwd() {\n\treturn cwd;\n}\n/**\n * @param {string} dir\n */\nfunction getChdir(dir) {\n\tcwd = path.resolve(dir, cwd);\n}\n\nexport {\n\tfeatures,\n\tnextTick,\n\tpid,\n\tbrowser,\n\tenvironment as env,\n\targv,\n\tbinding,\n\tgetCwd as cwd,\n\tgetChdir as chdir,\n\tnoop as exit,\n\tnoop as kill,\n\tnoop as umask,\n\tnoop as dlopen,\n\tnoop as uptime,\n\tnoop as memoryUsage,\n\tnoop as uvCounters,\n\tplatformName as platform,\n\tplatformName as arch,\n\tplatformName as execPath,\n\tplatformName as title\n};\n"],"names":["noop","nextTick","_len","arguments","length","arguments_","Array","_key","function_","shift","setTimeout","apply","binding","name","Error","features","platformName","pid","browser","environment","argv","cwd","getCwd","getChdir","dir","path","resolve"],"mappings":";;;;;;;;;;AAAA;AAIA,SAASA,IAAIA,GAAG,EAAC;AACjB;AACA;AACA;AACA,SAASC,QAAQA,GAAgB;AAAA,EAAA,KAAA,IAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,EAAZC,UAAU,GAAAC,IAAAA,KAAA,CAAAJ,IAAA,GAAAK,IAAA,GAAA,CAAA,EAAAA,IAAA,GAAAL,IAAA,EAAAK,IAAA,EAAA,EAAA;AAAVF,IAAAA,UAAU,CAAAE,IAAA,CAAAJ,GAAAA,SAAA,CAAAI,IAAA,CAAA,CAAA;AAAA,GAAA;EAC9B,IAAOC,SAAS,GAAIH,UAAU,CAAA,CAAA,CAAA,CAAA;EAC9BA,UAAU,CAACI,KAAK,EAAE,CAAA;AAClBC,EAAAA,UAAU,CAAC,YAAY;AACtB,IAAA,IAAI,OAAOF,SAAS,KAAK,UAAU,EAAE;AACpCA,MAAAA,SAAS,CAACG,KAAK,CAAC,IAAI,EAAEN,UAAU,CAAC,CAAA;AAClC,KAAA;GACA,EAAE,CAAC,CAAC,CAAA;AACN,CAAA;;AAEA;AACA;AACA;AACA,SAASO,OAAOA,CAACC,IAAI,EAAE;AACtB,EAAA,MAAM,IAAIC,KAAK,CAAC,2CAA2C,CAAC,CAAA;AAC7D,CAAA;AAEMC,IAAAA,QAAQ,GAAG,GAAE;AACbC,IAAAA,YAAY,GAAG,UAAS;AACxBC,IAAAA,GAAG,GAAG,EAAC;AACPC,IAAAA,OAAO,GAAG,KAAI;AACdC,IAAAA,WAAW,GAAG,GAAE;AACtB;AACMC,IAAAA,IAAI,GAAG,GAAE;AAEf,IAAIC,GAAG,GAAG,GAAG,CAAA;AACb,SAASC,MAAMA,GAAG;AACjB,EAAA,OAAOD,GAAG,CAAA;AACX,CAAA;AACA;AACA;AACA;AACA,SAASE,QAAQA,CAACC,GAAG,EAAE;EACtBH,GAAG,GAAGI,wBAAI,CAACC,OAAO,CAACF,GAAG,EAAEH,GAAG,CAAC,CAAA;AAC7B;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/punycode.d.ts b/node_modules/node-stdlib-browser/cjs/mock/punycode.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f1cc8d68e2d13b31423595f5cf26cce11251876c --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/punycode.d.ts @@ -0,0 +1,11 @@ +export namespace ucs2 { + export { passthrough as encode }; + export { passthrough as decode }; +} +export const version: "0.0.0"; +/** + * @param {string} s + */ +declare function passthrough(s: string): string; +export { passthrough as encode, passthrough as decode, passthrough as toUnicode, passthrough as toASCII }; +//# sourceMappingURL=punycode.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/punycode.d.ts.map b/node_modules/node-stdlib-browser/cjs/mock/punycode.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..b27e1ad2d7f56daf13905462ec2535d7a2306e3e --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/punycode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"punycode.d.ts","sourceRoot":"","sources":["../../mock/punycode.js"],"names":[],"mappings":";;;;AAYA,8BAAwB;AAZxB;;GAEG;AACH,gCAFW,MAAM,UAIhB"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/punycode.js b/node_modules/node-stdlib-browser/cjs/mock/punycode.js new file mode 100644 index 0000000000000000000000000000000000000000..131be1f6c7168abddf2edc6176cdb8a5fdba89a7 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/punycode.js @@ -0,0 +1,23 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +/** + * @param {string} s + */ +function passthrough(s) { + return s; +} +var ucs2 = { + encode: passthrough, + decode: passthrough +}; +var version = '0.0.0'; + +exports.decode = passthrough; +exports.encode = passthrough; +exports.toASCII = passthrough; +exports.toUnicode = passthrough; +exports.ucs2 = ucs2; +exports.version = version; +//# sourceMappingURL=punycode.js.map diff --git a/node_modules/node-stdlib-browser/cjs/mock/punycode.js.map b/node_modules/node-stdlib-browser/cjs/mock/punycode.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f3248a6e74b2079091b0d6d61672393112dae232 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/punycode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"punycode.js","sources":["../../mock/punycode.js"],"sourcesContent":["/**\n * @param {string} s\n */\nfunction passthrough(s) {\n\treturn s;\n}\n\nconst ucs2 = {\n\tencode: passthrough,\n\tdecode: passthrough\n};\n\nconst version = '0.0.0';\n\nexport {\n\tucs2,\n\tversion,\n\tpassthrough as encode,\n\tpassthrough as decode,\n\tpassthrough as toUnicode,\n\tpassthrough as toASCII\n};\n"],"names":["passthrough","s","ucs2","encode","decode","version"],"mappings":";;;;AAAA;AACA;AACA;AACA,SAASA,WAAWA,CAACC,CAAC,EAAE;AACvB,EAAA,OAAOA,CAAC,CAAA;AACT,CAAA;AAEA,IAAMC,IAAI,GAAG;AACZC,EAAAA,MAAM,EAAEH,WAAW;AACnBI,EAAAA,MAAM,EAAEJ,WAAAA;AACT,EAAC;AAEKK,IAAAA,OAAO,GAAG;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/tls.d.ts b/node_modules/node-stdlib-browser/cjs/mock/tls.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ae7ac26fa5eb2f55f71d25fc1ecbec88ab0d4548 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/tls.d.ts @@ -0,0 +1 @@ +//# sourceMappingURL=tls.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/tls.d.ts.map b/node_modules/node-stdlib-browser/cjs/mock/tls.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..05deb1ffb20824b389971585f1b261136a7464d7 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/tls.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tls.d.ts","sourceRoot":"","sources":["../../mock/tls.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/tls.js b/node_modules/node-stdlib-browser/cjs/mock/tls.js new file mode 100644 index 0000000000000000000000000000000000000000..482a75727ba7e8c12c4a0ff7a624081fb35c1c78 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/tls.js @@ -0,0 +1,3 @@ +'use strict'; + +//# sourceMappingURL=tls.js.map diff --git a/node_modules/node-stdlib-browser/cjs/mock/tls.js.map b/node_modules/node-stdlib-browser/cjs/mock/tls.js.map new file mode 100644 index 0000000000000000000000000000000000000000..685c93d496f917dd820f89ad84f0240a4990957e --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/tls.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tls.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/tty.d.ts b/node_modules/node-stdlib-browser/cjs/mock/tty.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9bcb95422fe1b61d43b8d6a5f796f232e90640b6 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/tty.d.ts @@ -0,0 +1,3 @@ +declare function noop(): void; +export { noop as isatty, noop as setRawMode }; +//# sourceMappingURL=tty.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/tty.d.ts.map b/node_modules/node-stdlib-browser/cjs/mock/tty.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..394e6afc25216ac770a25e32a635aed9406a5585 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/tty.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tty.d.ts","sourceRoot":"","sources":["../../mock/tty.js"],"names":[],"mappings":"AAAA,8BAAkB"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/mock/tty.js b/node_modules/node-stdlib-browser/cjs/mock/tty.js new file mode 100644 index 0000000000000000000000000000000000000000..0f8bfd846c6fce37f59d492b37a36da79c21e56c --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/tty.js @@ -0,0 +1,9 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function noop() {} + +exports.isatty = noop; +exports.setRawMode = noop; +//# sourceMappingURL=tty.js.map diff --git a/node_modules/node-stdlib-browser/cjs/mock/tty.js.map b/node_modules/node-stdlib-browser/cjs/mock/tty.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1125a6c1ceecd9965e1945e3cbf03c462d9eda8c --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/mock/tty.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tty.js","sources":["../../mock/tty.js"],"sourcesContent":["function noop() {}\n\nexport { noop as isatty, noop as setRawMode };\n"],"names":["noop"],"mappings":";;;;AAAA,SAASA,IAAIA,GAAG;;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/package.json b/node_modules/node-stdlib-browser/cjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0292b9956f2e40d6eb3d0f3998e710d973113aaa --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/package.json @@ -0,0 +1 @@ +{"type":"commonjs"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/proxy/process.d.ts b/node_modules/node-stdlib-browser/cjs/proxy/process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e7c91582c4e3c1cb3c490de10afc87a93524ab2 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/process.d.ts @@ -0,0 +1,73 @@ +export default api; +declare namespace api { + export { nextTick }; + export { title }; + export { browser }; + export { environment as env }; + export { argv }; + export { version }; + export { versions }; + export { on }; + export { addListener }; + export { once }; + export { off }; + export { removeListener }; + export { removeAllListeners }; + export { emit }; + export { emitWarning }; + export { prependListener }; + export { prependOnceListener }; + export { listeners }; + export { binding }; + export { cwd }; + export { chdir }; + export { umask }; + export { exit }; + export { pid }; + export { features }; + export { kill }; + export { dlopen }; + export { uptime }; + export { memoryUsage }; + export { uvCounters }; + export { platform }; + export { arch }; + export { execPath }; + export { execArgv }; +} +import { nextTick } from "node/process"; +import { title } from "node/process"; +export const browser: boolean; +import { env as environment } from "node/process"; +import { argv } from "node/process"; +import { version } from "node/process"; +import { versions } from "node/process"; +import { on } from "node/process"; +import { addListener } from "node/process"; +import { once } from "node/process"; +import { off } from "node/events"; +import { removeListener } from "node/events"; +import { removeAllListeners } from "node/events"; +import { emit } from "node/process"; +export function emitWarning(): void; +import { prependListener } from "node/process"; +import { prependOnceListener } from "node/process"; +import { listeners } from "node/process"; +export const binding: Function; +import { cwd } from "node/process"; +import { chdir } from "node/process"; +import { umask } from "node/process"; +export function exit(): void; +export const pid: 1; +export const features: {}; +export function kill(): void; +export function dlopen(): void; +export function uptime(): void; +export function memoryUsage(): void; +export function uvCounters(): void; +export const platform: "browser"; +export const arch: "browser"; +export const execPath: "browser"; +export const execArgv: string[]; +export { nextTick, title, environment as env, argv, version, versions, on, addListener, once, off, removeListener, removeAllListeners, emit, prependListener, prependOnceListener, listeners, cwd, chdir, umask }; +//# sourceMappingURL=process.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/proxy/process.d.ts.map b/node_modules/node-stdlib-browser/cjs/proxy/process.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..dfe4b4a478cf2f6b7e18e104c560258093aca4f0 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/process.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"process.d.ts","sourceRoot":"","sources":["../../proxy/process.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,8BAAkD;;;;;;;;;;;;AAFlD,oCAAkB;;;;AAIlB,+BAAmD;;;;AAJnD,6BAAkB;AAMlB,oBAAc;AACd,0BAAoB;AAPpB,6BAAkB;AAAlB,+BAAkB;AAAlB,+BAAkB;AAAlB,oCAAkB;AAAlB,mCAAkB;AAalB,iCAA2B;AAC3B,6BAAuB;AACvB,iCAA2B;AAC3B,gCAA8C"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/proxy/process.js b/node_modules/node-stdlib-browser/cjs/proxy/process.js new file mode 100644 index 0000000000000000000000000000000000000000..73742e689ccf74075819d362452c93c6471c83e9 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/process.js @@ -0,0 +1,282 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var browser$1 = {exports: {}}; + +// shim for using process in browser +var process = browser$1.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()); +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop$1() {} + +process.on = noop$1; +process.addListener = noop$1; +process.once = noop$1; +process.off = noop$1; +process.removeListener = noop$1; +process.removeAllListeners = noop$1; +process.emit = noop$1; +process.prependListener = noop$1; +process.prependOnceListener = noop$1; + +process.listeners = function (name) { return [] }; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +function noop() {} +var browser = /** @type {boolean} */browser$1.exports.browser; +var emitWarning = noop; +var binding = /** @type {Function} */browser$1.exports.binding; +var exit = noop; +var pid = 1; +var features = {}; +var kill = noop; +var dlopen = noop; +var uptime = noop; +var memoryUsage = noop; +var uvCounters = noop; +var platform = 'browser'; +var arch = 'browser'; +var execPath = 'browser'; +var execArgv = /** @type {string[]} */[]; +var api = { + nextTick: browser$1.exports.nextTick, + title: browser$1.exports.title, + browser: browser, + env: browser$1.exports.env, + argv: browser$1.exports.argv, + version: browser$1.exports.version, + versions: browser$1.exports.versions, + on: browser$1.exports.on, + addListener: browser$1.exports.addListener, + once: browser$1.exports.once, + off: browser$1.exports.off, + removeListener: browser$1.exports.removeListener, + removeAllListeners: browser$1.exports.removeAllListeners, + emit: browser$1.exports.emit, + emitWarning: emitWarning, + prependListener: browser$1.exports.prependListener, + prependOnceListener: browser$1.exports.prependOnceListener, + listeners: browser$1.exports.listeners, + binding: binding, + cwd: browser$1.exports.cwd, + chdir: browser$1.exports.chdir, + umask: browser$1.exports.umask, + exit: exit, + pid: pid, + features: features, + kill: kill, + dlopen: dlopen, + uptime: uptime, + memoryUsage: memoryUsage, + uvCounters: uvCounters, + platform: platform, + arch: arch, + execPath: execPath, + execArgv: execArgv +}; + +exports.addListener = browser$1.exports.addListener; +exports.arch = arch; +exports.argv = browser$1.exports.argv; +exports.binding = binding; +exports.browser = browser; +exports.chdir = browser$1.exports.chdir; +exports.cwd = browser$1.exports.cwd; +exports["default"] = api; +exports.dlopen = dlopen; +exports.emit = browser$1.exports.emit; +exports.emitWarning = emitWarning; +exports.env = browser$1.exports.env; +exports.execArgv = execArgv; +exports.execPath = execPath; +exports.exit = exit; +exports.features = features; +exports.kill = kill; +exports.listeners = browser$1.exports.listeners; +exports.memoryUsage = memoryUsage; +exports.nextTick = browser$1.exports.nextTick; +exports.off = browser$1.exports.off; +exports.on = browser$1.exports.on; +exports.once = browser$1.exports.once; +exports.pid = pid; +exports.platform = platform; +exports.prependListener = browser$1.exports.prependListener; +exports.prependOnceListener = browser$1.exports.prependOnceListener; +exports.removeAllListeners = browser$1.exports.removeAllListeners; +exports.removeListener = browser$1.exports.removeListener; +exports.title = browser$1.exports.title; +exports.umask = browser$1.exports.umask; +exports.uptime = uptime; +exports.uvCounters = uvCounters; +exports.version = browser$1.exports.version; +exports.versions = browser$1.exports.versions; + +exports = module.exports = api; +//# sourceMappingURL=process.js.map diff --git a/node_modules/node-stdlib-browser/cjs/proxy/process.js.map b/node_modules/node-stdlib-browser/cjs/proxy/process.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9e457d19a7c9fcbddd552dd45e696fbbcb1e5e9a --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/process.js.map @@ -0,0 +1 @@ +{"version":3,"file":"process.js","sources":["../../node_modules/process/browser.js","../../proxy/process.js"],"sourcesContent":["// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import {\n\tnextTick,\n\ttitle,\n\tenv as environment,\n\targv,\n\tversion,\n\tversions,\n\ton,\n\taddListener,\n\tonce,\n\toff,\n\tremoveListener,\n\tremoveAllListeners,\n\temit,\n\tprependListener,\n\tprependOnceListener,\n\tlisteners,\n\tcwd,\n\tchdir,\n\tumask,\n\t// @ts-ignore\n\tbrowser as _browser,\n\t// @ts-ignore\n\tbinding as _binding\n} from 'process/browser.js';\n\nfunction noop() {}\n\nconst browser = /** @type {boolean} */ (_browser);\nconst emitWarning = noop;\nconst binding = /** @type {Function} */ (_binding);\nconst exit = noop;\nconst pid = 1;\nconst features = {};\nconst kill = noop;\nconst dlopen = noop;\nconst uptime = noop;\nconst memoryUsage = noop;\nconst uvCounters = noop;\nconst platform = 'browser';\nconst arch = 'browser';\nconst execPath = 'browser';\nconst execArgv = /** @type {string[]} */ ([]);\n\nconst api = {\n\tnextTick,\n\ttitle,\n\tbrowser,\n\tenv: environment,\n\targv,\n\tversion,\n\tversions,\n\ton,\n\taddListener,\n\tonce,\n\toff,\n\tremoveListener,\n\tremoveAllListeners,\n\temit,\n\temitWarning,\n\tprependListener,\n\tprependOnceListener,\n\tlisteners,\n\tbinding,\n\tcwd,\n\tchdir,\n\tumask,\n\texit,\n\tpid,\n\tfeatures,\n\tkill,\n\tdlopen,\n\tuptime,\n\tmemoryUsage,\n\tuvCounters,\n\tplatform,\n\tarch,\n\texecPath,\n\texecArgv\n};\n\nexport default api;\n\nexport {\n\tnextTick,\n\ttitle,\n\tbrowser,\n\tenvironment as env,\n\targv,\n\tversion,\n\tversions,\n\ton,\n\taddListener,\n\tonce,\n\toff,\n\tremoveListener,\n\tremoveAllListeners,\n\temit,\n\temitWarning,\n\tprependListener,\n\tprependOnceListener,\n\tlisteners,\n\tbinding,\n\tcwd,\n\tchdir,\n\tumask,\n\texit,\n\tpid,\n\tfeatures,\n\tkill,\n\tdlopen,\n\tuptime,\n\tmemoryUsage,\n\tuvCounters,\n\tplatform,\n\tarch,\n\texecPath,\n\texecArgv\n};\n"],"names":["browserModule","noop","browser","_browser","emitWarning","binding","_binding","exit","pid","features","kill","dlopen","uptime","memoryUsage","uvCounters","platform","arch","execPath","execArgv","api","nextTick","title","env","environment","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","cwd","chdir","umask"],"mappings":";;;;;;AAAA;AACA,IAAI,OAAO,GAAGA,SAAc,CAAA,OAAA,GAAG,EAAE,CAAC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,gBAAgB,CAAC;AACrB,IAAI,kBAAkB,CAAC;AACvB;AACA,SAAS,gBAAgB,GAAG;AAC5B,IAAI,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;AACvD,CAAC;AACD,SAAS,mBAAmB,IAAI;AAChC,IAAI,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;AACzD,CAAC;AACD,CAAC,YAAY;AACb,IAAI,IAAI;AACR,QAAQ,IAAI,OAAO,UAAU,KAAK,UAAU,EAAE;AAC9C,YAAY,gBAAgB,GAAG,UAAU,CAAC;AAC1C,SAAS,MAAM;AACf,YAAY,gBAAgB,GAAG,gBAAgB,CAAC;AAChD,SAAS;AACT,KAAK,CAAC,OAAO,CAAC,EAAE;AAChB,QAAQ,gBAAgB,GAAG,gBAAgB,CAAC;AAC5C,KAAK;AACL,IAAI,IAAI;AACR,QAAQ,IAAI,OAAO,YAAY,KAAK,UAAU,EAAE;AAChD,YAAY,kBAAkB,GAAG,YAAY,CAAC;AAC9C,SAAS,MAAM;AACf,YAAY,kBAAkB,GAAG,mBAAmB,CAAC;AACrD,SAAS;AAC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mBAAmB,EAAnBA,qCAAmB;AACnBC,EAAAA,SAAS,EAATA,2BAAS;AACT/B,EAAAA,OAAO,EAAPA,OAAO;AACPgC,EAAAA,GAAG,EAAHA,qBAAG;AACHC,EAAAA,KAAK,EAALA,uBAAK;AACLC,EAAAA,KAAK,EAALA,uBAAK;AACLhC,EAAAA,IAAI,EAAJA,IAAI;AACJC,EAAAA,GAAG,EAAHA,GAAG;AACHC,EAAAA,QAAQ,EAARA,QAAQ;AACRC,EAAAA,IAAI,EAAJA,IAAI;AACJC,EAAAA,MAAM,EAANA,MAAM;AACNC,EAAAA,MAAM,EAANA,MAAM;AACNC,EAAAA,WAAW,EAAXA,WAAW;AACXC,EAAAA,UAAU,EAAVA,UAAU;AACVC,EAAAA,QAAQ,EAARA,QAAQ;AACRC,EAAAA,IAAI,EAAJA,IAAI;AACJC,EAAAA,QAAQ,EAARA,QAAQ;AACRC,EAAAA,QAAQ,EAARA,QAAAA;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/proxy/process/browser.d.ts b/node_modules/node-stdlib-browser/cjs/proxy/process/browser.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..045aaede6ce3bcf090a6921ba61ccb8273a234c3 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/process/browser.d.ts @@ -0,0 +1,4 @@ +export default api; +export * from "../process.js"; +import api from "../process.js"; +//# sourceMappingURL=browser.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/proxy/process/browser.d.ts.map b/node_modules/node-stdlib-browser/cjs/proxy/process/browser.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..0b79217798a33310d839008e9900b74aa1d2ebca --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/process/browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../../../proxy/process/browser.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/proxy/process/browser.js b/node_modules/node-stdlib-browser/cjs/proxy/process/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..bd202d7e6aa971b8b5b3bd08c0df66a1a99f9d9f --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/process/browser.js @@ -0,0 +1,282 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var browser$1 = {exports: {}}; + +// shim for using process in browser +var process = browser$1.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()); +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop$1() {} + +process.on = noop$1; +process.addListener = noop$1; +process.once = noop$1; +process.off = noop$1; +process.removeListener = noop$1; +process.removeAllListeners = noop$1; +process.emit = noop$1; +process.prependListener = noop$1; +process.prependOnceListener = noop$1; + +process.listeners = function (name) { return [] }; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +function noop() {} +var browser = /** @type {boolean} */browser$1.exports.browser; +var emitWarning = noop; +var binding = /** @type {Function} */browser$1.exports.binding; +var exit = noop; +var pid = 1; +var features = {}; +var kill = noop; +var dlopen = noop; +var uptime = noop; +var memoryUsage = noop; +var uvCounters = noop; +var platform = 'browser'; +var arch = 'browser'; +var execPath = 'browser'; +var execArgv = /** @type {string[]} */[]; +var api = { + nextTick: browser$1.exports.nextTick, + title: browser$1.exports.title, + browser: browser, + env: browser$1.exports.env, + argv: browser$1.exports.argv, + version: browser$1.exports.version, + versions: browser$1.exports.versions, + on: browser$1.exports.on, + addListener: browser$1.exports.addListener, + once: browser$1.exports.once, + off: browser$1.exports.off, + removeListener: browser$1.exports.removeListener, + removeAllListeners: browser$1.exports.removeAllListeners, + emit: browser$1.exports.emit, + emitWarning: emitWarning, + prependListener: browser$1.exports.prependListener, + prependOnceListener: browser$1.exports.prependOnceListener, + listeners: browser$1.exports.listeners, + binding: binding, + cwd: browser$1.exports.cwd, + chdir: browser$1.exports.chdir, + umask: browser$1.exports.umask, + exit: exit, + pid: pid, + features: features, + kill: kill, + dlopen: dlopen, + uptime: uptime, + memoryUsage: memoryUsage, + uvCounters: uvCounters, + platform: platform, + arch: arch, + execPath: execPath, + execArgv: execArgv +}; + +exports.addListener = browser$1.exports.addListener; +exports.arch = arch; +exports.argv = browser$1.exports.argv; +exports.binding = binding; +exports.browser = browser; +exports.chdir = browser$1.exports.chdir; +exports.cwd = browser$1.exports.cwd; +exports["default"] = api; +exports.dlopen = dlopen; +exports.emit = browser$1.exports.emit; +exports.emitWarning = emitWarning; +exports.env = browser$1.exports.env; +exports.execArgv = execArgv; +exports.execPath = execPath; +exports.exit = exit; +exports.features = features; +exports.kill = kill; +exports.listeners = browser$1.exports.listeners; +exports.memoryUsage = memoryUsage; +exports.nextTick = browser$1.exports.nextTick; +exports.off = browser$1.exports.off; +exports.on = browser$1.exports.on; +exports.once = browser$1.exports.once; +exports.pid = pid; +exports.platform = platform; +exports.prependListener = browser$1.exports.prependListener; +exports.prependOnceListener = browser$1.exports.prependOnceListener; +exports.removeAllListeners = browser$1.exports.removeAllListeners; +exports.removeListener = browser$1.exports.removeListener; +exports.title = browser$1.exports.title; +exports.umask = browser$1.exports.umask; +exports.uptime = uptime; +exports.uvCounters = uvCounters; +exports.version = browser$1.exports.version; +exports.versions = browser$1.exports.versions; + +exports = module.exports = api; +//# sourceMappingURL=browser.js.map diff --git a/node_modules/node-stdlib-browser/cjs/proxy/process/browser.js.map b/node_modules/node-stdlib-browser/cjs/proxy/process/browser.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0e33f74570d092c006d71da4802330e718976cb6 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/process/browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"browser.js","sources":["../../../node_modules/process/browser.js","../../../proxy/process.js"],"sourcesContent":["// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import {\n\tnextTick,\n\ttitle,\n\tenv as environment,\n\targv,\n\tversion,\n\tversions,\n\ton,\n\taddListener,\n\tonce,\n\toff,\n\tremoveListener,\n\tremoveAllListeners,\n\temit,\n\tprependListener,\n\tprependOnceListener,\n\tlisteners,\n\tcwd,\n\tchdir,\n\tumask,\n\t// @ts-ignore\n\tbrowser as _browser,\n\t// @ts-ignore\n\tbinding as _binding\n} from 'process/browser.js';\n\nfunction noop() {}\n\nconst browser = /** @type {boolean} */ (_browser);\nconst emitWarning = noop;\nconst binding = /** @type {Function} */ (_binding);\nconst exit = noop;\nconst pid = 1;\nconst features = {};\nconst kill = noop;\nconst dlopen = noop;\nconst uptime = noop;\nconst memoryUsage = noop;\nconst uvCounters = noop;\nconst platform = 'browser';\nconst arch = 'browser';\nconst execPath = 'browser';\nconst execArgv = /** @type {string[]} */ ([]);\n\nconst api = {\n\tnextTick,\n\ttitle,\n\tbrowser,\n\tenv: environment,\n\targv,\n\tversion,\n\tversions,\n\ton,\n\taddListener,\n\tonce,\n\toff,\n\tremoveListener,\n\tremoveAllListeners,\n\temit,\n\temitWarning,\n\tprependListener,\n\tprependOnceListener,\n\tlisteners,\n\tbinding,\n\tcwd,\n\tchdir,\n\tumask,\n\texit,\n\tpid,\n\tfeatures,\n\tkill,\n\tdlopen,\n\tuptime,\n\tmemoryUsage,\n\tuvCounters,\n\tplatform,\n\tarch,\n\texecPath,\n\texecArgv\n};\n\nexport default api;\n\nexport {\n\tnextTick,\n\ttitle,\n\tbrowser,\n\tenvironment as env,\n\targv,\n\tversion,\n\tversions,\n\ton,\n\taddListener,\n\tonce,\n\toff,\n\tremoveListener,\n\tremoveAllListeners,\n\temit,\n\temitWarning,\n\tprependListener,\n\tprependOnceListener,\n\tlisteners,\n\tbinding,\n\tcwd,\n\tchdir,\n\tumask,\n\texit,\n\tpid,\n\tfeatures,\n\tkill,\n\tdlopen,\n\tuptime,\n\tmemoryUsage,\n\tuvCounters,\n\tplatform,\n\tarch,\n\texecPath,\n\texecArgv\n};\n"],"names":["browserModule","noop","browser","_browser","emitWarning","binding","_binding","exit","pid","features","kill","dlopen","uptime","memoryUsage","uvCounters","platform","arch","execPath","execArgv","api","nextTick","title","env","environment","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","cwd","chdir","umask"],"mappings":";;;;;;AAAA;AACA,IAAI,OAAO,GAAGA,SAAc,CAAA,OAAA,GAAG,EAAE,CAAC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,gBAAgB,CAAC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;AACRC,EAAAA,QAAQ,EAARA,QAAAA;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/proxy/querystring.d.ts b/node_modules/node-stdlib-browser/cjs/proxy/querystring.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d1db762d2cb168b1696de2e8bae35faf28da9b3 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/querystring.d.ts @@ -0,0 +1,21 @@ +/// +/// +export default api; +export type qsEscape = typeof import("querystring").escape; +export type qsUnescape = typeof import("querystring").unescape; +declare namespace api { + export { decode }; + export { encode }; + export { parse }; + export { stringify }; + export { qsEscape as escape }; + export { qsUnescape as unescape }; +} +import { decode } from "querystring-es3"; +import { encode } from "querystring-es3"; +import { parse } from "querystring-es3"; +import { stringify } from "querystring-es3"; +declare function qsEscape(str: string): string; +declare function qsUnescape(str: string): string; +export { decode, encode, parse, stringify, qsEscape as escape, qsUnescape as unescape }; +//# sourceMappingURL=querystring.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/proxy/querystring.d.ts.map b/node_modules/node-stdlib-browser/cjs/proxy/querystring.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..551d6e1f7397f5cb9e8facd03c9c339c3dcf07c4 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/querystring.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"querystring.d.ts","sourceRoot":"","sources":["../../proxy/querystring.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAwCm+I,+CAAslB;AAAA,iDAA+wB"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/proxy/querystring.js b/node_modules/node-stdlib-browser/cjs/proxy/querystring.js new file mode 100644 index 0000000000000000000000000000000000000000..8bb23ea9aa569dca3366c139684efa20a27f2e30 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/querystring.js @@ -0,0 +1,55 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var querystringEs3 = require('querystring-es3'); + +/** + * @typedef {import('querystring').escape} qsEscape + * @typedef {import('querystring').unescape} qsUnescape + */ + +/** + * @type {qsEscape} + */ +function qsEscape(string) { + return encodeURIComponent(string); +} + +/** + * @type {qsUnescape} + */ +function qsUnescape(string) { + return decodeURIComponent(string); +} +var api = { + decode: querystringEs3.decode, + encode: querystringEs3.encode, + parse: querystringEs3.parse, + stringify: querystringEs3.stringify, + escape: qsEscape, + unescape: qsUnescape +}; + +Object.defineProperty(exports, 'decode', { + enumerable: true, + get: function () { return querystringEs3.decode; } +}); +Object.defineProperty(exports, 'encode', { + enumerable: true, + get: function () { return querystringEs3.encode; } +}); +Object.defineProperty(exports, 'parse', { + enumerable: true, + get: function () { return querystringEs3.parse; } +}); +Object.defineProperty(exports, 'stringify', { + enumerable: true, + get: function () { return querystringEs3.stringify; } +}); +exports["default"] = api; +exports.escape = qsEscape; +exports.unescape = qsUnescape; + +exports = module.exports = api; +//# sourceMappingURL=querystring.js.map diff --git a/node_modules/node-stdlib-browser/cjs/proxy/querystring.js.map b/node_modules/node-stdlib-browser/cjs/proxy/querystring.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d75944f65617e29a0d5bb891daab952848c61f62 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/querystring.js.map @@ -0,0 +1 @@ +{"version":3,"file":"querystring.js","sources":["../../proxy/querystring.js"],"sourcesContent":["/**\n * @typedef {import('querystring').escape} qsEscape\n * @typedef {import('querystring').unescape} qsUnescape\n */\n\nimport { decode, encode, parse, stringify } from 'querystring-es3';\n\n/**\n * @type {qsEscape}\n */\nfunction qsEscape(string) {\n\treturn encodeURIComponent(string);\n}\n\n/**\n * @type {qsUnescape}\n */\nfunction qsUnescape(string) {\n\treturn decodeURIComponent(string);\n}\n\nconst api = {\n\tdecode,\n\tencode,\n\tparse,\n\tstringify,\n\tescape: qsEscape,\n\tunescape: qsUnescape\n};\n\nexport default api;\n\nexport {\n\tdecode,\n\tencode,\n\tparse,\n\tstringify,\n\tqsEscape as escape,\n\tqsUnescape as unescape\n};\n"],"names":["qsEscape","string","encodeURIComponent","qsUnescape","decodeURIComponent","api","decode","encode","parse","stringify","escape","unescape"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;;AAIA;AACA;AACA;AACA,SAASA,QAAQA,CAACC,MAAM,EAAE;EACzB,OAAOC,kBAAkB,CAACD,MAAM,CAAC,CAAA;AAClC,CAAA;;AAEA;AACA;AACA;AACA,SAASE,UAAUA,CAACF,MAAM,EAAE;EAC3B,OAAOG,kBAAkB,CAACH,MAAM,CAAC,CAAA;AAClC,CAAA;AAEA,IAAMI,GAAG,GAAG;AACXC,EAAAA,MAAM,EAANA,qBAAM;AACNC,EAAAA,MAAM,EAANA,qBAAM;AACNC,EAAAA,KAAK,EAALA,oBAAK;AACLC,EAAAA,SAAS,EAATA,wBAAS;AACTC,EAAAA,MAAM,EAAEV,QAAQ;AAChBW,EAAAA,QAAQ,EAAER,UAAAA;AACX;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/proxy/url.d.ts b/node_modules/node-stdlib-browser/cjs/proxy/url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5df2d7d49d48c352ef62218761a19c96188ed1b7 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/url.d.ts @@ -0,0 +1,50 @@ +/// +export default api; +export type domainToASCII = typeof import("url").domainToASCII; +export type domainToUnicode = typeof import("url").domainToUnicode; +export type pathToFileURL = typeof import("url").pathToFileURL; +export type fileURLToPath = typeof import("url").fileURLToPath; +export type URLFormatOptions = import('url').URLFormatOptions; +export type UrlObject = import('url').UrlObject; +export type formatImport = typeof format; +export type parseImport = typeof parse; +export type resolveImport = typeof resolve; +export type UrlImport = import('url').Url; +declare namespace api { + export { formatImportWithOverloads as format }; + export { parseImport as parse }; + export { resolveImport as resolve }; + export { resolveObject }; + export { UrlImport as Url }; + export { URL }; + export { URLSearchParams }; + export { domainToASCII }; + export { domainToUnicode }; + export { pathToFileURL }; + export { fileURLToPath }; +} +declare const formatImportWithOverloads: ((urlObject: URL, options?: URLFormatOptions) => string) & ((urlObject: UrlObject | string, options?: never) => string); +declare const parseImport: typeof parse; +declare const resolveImport: typeof resolve; +declare const UrlImport: Url; +export const URL: { + new (url: string | URL, base?: string | URL | undefined): URL; + prototype: URL; + createObjectURL(obj: Blob | MediaSource): string; + revokeObjectURL(url: string): void; +}; +export const URLSearchParams: { + new (init?: string | URLSearchParams | string[][] | Record | undefined): URLSearchParams; + prototype: URLSearchParams; + toString(): string; +}; +export const domainToASCII: domainToASCII; +export const domainToUnicode: domainToUnicode; +export const pathToFileURL: (url: string) => URL; +export const fileURLToPath: typeof import("url").fileURLToPath & ((path: string | URL) => string); +import { format } from "url"; +import { parse } from "url"; +import { resolve } from "url"; +import { Url } from "url"; +export { formatImportWithOverloads as format, parseImport as parse, resolveImport as resolve, resolveObject, UrlImport as Url }; +//# sourceMappingURL=url.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/proxy/url.d.ts.map b/node_modules/node-stdlib-browser/cjs/proxy/url.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..36c8f7806bf35955b16426fd2caa98bd8a161c59 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/url.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"url.d.ts","sourceRoot":"","sources":["../../proxy/url.js"],"names":[],"mappings":";;;;;;+BAGa,OAAO,KAAK,EAAE,gBAAgB;wBAC9B,OAAO,KAAK,EAAE,SAAS;;;;wBAIvB,OAAO,KAAK,EAAE,GAAG;;;;;;;;;;;;;;AA2I9B,sDAGmB,GAAG,YAAY,gBAAgB,KAAK,MAAM,iBAC1C,SAAS,GAAG,MAAM,YAAY,KAAK,KAAK,MAAM,EAuC9D;AA1KH,wCAAsD;AACtD,4CAA4D;AAE5D,6BAAgD;AAEhD;;;;;EAA2B;AAE3B;;;;EAAmD;AA+DnD,4BAEW,aAAa,CAOrB;AAEH,8BAEW,eAAe,CAOvB;AAEH,kCAEiB,MAAM,KAAK,GAAG,CAc5B;AAEH,yEAEmC,MAAM,GAAG,GAAG,KAAK,MAAM,EAavD"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/proxy/url.js b/node_modules/node-stdlib-browser/cjs/proxy/url.js new file mode 100644 index 0000000000000000000000000000000000000000..e752b84ac5c6ee7380a01f3bac39e929db8e2f0b --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/url.js @@ -0,0 +1,1072 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var require$$0 = require('punycode/'); +var require$$1 = require('qs'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0); +var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); + +/* + * Copyright Joyent, Inc. and other Node contributors. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to permit + * persons to whom the Software is furnished to do so, subject to the + * following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + * USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +var punycode = require$$0__default["default"]; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +/* + * define these here so at least they only have to be + * compiled once on the first module load. + */ +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/, + + /* + * RFC 2396: characters reserved for delimiting URLs. + * We actually just auto-escape these. + */ + delims = [ + '<', '>', '"', '`', ' ', '\r', '\n', '\t' + ], + + // RFC 2396: characters not allowed for various reasons. + unwise = [ + '{', '}', '|', '\\', '^', '`' + ].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + /* + * Characters that are never ever allowed in a hostname. + * Note that any invalid chars are also handled, but these + * are the ones that are *expected* to be seen, so we fast-path + * them. + */ + nonHostChars = [ + '%', '/', '?', ';', '#' + ].concat(autoEscape), + hostEndingChars = [ + '/', '?', '#' + ], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + javascript: true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + javascript: true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + http: true, + https: true, + ftp: true, + gopher: true, + file: true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require$$1__default["default"]; + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && typeof url === 'object' && url instanceof Url) { return url; } + + var u = new Url(); + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) { + if (typeof url !== 'string') { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + /* + * Copy chrome, IE, opera backslash-handling behavior. + * Back slashes before the query string get converted to forward slashes + * See: https://code.google.com/p/chromium/issues/detail?id=25916 + */ + var queryIndex = url.indexOf('?'), + splitter = queryIndex !== -1 && queryIndex < url.indexOf('#') ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + /* + * trim before proceeding. + * This is to support parse stuff like " http://foo.com \n" + */ + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + /* + * figure out if it's got a host + * user@server is *always* interpreted as a hostname, and url + * resolution will treat //foo/bar as host=foo,path=bar because that's + * how the browser resolves relative URLs. + */ + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@/]+@[^@/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { + + /* + * there's a hostname. + * the first instance of /, ?, ;, or # ends the host. + * + * If there is an @ in the hostname, then non-host chars *are* allowed + * to the left of the last @ sign, unless some host-ending character + * comes *before* the @-sign. + * URLs are obnoxious. + * + * ex: + * http://a@b@c/ => user:a@b host:c + * http://a@b?@c => user:a host:c path:/?@c + */ + + /* + * v0.12 TODO(isaacs): This is not quite how Chrome does things. + * Review our test case against browsers more comprehensively. + */ + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; } + } + + /* + * at this point, either we have an explicit point where the + * auth portion cannot go past, or the last @ char is the decider. + */ + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + /* + * atSign must be in auth portion. + * http://a@b/c@d => host:b auth:a path:/c@d + */ + atSign = rest.lastIndexOf('@', hostEnd); + } + + /* + * Now we have a portion which is definitely the auth. + * Pull that off. + */ + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; } + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) { hostEnd = rest.length; } + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + /* + * we've indicated that there is a hostname, + * so even if it's empty, it has to be present. + */ + this.hostname = this.hostname || ''; + + /* + * if hostname begins with [ and ends with ] + * assume that it's an IPv6 address. + */ + var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) { continue; } + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + /* + * we replace non-ASCII char with a temporary placeholder + * we need this to make sure size of hostname is not + * broken by replacing non-ASCII by nothing + */ + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + /* + * IDNA Support: Returns a punycoded representation of "domain". + * It only converts parts of the domain name that + * have non-ASCII characters, i.e. it doesn't matter if + * you call it with a domain that already is ASCII-only. + */ + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + /* + * strip [ and ] from the hostname + * the host field still retains them, though + */ + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + /* + * now rest is set to the post-host stuff. + * chop off any delim chars. + */ + if (!unsafeProtocol[lowerProto]) { + + /* + * First, make 100% sure that any "autoEscape" chars get + * escaped, even if encodeURIComponent doesn't think they + * need to be. + */ + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) { continue; } + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) { this.pathname = rest; } + if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { + this.pathname = '/'; + } + + // to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + /* + * ensure it's an object, and not a string url. + * If it's an obj, this is a no-op. + * this way, you can call url_format() on strings + * to clean up potentially wonky urls. + */ + if (typeof obj === 'string') { obj = urlParse(obj); } + if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); } + return obj.format(); +} + +Url.prototype.format = function () { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && typeof this.query === 'object' && Object.keys(this.query).length) { + query = querystring.stringify(this.query, { + arrayFormat: 'repeat', + addQueryPrefix: false + }); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; } + + /* + * only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + * unless they had them to begin with. + */ + if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; } + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; } + if (search && search.charAt(0) !== '?') { search = '?' + search; } + + pathname = pathname.replace(/[?#]/g, function (match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function (relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) { return relative; } + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function (relative) { + if (typeof relative === 'string') { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + /* + * hash is always overridden, no matter what. + * even href="" will remove it. + */ + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') { result[rkey] = relative[rkey]; } + } + + // urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { + result.pathname = '/'; + result.path = result.pathname; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + /* + * if it's a known url protocol, then changing + * the protocol does weird things + * first, if it's not file:, then we MUST have a host, + * and if there was a path + * to begin with, then we MUST have a path. + * if it is file:, then the host is dropped, + * because that's known to be hostless. + * anything else is assumed to be absolute. + */ + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())) { } + if (!relative.host) { relative.host = ''; } + if (!relative.hostname) { relative.hostname = ''; } + if (relPath[0] !== '') { relPath.unshift(''); } + if (relPath.length < 2) { relPath.unshift(''); } + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = result.pathname && result.pathname.charAt(0) === '/', + isRelAbs = relative.host || relative.pathname && relative.pathname.charAt(0) === '/', + mustEndAbs = isRelAbs || isSourceAbs || (result.host && relative.pathname), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + /* + * if the url is a non-slashed url, then relative + * links like ../.. should be able + * to crawl up to the hostname, as well. This is strange. + * result.protocol has already been set by now. + * Later on, put the first path part into the host field. + */ + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') { srcPath[0] = result.host; } else { srcPath.unshift(result.host); } + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') { relPath[0] = relative.host; } else { relPath.unshift(relative.host); } + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = relative.host || relative.host === '' ? relative.host : result.host; + result.hostname = relative.hostname || relative.hostname === '' ? relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + /* + * it's relative + * throw away the existing file, and take the new path instead. + */ + if (!srcPath) { srcPath = []; } + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (relative.search != null) { + /* + * just pull out the search. + * like href='?foo'. + * Put this after the other two cases because it simplifies the booleans + */ + if (psychotic) { + result.host = srcPath.shift(); + result.hostname = result.host; + /* + * occationaly the auth can get stuck only in host + * this especially happens in cases like + * url.resolveObject('mailto:local1@domain1', 'local2@domain2') + */ + var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.hostname = authInHost.shift(); + result.host = result.hostname; + } + } + result.search = relative.search; + result.query = relative.query; + // to support http.request + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + /* + * no path at all. easy. + * we've already handled the other stuff above. + */ + result.pathname = null; + // to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + /* + * if a url ENDs in . or .., then it must get a trailing slash. + * however, if it ends in anything else non-slashy, + * then it must NOT get a trailing slash. + */ + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''; + + /* + * strip single dots, resolve double dots to parent dir + * if the path tries to go above the root, `up` ends up > 0 + */ + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; + result.host = result.hostname; + /* + * occationaly the auth can get stuck only in host + * this especially happens in cases like + * url.resolveObject('mailto:local1@domain1', 'local2@domain2') + */ + var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.hostname = authInHost.shift(); + result.host = result.hostname; + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (srcPath.length > 0) { + result.pathname = srcPath.join('/'); + } else { + result.pathname = null; + result.path = null; + } + + // to support request.http + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function () { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) { this.hostname = host; } +}; + +var parse = urlParse; +var resolve$1 = urlResolve; +var resolveObject = urlResolveObject; +var format = urlFormat; + +var Url_1 = Url; + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// path.resolve([from ...], to) +// posix version +function resolve() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : '/'; + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +var _globalThis = function (Object) { + function get() { + var _global = this || self; + delete Object.prototype.__magic__; + return _global; + } + if (typeof globalThis === "object") { + return globalThis; + } + if (this) { + return get(); + } else { + Object.defineProperty(Object.prototype, "__magic__", { + configurable: true, + get: get + }); + var _global = __magic__; + return _global; + } +}(Object); +var formatImport = /** @type {formatImport}*/format; +var parseImport = /** @type {parseImport}*/parse; +var resolveImport = /** @type {resolveImport}*/resolve$1; +// @ts-ignore +var UrlImport = /** @type {UrlImport}*/Url_1; +var URL = _globalThis.URL; +/* eslint-disable-next-line unicorn/prevent-abbreviations */ +var URLSearchParams = _globalThis.URLSearchParams; +var percentRegEx = /%/g; +var backslashRegEx = /\\/g; +var newlineRegEx = /\n/g; +var carriageReturnRegEx = /\r/g; +var tabRegEx = /\t/g; +var CHAR_FORWARD_SLASH = 47; + +/** + * @param {unknown} instance + */ +function isURLInstance(instance) { + var resolved = /** @type {URL|null} */instance != null ? instance : null; + return Boolean(resolved !== null && (resolved == null ? void 0 : resolved.href) && (resolved == null ? void 0 : resolved.origin)); +} + +/** + * @param {URL} url + */ +function getPathFromURLPosix(url) { + if (url.hostname !== '') { + throw new TypeError("File URL host must be \"localhost\" or empty on browser"); + } + var pathname = url.pathname; + for (var n = 0; n < pathname.length; n++) { + if (pathname[n] === '%') { + // @ts-ignore + var third = pathname.codePointAt(n + 2) | 0x20; + if (pathname[n + 1] === '2' && third === 102) { + throw new TypeError('File URL path must not include encoded / characters'); + } + } + } + return decodeURIComponent(pathname); +} + +/** + * @param {string} filepath + */ +function encodePathChars(filepath) { + if (filepath.includes('%')) { + filepath = filepath.replace(percentRegEx, '%25'); + } + if (filepath.includes('\\')) { + filepath = filepath.replace(backslashRegEx, '%5C'); + } + if (filepath.includes('\n')) { + filepath = filepath.replace(newlineRegEx, '%0A'); + } + if (filepath.includes('\r')) { + filepath = filepath.replace(carriageReturnRegEx, '%0D'); + } + if (filepath.includes('\t')) { + filepath = filepath.replace(tabRegEx, '%09'); + } + return filepath; +} +var domainToASCII = +/** + * @type {domainToASCII} + */ +function domainToASCII(domain) { + if (typeof domain === 'undefined') { + throw new TypeError('The "domain" argument must be specified'); + } + return new URL("http://" + domain).hostname; +}; +var domainToUnicode = +/** + * @type {domainToUnicode} + */ +function domainToUnicode(domain) { + if (typeof domain === 'undefined') { + throw new TypeError('The "domain" argument must be specified'); + } + return new URL("http://" + domain).hostname; +}; +var pathToFileURL = +/** + * @type {(url: string) => URL} + */ +function pathToFileURL(filepath) { + var outURL = new URL('file://'); + var resolved = resolve(filepath); + var filePathLast = filepath.charCodeAt(filepath.length - 1); + if (filePathLast === CHAR_FORWARD_SLASH && resolved[resolved.length - 1] !== '/') { + resolved += '/'; + } + outURL.pathname = encodePathChars(resolved); + return outURL; +}; +var fileURLToPath = +/** + * @type {fileURLToPath & ((path: string | URL) => string)} + */ +function fileURLToPath(path) { + if (!isURLInstance(path) && typeof path !== 'string') { + throw new TypeError("The \"path\" argument must be of type string or an instance of URL. Received type " + typeof path + " (" + path + ")"); + } + var resolved = new URL(path); + if (resolved.protocol !== 'file:') { + throw new TypeError('The URL must be of scheme file'); + } + return getPathFromURLPosix(resolved); +}; +var formatImportWithOverloads = +/** + * @type {( + * ((urlObject: URL, options?: URLFormatOptions) => string) & + * ((urlObject: UrlObject | string, options?: never) => string) + * )} + */ +function formatImportWithOverloads(urlObject, options) { + var _options$auth, _options$fragment, _options$search, _options$unicode; + if (options === void 0) { + options = {}; + } + if (!(urlObject instanceof URL)) { + return formatImport(urlObject); + } + if (typeof options !== 'object' || options === null) { + throw new TypeError('The "options" argument must be of type object.'); + } + var auth = (_options$auth = options.auth) != null ? _options$auth : true; + var fragment = (_options$fragment = options.fragment) != null ? _options$fragment : true; + var search = (_options$search = options.search) != null ? _options$search : true; + (_options$unicode = options.unicode) != null ? _options$unicode : false; + var parsed = new URL(urlObject.toString()); + if (!auth) { + parsed.username = ''; + parsed.password = ''; + } + if (!fragment) { + parsed.hash = ''; + } + if (!search) { + parsed.search = ''; + } + return parsed.toString(); +}; +var api = { + format: formatImportWithOverloads, + parse: parseImport, + resolve: resolveImport, + resolveObject: resolveObject, + Url: UrlImport, + URL: URL, + URLSearchParams: URLSearchParams, + domainToASCII: domainToASCII, + domainToUnicode: domainToUnicode, + pathToFileURL: pathToFileURL, + fileURLToPath: fileURLToPath +}; + +exports.URL = URL; +exports.URLSearchParams = URLSearchParams; +exports.Url = UrlImport; +exports["default"] = api; +exports.domainToASCII = domainToASCII; +exports.domainToUnicode = domainToUnicode; +exports.fileURLToPath = fileURLToPath; +exports.format = formatImportWithOverloads; +exports.parse = parseImport; +exports.pathToFileURL = pathToFileURL; +exports.resolve = resolveImport; +exports.resolveObject = resolveObject; + +exports = module.exports = api; +//# sourceMappingURL=url.js.map diff --git a/node_modules/node-stdlib-browser/cjs/proxy/url.js.map b/node_modules/node-stdlib-browser/cjs/proxy/url.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a0ee236b3840c881379bc7d95d004cc1e73d43c7 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/proxy/url.js.map @@ -0,0 +1 @@ +{"version":3,"file":"url.js","sources":["../../node_modules/url/url.js","../../node_modules/rollup-plugin-node-builtins/src/es6/path.js","../../proxy/url.js"],"sourcesContent":["/*\n * Copyright Joyent, Inc. and other Node contributors.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to permit\n * persons to whom the Software is furnished to do so, subject to the\n * following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n'use strict';\n\nvar punycode = require('punycode/');\n\nfunction Url() {\n this.protocol = null;\n this.slashes = null;\n this.auth = null;\n this.host = null;\n this.port = null;\n this.hostname = null;\n this.hash = null;\n this.search = null;\n this.query = null;\n this.pathname = null;\n this.path = null;\n this.href = null;\n}\n\n// Reference: RFC 3986, RFC 1808, RFC 2396\n\n/*\n * define these here so at least they only have to be\n * compiled once on the first module load.\n */\nvar protocolPattern = /^([a-z0-9.+-]+:)/i,\n portPattern = /:[0-9]*$/,\n\n // Special case for a simple path URL\n simplePathPattern = /^(\\/\\/?(?!\\/)[^?\\s]*)(\\?[^\\s]*)?$/,\n\n /*\n * RFC 2396: characters reserved for delimiting URLs.\n * We actually just auto-escape these.\n */\n delims = [\n '<', '>', '\"', '`', ' ', '\\r', '\\n', '\\t'\n ],\n\n // RFC 2396: characters not allowed for various reasons.\n unwise = [\n '{', '}', '|', '\\\\', '^', '`'\n ].concat(delims),\n\n // Allowed by RFCs, but cause of XSS attacks. Always escape these.\n autoEscape = ['\\''].concat(unwise),\n /*\n * Characters that are never ever allowed in a hostname.\n * Note that any invalid chars are also handled, but these\n * are the ones that are *expected* to be seen, so we fast-path\n * them.\n */\n nonHostChars = [\n '%', '/', '?', ';', '#'\n ].concat(autoEscape),\n hostEndingChars = [\n '/', '?', '#'\n ],\n hostnameMaxLen = 255,\n hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,\n hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,\n // protocols that can allow \"unsafe\" and \"unwise\" chars.\n unsafeProtocol = {\n javascript: true,\n 'javascript:': true\n },\n // protocols that never have a hostname.\n hostlessProtocol = {\n javascript: true,\n 'javascript:': true\n },\n // protocols that always contain a // bit.\n slashedProtocol = {\n http: true,\n https: true,\n ftp: true,\n gopher: true,\n file: true,\n 'http:': true,\n 'https:': true,\n 'ftp:': true,\n 'gopher:': true,\n 'file:': true\n },\n querystring = require('qs');\n\nfunction urlParse(url, parseQueryString, slashesDenoteHost) {\n if (url && typeof url === 'object' && url instanceof Url) { return url; }\n\n var u = new Url();\n u.parse(url, parseQueryString, slashesDenoteHost);\n return u;\n}\n\nUrl.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {\n if (typeof url !== 'string') {\n throw new TypeError(\"Parameter 'url' must be a string, not \" + typeof url);\n }\n\n /*\n * Copy chrome, IE, opera backslash-handling behavior.\n * Back slashes before the query string get converted to forward slashes\n * See: https://code.google.com/p/chromium/issues/detail?id=25916\n */\n var queryIndex = url.indexOf('?'),\n splitter = queryIndex !== -1 && queryIndex < url.indexOf('#') ? '?' : '#',\n uSplit = url.split(splitter),\n slashRegex = /\\\\/g;\n uSplit[0] = uSplit[0].replace(slashRegex, '/');\n url = uSplit.join(splitter);\n\n var rest = url;\n\n /*\n * trim before proceeding.\n * This is to support parse stuff like \" http://foo.com \\n\"\n */\n rest = rest.trim();\n\n if (!slashesDenoteHost && url.split('#').length === 1) {\n // Try fast path regexp\n var simplePath = simplePathPattern.exec(rest);\n if (simplePath) {\n this.path = rest;\n this.href = rest;\n this.pathname = simplePath[1];\n if (simplePath[2]) {\n this.search = simplePath[2];\n if (parseQueryString) {\n this.query = querystring.parse(this.search.substr(1));\n } else {\n this.query = this.search.substr(1);\n }\n } else if (parseQueryString) {\n this.search = '';\n this.query = {};\n }\n return this;\n }\n }\n\n var proto = protocolPattern.exec(rest);\n if (proto) {\n proto = proto[0];\n var lowerProto = proto.toLowerCase();\n this.protocol = lowerProto;\n rest = rest.substr(proto.length);\n }\n\n /*\n * figure out if it's got a host\n * user@server is *always* interpreted as a hostname, and url\n * resolution will treat //foo/bar as host=foo,path=bar because that's\n * how the browser resolves relative URLs.\n */\n if (slashesDenoteHost || proto || rest.match(/^\\/\\/[^@/]+@[^@/]+/)) {\n var slashes = rest.substr(0, 2) === '//';\n if (slashes && !(proto && hostlessProtocol[proto])) {\n rest = rest.substr(2);\n this.slashes = true;\n }\n }\n\n if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) {\n\n /*\n * there's a hostname.\n * the first instance of /, ?, ;, or # ends the host.\n *\n * If there is an @ in the hostname, then non-host chars *are* allowed\n * to the left of the last @ sign, unless some host-ending character\n * comes *before* the @-sign.\n * URLs are obnoxious.\n *\n * ex:\n * http://a@b@c/ => user:a@b host:c\n * http://a@b?@c => user:a host:c path:/?@c\n */\n\n /*\n * v0.12 TODO(isaacs): This is not quite how Chrome does things.\n * Review our test case against browsers more comprehensively.\n */\n\n // find the first instance of any hostEndingChars\n var hostEnd = -1;\n for (var i = 0; i < hostEndingChars.length; i++) {\n var hec = rest.indexOf(hostEndingChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; }\n }\n\n /*\n * at this point, either we have an explicit point where the\n * auth portion cannot go past, or the last @ char is the decider.\n */\n var auth, atSign;\n if (hostEnd === -1) {\n // atSign can be anywhere.\n atSign = rest.lastIndexOf('@');\n } else {\n /*\n * atSign must be in auth portion.\n * http://a@b/c@d => host:b auth:a path:/c@d\n */\n atSign = rest.lastIndexOf('@', hostEnd);\n }\n\n /*\n * Now we have a portion which is definitely the auth.\n * Pull that off.\n */\n if (atSign !== -1) {\n auth = rest.slice(0, atSign);\n rest = rest.slice(atSign + 1);\n this.auth = decodeURIComponent(auth);\n }\n\n // the host is the remaining to the left of the first non-host char\n hostEnd = -1;\n for (var i = 0; i < nonHostChars.length; i++) {\n var hec = rest.indexOf(nonHostChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; }\n }\n // if we still have not hit it, then the entire thing is a host.\n if (hostEnd === -1) { hostEnd = rest.length; }\n\n this.host = rest.slice(0, hostEnd);\n rest = rest.slice(hostEnd);\n\n // pull out port.\n this.parseHost();\n\n /*\n * we've indicated that there is a hostname,\n * so even if it's empty, it has to be present.\n */\n this.hostname = this.hostname || '';\n\n /*\n * if hostname begins with [ and ends with ]\n * assume that it's an IPv6 address.\n */\n var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']';\n\n // validate a little.\n if (!ipv6Hostname) {\n var hostparts = this.hostname.split(/\\./);\n for (var i = 0, l = hostparts.length; i < l; i++) {\n var part = hostparts[i];\n if (!part) { continue; }\n if (!part.match(hostnamePartPattern)) {\n var newpart = '';\n for (var j = 0, k = part.length; j < k; j++) {\n if (part.charCodeAt(j) > 127) {\n /*\n * we replace non-ASCII char with a temporary placeholder\n * we need this to make sure size of hostname is not\n * broken by replacing non-ASCII by nothing\n */\n newpart += 'x';\n } else {\n newpart += part[j];\n }\n }\n // we test again with ASCII char only\n if (!newpart.match(hostnamePartPattern)) {\n var validParts = hostparts.slice(0, i);\n var notHost = hostparts.slice(i + 1);\n var bit = part.match(hostnamePartStart);\n if (bit) {\n validParts.push(bit[1]);\n notHost.unshift(bit[2]);\n }\n if (notHost.length) {\n rest = '/' + notHost.join('.') + rest;\n }\n this.hostname = validParts.join('.');\n break;\n }\n }\n }\n }\n\n if (this.hostname.length > hostnameMaxLen) {\n this.hostname = '';\n } else {\n // hostnames are always lower case.\n this.hostname = this.hostname.toLowerCase();\n }\n\n if (!ipv6Hostname) {\n /*\n * IDNA Support: Returns a punycoded representation of \"domain\".\n * It only converts parts of the domain name that\n * have non-ASCII characters, i.e. it doesn't matter if\n * you call it with a domain that already is ASCII-only.\n */\n this.hostname = punycode.toASCII(this.hostname);\n }\n\n var p = this.port ? ':' + this.port : '';\n var h = this.hostname || '';\n this.host = h + p;\n this.href += this.host;\n\n /*\n * strip [ and ] from the hostname\n * the host field still retains them, though\n */\n if (ipv6Hostname) {\n this.hostname = this.hostname.substr(1, this.hostname.length - 2);\n if (rest[0] !== '/') {\n rest = '/' + rest;\n }\n }\n }\n\n /*\n * now rest is set to the post-host stuff.\n * chop off any delim chars.\n */\n if (!unsafeProtocol[lowerProto]) {\n\n /*\n * First, make 100% sure that any \"autoEscape\" chars get\n * escaped, even if encodeURIComponent doesn't think they\n * need to be.\n */\n for (var i = 0, l = autoEscape.length; i < l; i++) {\n var ae = autoEscape[i];\n if (rest.indexOf(ae) === -1) { continue; }\n var esc = encodeURIComponent(ae);\n if (esc === ae) {\n esc = escape(ae);\n }\n rest = rest.split(ae).join(esc);\n }\n }\n\n // chop off from the tail first.\n var hash = rest.indexOf('#');\n if (hash !== -1) {\n // got a fragment string.\n this.hash = rest.substr(hash);\n rest = rest.slice(0, hash);\n }\n var qm = rest.indexOf('?');\n if (qm !== -1) {\n this.search = rest.substr(qm);\n this.query = rest.substr(qm + 1);\n if (parseQueryString) {\n this.query = querystring.parse(this.query);\n }\n rest = rest.slice(0, qm);\n } else if (parseQueryString) {\n // no query string, but parseQueryString still requested\n this.search = '';\n this.query = {};\n }\n if (rest) { this.pathname = rest; }\n if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) {\n this.pathname = '/';\n }\n\n // to support http.request\n if (this.pathname || this.search) {\n var p = this.pathname || '';\n var s = this.search || '';\n this.path = p + s;\n }\n\n // finally, reconstruct the href based on what has been validated.\n this.href = this.format();\n return this;\n};\n\n// format a parsed object into a url string\nfunction urlFormat(obj) {\n /*\n * ensure it's an object, and not a string url.\n * If it's an obj, this is a no-op.\n * this way, you can call url_format() on strings\n * to clean up potentially wonky urls.\n */\n if (typeof obj === 'string') { obj = urlParse(obj); }\n if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); }\n return obj.format();\n}\n\nUrl.prototype.format = function () {\n var auth = this.auth || '';\n if (auth) {\n auth = encodeURIComponent(auth);\n auth = auth.replace(/%3A/i, ':');\n auth += '@';\n }\n\n var protocol = this.protocol || '',\n pathname = this.pathname || '',\n hash = this.hash || '',\n host = false,\n query = '';\n\n if (this.host) {\n host = auth + this.host;\n } else if (this.hostname) {\n host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']');\n if (this.port) {\n host += ':' + this.port;\n }\n }\n\n if (this.query && typeof this.query === 'object' && Object.keys(this.query).length) {\n query = querystring.stringify(this.query, {\n arrayFormat: 'repeat',\n addQueryPrefix: false\n });\n }\n\n var search = this.search || (query && ('?' + query)) || '';\n\n if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; }\n\n /*\n * only the slashedProtocols get the //. Not mailto:, xmpp:, etc.\n * unless they had them to begin with.\n */\n if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) {\n host = '//' + (host || '');\n if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; }\n } else if (!host) {\n host = '';\n }\n\n if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; }\n if (search && search.charAt(0) !== '?') { search = '?' + search; }\n\n pathname = pathname.replace(/[?#]/g, function (match) {\n return encodeURIComponent(match);\n });\n search = search.replace('#', '%23');\n\n return protocol + host + pathname + search + hash;\n};\n\nfunction urlResolve(source, relative) {\n return urlParse(source, false, true).resolve(relative);\n}\n\nUrl.prototype.resolve = function (relative) {\n return this.resolveObject(urlParse(relative, false, true)).format();\n};\n\nfunction urlResolveObject(source, relative) {\n if (!source) { return relative; }\n return urlParse(source, false, true).resolveObject(relative);\n}\n\nUrl.prototype.resolveObject = function (relative) {\n if (typeof relative === 'string') {\n var rel = new Url();\n rel.parse(relative, false, true);\n relative = rel;\n }\n\n var result = new Url();\n var tkeys = Object.keys(this);\n for (var tk = 0; tk < tkeys.length; tk++) {\n var tkey = tkeys[tk];\n result[tkey] = this[tkey];\n }\n\n /*\n * hash is always overridden, no matter what.\n * even href=\"\" will remove it.\n */\n result.hash = relative.hash;\n\n // if the relative url is empty, then there's nothing left to do here.\n if (relative.href === '') {\n result.href = result.format();\n return result;\n }\n\n // hrefs like //foo/bar always cut to the protocol.\n if (relative.slashes && !relative.protocol) {\n // take everything except the protocol from relative\n var rkeys = Object.keys(relative);\n for (var rk = 0; rk < rkeys.length; rk++) {\n var rkey = rkeys[rk];\n if (rkey !== 'protocol') { result[rkey] = relative[rkey]; }\n }\n\n // urlParse appends trailing / to urls like http://www.example.com\n if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) {\n result.pathname = '/';\n result.path = result.pathname;\n }\n\n result.href = result.format();\n return result;\n }\n\n if (relative.protocol && relative.protocol !== result.protocol) {\n /*\n * if it's a known url protocol, then changing\n * the protocol does weird things\n * first, if it's not file:, then we MUST have a host,\n * and if there was a path\n * to begin with, then we MUST have a path.\n * if it is file:, then the host is dropped,\n * because that's known to be hostless.\n * anything else is assumed to be absolute.\n */\n if (!slashedProtocol[relative.protocol]) {\n var keys = Object.keys(relative);\n for (var v = 0; v < keys.length; v++) {\n var k = keys[v];\n result[k] = relative[k];\n }\n result.href = result.format();\n return result;\n }\n\n result.protocol = relative.protocol;\n if (!relative.host && !hostlessProtocol[relative.protocol]) {\n var relPath = (relative.pathname || '').split('/');\n while (relPath.length && !(relative.host = relPath.shift())) { }\n if (!relative.host) { relative.host = ''; }\n if (!relative.hostname) { relative.hostname = ''; }\n if (relPath[0] !== '') { relPath.unshift(''); }\n if (relPath.length < 2) { relPath.unshift(''); }\n result.pathname = relPath.join('/');\n } else {\n result.pathname = relative.pathname;\n }\n result.search = relative.search;\n result.query = relative.query;\n result.host = relative.host || '';\n result.auth = relative.auth;\n result.hostname = relative.hostname || relative.host;\n result.port = relative.port;\n // to support http.request\n if (result.pathname || result.search) {\n var p = result.pathname || '';\n var s = result.search || '';\n result.path = p + s;\n }\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n }\n\n var isSourceAbs = result.pathname && result.pathname.charAt(0) === '/',\n isRelAbs = relative.host || relative.pathname && relative.pathname.charAt(0) === '/',\n mustEndAbs = isRelAbs || isSourceAbs || (result.host && relative.pathname),\n removeAllDots = mustEndAbs,\n srcPath = result.pathname && result.pathname.split('/') || [],\n relPath = relative.pathname && relative.pathname.split('/') || [],\n psychotic = result.protocol && !slashedProtocol[result.protocol];\n\n /*\n * if the url is a non-slashed url, then relative\n * links like ../.. should be able\n * to crawl up to the hostname, as well. This is strange.\n * result.protocol has already been set by now.\n * Later on, put the first path part into the host field.\n */\n if (psychotic) {\n result.hostname = '';\n result.port = null;\n if (result.host) {\n if (srcPath[0] === '') { srcPath[0] = result.host; } else { srcPath.unshift(result.host); }\n }\n result.host = '';\n if (relative.protocol) {\n relative.hostname = null;\n relative.port = null;\n if (relative.host) {\n if (relPath[0] === '') { relPath[0] = relative.host; } else { relPath.unshift(relative.host); }\n }\n relative.host = null;\n }\n mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');\n }\n\n if (isRelAbs) {\n // it's absolute.\n result.host = relative.host || relative.host === '' ? relative.host : result.host;\n result.hostname = relative.hostname || relative.hostname === '' ? relative.hostname : result.hostname;\n result.search = relative.search;\n result.query = relative.query;\n srcPath = relPath;\n // fall through to the dot-handling below.\n } else if (relPath.length) {\n /*\n * it's relative\n * throw away the existing file, and take the new path instead.\n */\n if (!srcPath) { srcPath = []; }\n srcPath.pop();\n srcPath = srcPath.concat(relPath);\n result.search = relative.search;\n result.query = relative.query;\n } else if (relative.search != null) {\n /*\n * just pull out the search.\n * like href='?foo'.\n * Put this after the other two cases because it simplifies the booleans\n */\n if (psychotic) {\n result.host = srcPath.shift();\n result.hostname = result.host;\n /*\n * occationaly the auth can get stuck only in host\n * this especially happens in cases like\n * url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n */\n var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.hostname = authInHost.shift();\n result.host = result.hostname;\n }\n }\n result.search = relative.search;\n result.query = relative.query;\n // to support http.request\n if (result.pathname !== null || result.search !== null) {\n result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : '');\n }\n result.href = result.format();\n return result;\n }\n\n if (!srcPath.length) {\n /*\n * no path at all. easy.\n * we've already handled the other stuff above.\n */\n result.pathname = null;\n // to support http.request\n if (result.search) {\n result.path = '/' + result.search;\n } else {\n result.path = null;\n }\n result.href = result.format();\n return result;\n }\n\n /*\n * if a url ENDs in . or .., then it must get a trailing slash.\n * however, if it ends in anything else non-slashy,\n * then it must NOT get a trailing slash.\n */\n var last = srcPath.slice(-1)[0];\n var hasTrailingSlash = (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === '';\n\n /*\n * strip single dots, resolve double dots to parent dir\n * if the path tries to go above the root, `up` ends up > 0\n */\n var up = 0;\n for (var i = srcPath.length; i >= 0; i--) {\n last = srcPath[i];\n if (last === '.') {\n srcPath.splice(i, 1);\n } else if (last === '..') {\n srcPath.splice(i, 1);\n up++;\n } else if (up) {\n srcPath.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (!mustEndAbs && !removeAllDots) {\n for (; up--; up) {\n srcPath.unshift('..');\n }\n }\n\n if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {\n srcPath.unshift('');\n }\n\n if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {\n srcPath.push('');\n }\n\n var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/');\n\n // put the host back\n if (psychotic) {\n result.hostname = isAbsolute ? '' : srcPath.length ? srcPath.shift() : '';\n result.host = result.hostname;\n /*\n * occationaly the auth can get stuck only in host\n * this especially happens in cases like\n * url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n */\n var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.hostname = authInHost.shift();\n result.host = result.hostname;\n }\n }\n\n mustEndAbs = mustEndAbs || (result.host && srcPath.length);\n\n if (mustEndAbs && !isAbsolute) {\n srcPath.unshift('');\n }\n\n if (srcPath.length > 0) {\n result.pathname = srcPath.join('/');\n } else {\n result.pathname = null;\n result.path = null;\n }\n\n // to support request.http\n if (result.pathname !== null || result.search !== null) {\n result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : '');\n }\n result.auth = relative.auth || result.auth;\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n};\n\nUrl.prototype.parseHost = function () {\n var host = this.host;\n var port = portPattern.exec(host);\n if (port) {\n port = port[0];\n if (port !== ':') {\n this.port = port.substr(1);\n }\n host = host.substr(0, host.length - port.length);\n }\n if (host) { this.hostname = host; }\n};\n\nexports.parse = urlParse;\nexports.resolve = urlResolve;\nexports.resolveObject = urlResolveObject;\nexports.format = urlFormat;\n\nexports.Url = Url;\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// resolves . and .. elements in a path array with directory names there\n// must be no slashes, empty elements, or device names (c:\\) in the array\n// (so also no leading and trailing slashes - it does not distinguish\n// relative and absolute paths)\nfunction normalizeArray(parts, allowAboveRoot) {\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = parts.length - 1; i >= 0; i--) {\n var last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// Split a filename into [root, dir, basename, ext], unix version\n// 'root' is just a slash, or nothing.\nvar splitPathRe =\n /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/;\nvar splitPath = function(filename) {\n return splitPathRe.exec(filename).slice(1);\n};\n\n// path.resolve([from ...], to)\n// posix version\nexport function resolve() {\n var resolvedPath = '',\n resolvedAbsolute = false;\n\n for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path = (i >= 0) ? arguments[i] : '/';\n\n // Skip empty and invalid entries\n if (typeof path !== 'string') {\n throw new TypeError('Arguments to path.resolve must be strings');\n } else if (!path) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {\n return !!p;\n }), !resolvedAbsolute).join('/');\n\n return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';\n};\n\n// path.normalize(path)\n// posix version\nexport function normalize(path) {\n var isPathAbsolute = isAbsolute(path),\n trailingSlash = substr(path, -1) === '/';\n\n // Normalize the path\n path = normalizeArray(filter(path.split('/'), function(p) {\n return !!p;\n }), !isPathAbsolute).join('/');\n\n if (!path && !isPathAbsolute) {\n path = '.';\n }\n if (path && trailingSlash) {\n path += '/';\n }\n\n return (isPathAbsolute ? '/' : '') + path;\n};\n\n// posix version\nexport function isAbsolute(path) {\n return path.charAt(0) === '/';\n}\n\n// posix version\nexport function join() {\n var paths = Array.prototype.slice.call(arguments, 0);\n return normalize(filter(paths, function(p, index) {\n if (typeof p !== 'string') {\n throw new TypeError('Arguments to path.join must be strings');\n }\n return p;\n }).join('/'));\n}\n\n\n// path.relative(from, to)\n// posix version\nexport function relative(from, to) {\n from = resolve(from).substr(1);\n to = resolve(to).substr(1);\n\n function trim(arr) {\n var start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') break;\n }\n\n var end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') break;\n }\n\n if (start > end) return [];\n return arr.slice(start, end - start + 1);\n }\n\n var fromParts = trim(from.split('/'));\n var toParts = trim(to.split('/'));\n\n var length = Math.min(fromParts.length, toParts.length);\n var samePartsLength = length;\n for (var i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n var outputParts = [];\n for (var i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n}\n\nexport var sep = '/';\nexport var delimiter = ':';\n\nexport function dirname(path) {\n var result = splitPath(path),\n root = result[0],\n dir = result[1];\n\n if (!root && !dir) {\n // No dirname whatsoever\n return '.';\n }\n\n if (dir) {\n // It has a dirname, strip trailing slash\n dir = dir.substr(0, dir.length - 1);\n }\n\n return root + dir;\n}\n\nexport function basename(path, ext) {\n var f = splitPath(path)[2];\n // TODO: make this comparison case-insensitive on windows?\n if (ext && f.substr(-1 * ext.length) === ext) {\n f = f.substr(0, f.length - ext.length);\n }\n return f;\n}\n\n\nexport function extname(path) {\n return splitPath(path)[3];\n}\nexport default {\n extname: extname,\n basename: basename,\n dirname: dirname,\n sep: sep,\n delimiter: delimiter,\n relative: relative,\n join: join,\n isAbsolute: isAbsolute,\n normalize: normalize,\n resolve: resolve\n};\nfunction filter (xs, f) {\n if (xs.filter) return xs.filter(f);\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n if (f(xs[i], i, xs)) res.push(xs[i]);\n }\n return res;\n}\n\n// String.prototype.substr - negative index don't work in IE8\nvar substr = 'ab'.substr(-1) === 'b' ?\n function (str, start, len) { return str.substr(start, len) } :\n function (str, start, len) {\n if (start < 0) start = str.length + start;\n return str.substr(start, len);\n }\n;\n","/* globals unknown */\n\n/**\n * @typedef {import('url').URLFormatOptions} URLFormatOptions\n * @typedef {import('url').UrlObject} UrlObject\n * @typedef {import('url').format} formatImport\n * @typedef {import('url').parse} parseImport\n * @typedef {import('url').resolve} resolveImport\n * @typedef {import('url').Url} UrlImport\n * @typedef {import('url').fileURLToPath} fileURLToPath\n * @typedef {import('url').pathToFileURL} pathToFileURL\n * @typedef {import('url').domainToUnicode} domainToUnicode\n * @typedef {import('url').domainToASCII} domainToASCII\n */\n\n// @ts-ignore\nimport { format, parse, resolve, resolveObject, Url } from 'url';\nimport { resolve as pathResolve } from 'path';\n\nconst formatImport = /** @type {formatImport}*/ (format);\nconst parseImport = /** @type {parseImport}*/ (parse);\nconst resolveImport = /** @type {resolveImport}*/ (resolve);\n// @ts-ignore\nconst UrlImport = /** @type {UrlImport}*/ (Url);\n\nconst URL = globalThis.URL;\n/* eslint-disable-next-line unicorn/prevent-abbreviations */\nconst URLSearchParams = globalThis.URLSearchParams;\n\nconst percentRegEx = /%/g;\nconst backslashRegEx = /\\\\/g;\nconst newlineRegEx = /\\n/g;\nconst carriageReturnRegEx = /\\r/g;\nconst tabRegEx = /\\t/g;\nconst CHAR_FORWARD_SLASH = 47;\n\n/**\n * @param {unknown} instance\n */\nfunction isURLInstance(instance) {\n\tconst resolved = /** @type {URL|null} */ (instance ?? null);\n\treturn Boolean(resolved !== null && resolved?.href && resolved?.origin);\n}\n\n/**\n * @param {URL} url\n */\nfunction getPathFromURLPosix(url) {\n\tif (url.hostname !== '') {\n\t\tthrow new TypeError(\n\t\t\t`File URL host must be \"localhost\" or empty on browser`\n\t\t);\n\t}\n\tconst pathname = url.pathname;\n\tfor (let n = 0; n < pathname.length; n++) {\n\t\tif (pathname[n] === '%') {\n\t\t\t// @ts-ignore\n\t\t\tconst third = pathname.codePointAt(n + 2) | 0x20;\n\t\t\tif (pathname[n + 1] === '2' && third === 102) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t'File URL path must not include encoded / characters'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn decodeURIComponent(pathname);\n}\n\n/**\n * @param {string} filepath\n */\nfunction encodePathChars(filepath) {\n\tif (filepath.includes('%')) {\n\t\tfilepath = filepath.replace(percentRegEx, '%25');\n\t}\n\tif (filepath.includes('\\\\')) {\n\t\tfilepath = filepath.replace(backslashRegEx, '%5C');\n\t}\n\tif (filepath.includes('\\n')) {\n\t\tfilepath = filepath.replace(newlineRegEx, '%0A');\n\t}\n\tif (filepath.includes('\\r')) {\n\t\tfilepath = filepath.replace(carriageReturnRegEx, '%0D');\n\t}\n\tif (filepath.includes('\\t')) {\n\t\tfilepath = filepath.replace(tabRegEx, '%09');\n\t}\n\treturn filepath;\n}\n\nconst domainToASCII =\n\t/**\n\t * @type {domainToASCII}\n\t */\n\tfunction (domain) {\n\t\tif (typeof domain === 'undefined') {\n\t\t\tthrow new TypeError('The \"domain\" argument must be specified');\n\t\t}\n\t\treturn new URL(`http://${domain}`).hostname;\n\t};\n\nconst domainToUnicode =\n\t/**\n\t * @type {domainToUnicode}\n\t */\n\tfunction (domain) {\n\t\tif (typeof domain === 'undefined') {\n\t\t\tthrow new TypeError('The \"domain\" argument must be specified');\n\t\t}\n\t\treturn new URL(`http://${domain}`).hostname;\n\t};\n\nconst pathToFileURL =\n\t/**\n\t * @type {(url: string) => URL}\n\t */\n\tfunction (filepath) {\n\t\tconst outURL = new URL('file://');\n\t\tlet resolved = pathResolve(filepath);\n\t\tconst filePathLast = filepath.charCodeAt(filepath.length - 1);\n\t\tif (\n\t\t\tfilePathLast === CHAR_FORWARD_SLASH &&\n\t\t\tresolved[resolved.length - 1] !== '/'\n\t\t) {\n\t\t\tresolved += '/';\n\t\t}\n\t\toutURL.pathname = encodePathChars(resolved);\n\t\treturn outURL;\n\t};\n\nconst fileURLToPath =\n\t/**\n\t * @type {fileURLToPath & ((path: string | URL) => string)}\n\t */\n\tfunction (path) {\n\t\tif (!isURLInstance(path) && typeof path !== 'string') {\n\t\t\tthrow new TypeError(\n\t\t\t\t`The \"path\" argument must be of type string or an instance of URL. Received type ${typeof path} (${path})`\n\t\t\t);\n\t\t}\n\t\tconst resolved = new URL(path);\n\t\tif (resolved.protocol !== 'file:') {\n\t\t\tthrow new TypeError('The URL must be of scheme file');\n\t\t}\n\t\treturn getPathFromURLPosix(resolved);\n\t};\n\nconst formatImportWithOverloads =\n\t/**\n\t * @type {(\n\t * ((urlObject: URL, options?: URLFormatOptions) => string) &\n\t * ((urlObject: UrlObject | string, options?: never) => string)\n\t * )}\n\t */\n\tfunction (urlObject, options = {}) {\n\t\tif (!(urlObject instanceof URL)) {\n\t\t\treturn formatImport(urlObject);\n\t\t}\n\n\t\tif (typeof options !== 'object' || options === null) {\n\t\t\tthrow new TypeError(\n\t\t\t\t'The \"options\" argument must be of type object.'\n\t\t\t);\n\t\t}\n\n\t\tconst auth = options.auth ?? true;\n\t\tconst fragment = options.fragment ?? true;\n\t\tconst search = options.search ?? true;\n\t\tconst unicode = options.unicode ?? false;\n\n\t\tconst parsed = new URL(urlObject.toString());\n\n\t\tif (!auth) {\n\t\t\tparsed.username = '';\n\t\t\tparsed.password = '';\n\t\t}\n\n\t\tif (!fragment) {\n\t\t\tparsed.hash = '';\n\t\t}\n\n\t\tif (!search) {\n\t\t\tparsed.search = '';\n\t\t}\n\n\t\tif (unicode) {\n\t\t\t// Not implemented\n\t\t}\n\n\t\treturn parsed.toString();\n\t};\n\nconst api = {\n\tformat: formatImportWithOverloads,\n\tparse: parseImport,\n\tresolve: resolveImport,\n\tresolveObject,\n\tUrl: UrlImport,\n\tURL,\n\tURLSearchParams,\n\tdomainToASCII,\n\tdomainToUnicode,\n\tpathToFileURL,\n\tfileURLToPath\n};\n\nexport default api;\n\nexport {\n\tformatImportWithOverloads as format,\n\tparseImport as parse,\n\tresolveImport as resolve,\n\tresolveObject,\n\tUrlImport as Url,\n\tURL,\n\tURLSearchParams,\n\tdomainToASCII,\n\tdomainToUnicode,\n\tpathToFileURL,\n\tfileURLToPath\n};\n"],"names":["require$$0","require$$1","resolve","formatImport","format","parseImport","parse","resolveImport","UrlImport","Url","URL","_globalThis","URLSearchParams","percentRegEx","backslashRegEx","newlineRegEx","carriageReturnRegEx","tabRegEx","CHAR_FORWARD_SLASH","isURLInstance","instance","resolved","Boolean","href","origin","getPathFromURLPosix","url","hostname","TypeError","pathname","n","length","third","codePointAt","decodeURIComponent","encodePathChars","filepath","includes","replace","domainToASCII","domain","domainToUnicode","pathToFileURL","outURL","pathResolve","filePathLast","charCodeAt","fileURLToPath","path","protocol","formatImportWithOverloads","urlObject","options","_options$auth","_options$fragment","_options$search","_options$unicode","auth","fragment","search","unicode","parsed","toString","username","password","hash","api","resolveObject"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA;AACA,IAAI,QAAQ,GAAGA,8BAAoB,CAAC;AACpC;AACA,SAAS,GAAG,GAAG;AACf,EAAE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;AACvB,EAAE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;AACtB,EAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACnB,EAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACnB,EAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACnB,EAAE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;AACvB,EAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACnB,EAAE,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;AACrB,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;AACpB,EAAE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;AACvB,EAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACnB,EAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACnB,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,eA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GAAI,IAAI,CAAA;EACzC,IAAMK,MAAM,GAAAJ,CAAAA,eAAA,GAAGH,OAAO,CAACO,MAAM,KAAA,IAAA,GAAAJ,eAAA,GAAI,IAAI,CAAA;EACxBC,CAAAA,gBAAA,GAAGJ,OAAO,CAACQ,OAAO,KAAA,IAAA,GAAAJ,gBAAA,GAAI,MAAK;EAExC,IAAMK,MAAM,GAAG,IAAInD,GAAG,CAACyC,SAAS,CAACW,QAAQ,EAAE,CAAC,CAAA;EAE5C,IAAI,CAACL,IAAI,EAAE;IACVI,MAAM,CAACE,QAAQ,GAAG,EAAE,CAAA;IACpBF,MAAM,CAACG,QAAQ,GAAG,EAAE,CAAA;AACrB,GAAA;EAEA,IAAI,CAACN,QAAQ,EAAE;IACdG,MAAM,CAACI,IAAI,GAAG,EAAE,CAAA;AACjB,GAAA;EAEA,IAAI,CAACN,MAAM,EAAE;IACZE,MAAM,CAACF,MAAM,GAAG,EAAE,CAAA;AACnB,GAAA;AAMA,EAAA,OAAOE,MAAM,CAACC,QAAQ,EAAE,CAAA;AACzB,EAAC;AAEF,IAAMI,GAAG,GAAG;AACX9D,EAAAA,MAAM,EAAE8C,yBAAyB;AACjC5C,EAAAA,KAAK,EAAED,WAAW;AAClBH,EAAAA,OAAO,EAAEK,aAAa;AACtB4D,EAAAA,aAAa,EAAbA,aAAa;AACb1D,EAAAA,GAAG,EAAED,SAAS;AACdE,EAAAA,GAAG,EAAHA,GAAG;AACHE,EAAAA,eAAe,EAAfA,eAAe;AACf2B,EAAAA,aAAa,EAAbA,aAAa;AACbE,EAAAA,eAAe,EAAfA,eAAe;AACfC,EAAAA,aAAa,EAAbA,aAAa;AACbK,EAAAA,aAAa,EAAbA,aAAAA;AACD;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/types/lib.d.ts b/node_modules/node-stdlib-browser/cjs/types/lib.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4048e05ef034ef2b1a8a7d5c6bfa6cc8f3fa8176 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/types/lib.d.ts @@ -0,0 +1,10 @@ +/// +declare module 'querystring-es3' { + import { decode, encode, parse, stringify } from 'querystring'; + export { decode, encode, parse, stringify }; +} +declare module 'process/browser.js' { + const process: NodeJS.Process; + export = process; +} +//# sourceMappingURL=lib.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/cjs/types/lib.d.ts.map b/node_modules/node-stdlib-browser/cjs/types/lib.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..28642c78d2fb4a234df06188d07a53d92d302293 --- /dev/null +++ b/node_modules/node-stdlib-browser/cjs/types/lib.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"lib.d.ts","sourceRoot":"","sources":["../../types/lib.ts"],"names":[],"mappings":";AAAA,OAAO,QAAQ,iBAAiB,CAAC;IAChC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;IAC/D,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;CAC5C;AAED,OAAO,QAAQ,oBAAoB,CAAC;IACnC,MAAM,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC;IAC9B,SAAS,OAAO,CAAC;CACjB"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/index.d.ts b/node_modules/node-stdlib-browser/esm/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..608db0a6b8f4666be727e6e8b4edbe55f889a2ce --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/index.d.ts @@ -0,0 +1,170 @@ +declare const _default: { + "node:assert": string; + "node:buffer": string; + "node:child_process": string; + "node:cluster": string; + "node:console": string; + "node:constants": string; + "node:crypto": string; + "node:dgram": string; + "node:dns": string; + "node:domain": string; + "node:events": string; + "node:fs": string; + "node:http": string; + "node:https": string; + "node:http2": string; + "node:module": string; + "node:net": string; + "node:os": string; + "node:path": string; + "node:punycode": string; + "node:process": string; + "node:querystring": string; + "node:readline": string; + "node:repl": string; + "node:stream": string; + "node:_stream_duplex": string; + "node:_stream_passthrough": string; + "node:_stream_readable": string; + "node:_stream_transform": string; + "node:_stream_writable": string; + "node:string_decoder": string; + "node:sys": string; + "node:timers/promises": string; + "node:timers": string; + "node:tls": string; + "node:tty": string; + "node:url": string; + "node:util": string; + "node:vm": string; + "node:zlib": string; + assert: string; + buffer: string; + child_process: string; + cluster: string; + console: string; + constants: string; + crypto: string; + dgram: string; + dns: string; + domain: string; + events: string; + fs: string; + http: string; + https: string; + http2: string; + module: string; + net: string; + os: string; + path: string; + punycode: string; + process: string; + querystring: string; + readline: string; + repl: string; + stream: string; + _stream_duplex: string; + _stream_passthrough: string; + _stream_readable: string; + _stream_transform: string; + _stream_writable: string; + string_decoder: string; + sys: string; + 'timers/promises': string; + timers: string; + tls: string; + tty: string; + url: string; + util: string; + vm: string; + zlib: string; +}; +export default _default; +export type Packages = typeof packages; +export type PackageNames = keyof Packages; +export type NodeProtocolPackages = { + "node:assert": string; + "node:buffer": string; + "node:child_process": string; + "node:cluster": string; + "node:console": string; + "node:constants": string; + "node:crypto": string; + "node:dgram": string; + "node:dns": string; + "node:domain": string; + "node:events": string; + "node:fs": string; + "node:http": string; + "node:https": string; + "node:http2": string; + "node:module": string; + "node:net": string; + "node:os": string; + "node:path": string; + "node:punycode": string; + "node:process": string; + "node:querystring": string; + "node:readline": string; + "node:repl": string; + "node:stream": string; + "node:_stream_duplex": string; + "node:_stream_passthrough": string; + "node:_stream_readable": string; + "node:_stream_transform": string; + "node:_stream_writable": string; + "node:string_decoder": string; + "node:sys": string; + "node:timers/promises": string; + "node:timers": string; + "node:tls": string; + "node:tty": string; + "node:url": string; + "node:util": string; + "node:vm": string; + "node:zlib": string; +}; +declare const packages: { + assert: string; + buffer: string; + child_process: string; + cluster: string; + console: string; + constants: string; + crypto: string; + dgram: string; + dns: string; + domain: string; + events: string; + fs: string; + http: string; + https: string; + http2: string; + module: string; + net: string; + os: string; + path: string; + punycode: string; + process: string; + querystring: string; + readline: string; + repl: string; + stream: string; + _stream_duplex: string; + _stream_passthrough: string; + _stream_readable: string; + _stream_transform: string; + _stream_writable: string; + string_decoder: string; + sys: string; + 'timers/promises': string; + timers: string; + tls: string; + tty: string; + url: string; + util: string; + vm: string; + zlib: string; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/index.d.ts.map b/node_modules/node-stdlib-browser/esm/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..91c567327bd05477a50b162bb0e7c4f552739c82 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBA8Gc,eAAe;2BACf,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA5C5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyCE"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/index.js b/node_modules/node-stdlib-browser/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..744e1f0ec2350dae8b2f4c3e470608e5bee6f565 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/index.js @@ -0,0 +1,140 @@ +import createRequire from 'create-require'; +import pkgDir from 'pkg-dir'; + +var _globalThis = function (Object) { + function get() { + var _global = this || self; + delete Object.prototype.__magic__; + return _global; + } + if (typeof globalThis === "object") { + return globalThis; + } + if (this) { + return get(); + } else { + Object.defineProperty(Object.prototype, "__magic__", { + configurable: true, + get: get + }); + var _global = __magic__; + return _global; + } +}(Object); + +/** + * @param {string} path + */ +const resolvePath = path => { + let resolvedPath; + try { + resolvedPath = require.resolve(path); + } catch { + var _globalThis$require; + resolvedPath = ((_globalThis$require = _globalThis.require) != null ? _globalThis$require : createRequire(import.meta.url)).resolve(path); + } + if (!path.includes('./')) { + var _pkgDir$sync; + const directory = (_pkgDir$sync = pkgDir.sync(resolvedPath)) != null ? _pkgDir$sync : ''; + return directory; + } + return resolvedPath; +}; +const assert = resolvePath('assert/'); +const buffer = resolvePath('buffer/'); +const child_process = resolvePath('./mock/empty.js'); +const cluster = resolvePath('./mock/empty.js'); +const _console = resolvePath('console-browserify'); +const constants = resolvePath('constants-browserify'); +const crypto = resolvePath('crypto-browserify'); +const dgram = resolvePath('./mock/empty.js'); +const dns = resolvePath('./mock/empty.js'); +const domain = resolvePath('domain-browser'); +const events = resolvePath('events/'); +const fs = resolvePath('./mock/empty.js'); +const http = resolvePath('stream-http'); +const https = resolvePath('https-browserify'); +const http2 = resolvePath('./mock/empty.js'); +const _module = resolvePath('./mock/empty.js'); +const net = resolvePath('./mock/empty.js'); +const os = resolvePath('os-browserify/browser.js'); +const path = resolvePath('path-browserify'); +const punycode = resolvePath('punycode/'); +const _process = resolvePath('./proxy/process').replace('.js', ''); +const querystring = resolvePath('./proxy/querystring.js'); +const readline = resolvePath('./mock/empty.js'); +const repl = resolvePath('./mock/empty.js'); +const stream = resolvePath('stream-browserify'); +const _stream_duplex = resolvePath('readable-stream/lib/_stream_duplex.js'); +const _stream_passthrough = resolvePath('readable-stream/lib/_stream_passthrough.js'); +const _stream_readable = resolvePath('readable-stream/lib/_stream_readable.js'); +const _stream_transform = resolvePath('readable-stream/lib/_stream_transform.js'); +const _stream_writable = resolvePath('readable-stream/lib/_stream_writable.js'); +const string_decoder = resolvePath('string_decoder/'); +const sys = resolvePath('util/util.js'); +const timers = resolvePath('timers-browserify'); +const timersPromises = resolvePath('isomorphic-timers-promises'); +const tls = resolvePath('./mock/empty.js'); +const tty = resolvePath('tty-browserify'); +const url = resolvePath('./proxy/url.js'); +const util = resolvePath('util/util.js'); +const vm = resolvePath('vm-browserify'); +const zlib = resolvePath('browserify-zlib'); +const packages = { + assert, + buffer, + child_process, + cluster, + console: _console, + constants, + crypto, + dgram, + dns, + domain, + events, + fs, + http, + https, + http2, + module: _module, + net, + os, + path, + punycode, + process: _process, + querystring, + readline, + repl, + stream, + _stream_duplex, + _stream_passthrough, + _stream_readable, + _stream_transform, + _stream_writable, + string_decoder, + sys, + 'timers/promises': timersPromises, + timers, + tls, + tty, + url, + util, + vm, + zlib +}; + +/** @typedef {typeof packages} Packages */ +/** @typedef {keyof Packages} PackageNames */ +/** @typedef {{ [Property in PackageNames as `node:${Property}`]: Packages[Property] }} NodeProtocolPackages */ + +const packagesWithNodeProtocol = /** @type NodeProtocolPackages */{}; +for (const [packageName, packagePath] of Object.entries(packages)) { + packagesWithNodeProtocol[`node:${(/** @type PackageNames */packageName)}`] = /** @type PackageNames */packagePath; +} +var index = { + ...packages, + ...packagesWithNodeProtocol +}; + +export { index as default }; +//# sourceMappingURL=index.js.map diff --git a/node_modules/node-stdlib-browser/esm/index.js.map b/node_modules/node-stdlib-browser/esm/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..705d76601e629f55a6857497cf3942aa154d7ea2 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../index.js"],"sourcesContent":["import createRequire from 'create-require';\nimport pkgDir from 'pkg-dir';\n\n/**\n * @param {string} path\n */\nconst resolvePath = (path) => {\n\tlet resolvedPath;\n\ttry {\n\t\tresolvedPath = require.resolve(path);\n\t} catch {\n\t\tresolvedPath = (\n\t\t\tglobalThis.require ?? createRequire(import.meta.url)\n\t\t).resolve(path);\n\t}\n\tif (!path.includes('./')) {\n\t\tconst directory = pkgDir.sync(resolvedPath) ?? '';\n\t\treturn directory;\n\t}\n\treturn resolvedPath;\n};\n\nconst assert = resolvePath('assert/');\nconst buffer = resolvePath('buffer/');\nconst child_process = resolvePath('./mock/empty.js');\nconst cluster = resolvePath('./mock/empty.js');\nconst _console = resolvePath('console-browserify');\nconst constants = resolvePath('constants-browserify');\nconst crypto = resolvePath('crypto-browserify');\nconst dgram = resolvePath('./mock/empty.js');\nconst dns = resolvePath('./mock/empty.js');\nconst domain = resolvePath('domain-browser');\nconst events = resolvePath('events/');\nconst fs = resolvePath('./mock/empty.js');\nconst http = resolvePath('stream-http');\nconst https = resolvePath('https-browserify');\nconst http2 = resolvePath('./mock/empty.js');\nconst _module = resolvePath('./mock/empty.js');\nconst net = resolvePath('./mock/empty.js');\nconst os = resolvePath('os-browserify/browser.js');\nconst path = resolvePath('path-browserify');\nconst punycode = resolvePath('punycode/');\nconst _process = resolvePath('./proxy/process').replace('.js', '');\nconst querystring = resolvePath('./proxy/querystring.js');\nconst readline = resolvePath('./mock/empty.js');\nconst repl = resolvePath('./mock/empty.js');\nconst stream = resolvePath('stream-browserify');\nconst _stream_duplex = resolvePath('readable-stream/lib/_stream_duplex.js');\nconst _stream_passthrough = resolvePath(\n\t'readable-stream/lib/_stream_passthrough.js'\n);\nconst _stream_readable = resolvePath('readable-stream/lib/_stream_readable.js');\nconst _stream_transform = resolvePath(\n\t'readable-stream/lib/_stream_transform.js'\n);\nconst _stream_writable = resolvePath('readable-stream/lib/_stream_writable.js');\nconst string_decoder = resolvePath('string_decoder/');\nconst sys = resolvePath('util/util.js');\nconst timers = resolvePath('timers-browserify');\nconst timersPromises = resolvePath('isomorphic-timers-promises');\nconst tls = resolvePath('./mock/empty.js');\nconst tty = resolvePath('tty-browserify');\nconst url = resolvePath('./proxy/url.js');\nconst util = resolvePath('util/util.js');\nconst vm = resolvePath('vm-browserify');\nconst zlib = resolvePath('browserify-zlib');\n\nconst packages = {\n\tassert,\n\tbuffer,\n\tchild_process,\n\tcluster,\n\tconsole: _console,\n\tconstants,\n\tcrypto,\n\tdgram,\n\tdns,\n\tdomain,\n\tevents,\n\tfs,\n\thttp,\n\thttps,\n\thttp2,\n\tmodule: _module,\n\tnet,\n\tos,\n\tpath,\n\tpunycode,\n\tprocess: _process,\n\tquerystring,\n\treadline,\n\trepl,\n\tstream,\n\t_stream_duplex,\n\t_stream_passthrough,\n\t_stream_readable,\n\t_stream_transform,\n\t_stream_writable,\n\tstring_decoder,\n\tsys,\n\t'timers/promises': timersPromises,\n\ttimers,\n\ttls,\n\ttty,\n\turl,\n\tutil,\n\tvm,\n\tzlib\n};\n\n/** @typedef {typeof packages} Packages */\n/** @typedef {keyof Packages} PackageNames */\n/** @typedef {{ [Property in PackageNames as `node:${Property}`]: Packages[Property] }} NodeProtocolPackages */\n\nconst packagesWithNodeProtocol = /** @type NodeProtocolPackages */ ({});\nfor (const [packageName, packagePath] of Object.entries(packages)) {\n\tpackagesWithNodeProtocol[\n\t\t`node:${/** @type PackageNames */ (packageName)}`\n\t] = /** @type PackageNames */ packagePath;\n}\n\nexport default {\n\t...packages,\n\t...packagesWithNodeProtocol\n};\n"],"names":["resolvePath","path","resolvedPath","require","resolve","_globalThis$require","_globalThis","createRequire","import","meta","url","includes","_pkgDir$sync","directory","pkgDir","sync","assert","buffer","child_process","cluster","_console","constants","crypto","dgram","dns","domain","events","fs","http","https","http2","_module","net","os","punycode","_process","replace","querystring","readline","repl","stream","_stream_duplex","_stream_passthrough","_stream_readable","_stream_transform","_stream_writable","string_decoder","sys","timers","timersPromises","tls","tty","util","vm","zlib","packages","console","module","process","packagesWithNodeProtocol","packageName","packagePath","Object","entries"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAGA;AACA;AACA;AACA,MAAMA,WAAW,GAAIC,IAAI,IAAK;AAC7B,EAAA,IAAIC,YAAY,CAAA;EAChB,IAAI;AACHA,IAAAA,YAAY,GAAGC,OAAO,CAACC,OAAO,CAACH,IAAI,CAAC,CAAA;AACrC,GAAC,CAAC,MAAM;AAAA,IAAA,IAAAI,mBAAA,CAAA;IACPH,YAAY,GAAG,EAAAG,mBAAA,GACdC,WAAA,CAAWH,OAAO,KAAAE,IAAAA,GAAAA,mBAAA,GAAIE,aAAa,CAACC,MAAM,CAACC,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CAAC,EAAE;EAClEI,wBAAwB,CACvB,kCAAmCC,WAAW,GAAG,CACjD,4BAA6BC,WAAW,CAAA;AAC1C,CAAA;AAEA,YAAe;AACd,EAAA,GAAGN,QAAQ;EACX,GAAGI,wBAAAA;AACJ,CAAC;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/buffer.d.ts b/node_modules/node-stdlib-browser/esm/mock/buffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..35342fc09b28dc7f6a24f64a89714b5be06c4114 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/buffer.d.ts @@ -0,0 +1,7 @@ +export const INSPECT_MAX_BYTES: 50; +export function Buffer(): void; +export namespace Buffer { + function isBuffer(): boolean; +} +export { Buffer as SlowBuffer }; +//# sourceMappingURL=buffer.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/buffer.d.ts.map b/node_modules/node-stdlib-browser/esm/mock/buffer.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..67d3a4b2a51fca145339bed8eda4945944d0afed --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/buffer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer.d.ts","sourceRoot":"","sources":["../../mock/buffer.js"],"names":[],"mappings":"AAOA,mCAA6B;AAP7B,+BAEC;;IACD,6BAEC"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/buffer.js b/node_modules/node-stdlib-browser/esm/mock/buffer.js new file mode 100644 index 0000000000000000000000000000000000000000..3549c3564df35bfdad8c127b319d097d702f9d75 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/buffer.js @@ -0,0 +1,10 @@ +function Buffer() { + throw new Error('Buffer is not included.'); +} +Buffer.isBuffer = function () { + return false; +}; +var INSPECT_MAX_BYTES = 50; + +export { Buffer, INSPECT_MAX_BYTES, Buffer as SlowBuffer }; +//# sourceMappingURL=buffer.js.map diff --git a/node_modules/node-stdlib-browser/esm/mock/buffer.js.map b/node_modules/node-stdlib-browser/esm/mock/buffer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..19196f4721058cec138257fc0cc73cb4429e5907 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/buffer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer.js","sources":["../../mock/buffer.js"],"sourcesContent":["function Buffer() {\n\tthrow new Error('Buffer is not included.');\n}\nBuffer.isBuffer = function () {\n\treturn false;\n};\n\nconst INSPECT_MAX_BYTES = 50;\n\nexport { INSPECT_MAX_BYTES, Buffer as SlowBuffer, Buffer };\n"],"names":["Buffer","Error","isBuffer","INSPECT_MAX_BYTES"],"mappings":"AAAA,SAASA,MAAMA,GAAG;AACjB,EAAA,MAAM,IAAIC,KAAK,CAAC,yBAAyB,CAAC,CAAA;AAC3C,CAAA;AACAD,MAAM,CAACE,QAAQ,GAAG,YAAY;AAC7B,EAAA,OAAO,KAAK,CAAA;AACb,CAAC,CAAA;AAEKC,IAAAA,iBAAiB,GAAG;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/console.d.ts b/node_modules/node-stdlib-browser/esm/mock/console.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..94757578e36b7845e721f3b0d1a689568289540b --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/console.d.ts @@ -0,0 +1,14 @@ +export default _console; +export type ConsoleApi = keyof { + log: number; + info: number; + error: number; + warn: number; + dir: number; + trace: number; + assert: number; + time: number; + timeEnd: number; +}; +declare const _console: Console; +//# sourceMappingURL=console.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/console.d.ts.map b/node_modules/node-stdlib-browser/esm/mock/console.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..da89c58ba05bb1f9f31ecef5d2fdbdde3ff9af1e --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/console.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"console.d.ts","sourceRoot":"","sources":["../../mock/console.js"],"names":[],"mappings":";yBAcc;;;;;;;;;;CAAgB;AAd9B,gCAA0C"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/console.js b/node_modules/node-stdlib-browser/esm/mock/console.js new file mode 100644 index 0000000000000000000000000000000000000000..fb79e8679b154cba0d40de58b835701835423bfe --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/console.js @@ -0,0 +1,44 @@ +var _globalThis$console; +var _globalThis = function (Object) { + function get() { + var _global = this || self; + delete Object.prototype.__magic__; + return _global; + } + if (typeof globalThis === "object") { + return globalThis; + } + if (this) { + return get(); + } else { + Object.defineProperty(Object.prototype, "__magic__", { + configurable: true, + get: get + }); + var _global = __magic__; + return _global; + } +}(Object); +var _console = (_globalThis$console = _globalThis.console) != null ? _globalThis$console : {}; +var consoleApi = { + log: 1, + info: 1, + error: 1, + warn: 1, + dir: 1, + trace: 1, + assert: 1, + time: 1, + timeEnd: 1 +}; + +/** @typedef {keyof consoleApi} ConsoleApi */ + +for (var property in consoleApi) { + if (!_console[(/** @type {ConsoleApi} */property)]) { + _console[(/** @type {ConsoleApi} */property)] = function () {}; + } +} + +export { _console as default }; +//# sourceMappingURL=console.js.map diff --git a/node_modules/node-stdlib-browser/esm/mock/console.js.map b/node_modules/node-stdlib-browser/esm/mock/console.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4e3502756d8859242275f1598895b1f7b8deaa74 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/console.js.map @@ -0,0 +1 @@ +{"version":3,"file":"console.js","sources":["../../mock/console.js"],"sourcesContent":["const _console = globalThis.console ?? {};\n\nconst consoleApi = {\n\tlog: 1,\n\tinfo: 1,\n\terror: 1,\n\twarn: 1,\n\tdir: 1,\n\ttrace: 1,\n\tassert: 1,\n\ttime: 1,\n\ttimeEnd: 1\n};\n\n/** @typedef {keyof consoleApi} ConsoleApi */\n\nfor (const property in consoleApi) {\n\tif (!_console[/** @type {ConsoleApi} */ (property)]) {\n\t\t_console[/** @type {ConsoleApi} */ (property)] = function () {};\n\t}\n}\n\nexport default _console;\n"],"names":["_console","_globalThis$console","_globalThis","console","consoleApi","log","info","error","warn","dir","trace","assert","time","timeEnd","property"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAMA,IAAAA,QAAQ,GAAAC,CAAAA,mBAAA,GAAGC,WAAA,CAAWC,OAAO,KAAAF,IAAAA,GAAAA,mBAAA,GAAI,GAAE;AAEzC,IAAMG,UAAU,GAAG;AAClBC,EAAAA,GAAG,EAAE,CAAC;AACNC,EAAAA,IAAI,EAAE,CAAC;AACPC,EAAAA,KAAK,EAAE,CAAC;AACRC,EAAAA,IAAI,EAAE,CAAC;AACPC,EAAAA,GAAG,EAAE,CAAC;AACNC,EAAAA,KAAK,EAAE,CAAC;AACRC,EAAAA,MAAM,EAAE,CAAC;AACTC,EAAAA,IAAI,EAAE,CAAC;AACPC,EAAAA,OAAO,EAAE,CAAA;AACV,CAAC,CAAA;;AAED;;AAEA,KAAK,IAAMC,QAAQ,IAAIV,UAAU,EAAE;AAClC,EAAA,IAAI,CAACJ,QAAQ,2BAA4Bc,QAAQ,EAAE,EAAE;AACpDd,IAAAA,QAAQ,2BAA4Bc,QAAQ,EAAE,GAAG,YAAY,EAAE,CAAA;AAChE,GAAA;AACD;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/dns.d.ts b/node_modules/node-stdlib-browser/esm/mock/dns.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ace59d7ae728339233c1a9fca7a89b90bfbbb97 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/dns.d.ts @@ -0,0 +1,6 @@ +/** + * @param {unknown[]} arguments_ + */ +declare function api(...arguments_: unknown[]): void; +export { api as lookup, api as resolve4, api as resolve6, api as resolveCname, api as resolveMx, api as resolveNs, api as resolveTxt, api as resolveSrv, api as resolveNaptr, api as reverse, api as resolve }; +//# sourceMappingURL=dns.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/dns.d.ts.map b/node_modules/node-stdlib-browser/esm/mock/dns.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..a51b76c719f05114729ba7c027d2d2912583eba1 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/dns.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dns.d.ts","sourceRoot":"","sources":["../../mock/dns.js"],"names":[],"mappings":"AAEA;;GAEG;AACH,oCAFW,OAAO,EAAE,QAUnB"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/dns.js b/node_modules/node-stdlib-browser/esm/mock/dns.js new file mode 100644 index 0000000000000000000000000000000000000000..389a9053926cedbf5c11ced1b01ee6a8daa3d6c8 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/dns.js @@ -0,0 +1,18 @@ +/* globals unknown */ + +/** + * @param {unknown[]} arguments_ + */ +var api = function api() { + var _ref; + if (arguments.length === 0) { + return; + } + var callback = (_ref = arguments.length - 1, _ref < 0 || arguments.length <= _ref ? undefined : arguments[_ref]); + if (typeof callback === 'function') { + callback(null, '0.0.0.0'); + } +}; + +export { api as lookup, api as resolve, api as resolve4, api as resolve6, api as resolveCname, api as resolveMx, api as resolveNaptr, api as resolveNs, api as resolveSrv, api as resolveTxt, api as reverse }; +//# sourceMappingURL=dns.js.map diff --git a/node_modules/node-stdlib-browser/esm/mock/dns.js.map b/node_modules/node-stdlib-browser/esm/mock/dns.js.map new file mode 100644 index 0000000000000000000000000000000000000000..971d5866294594572d67219477e3b5f5959902c5 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/dns.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dns.js","sources":["../../mock/dns.js"],"sourcesContent":["/* globals unknown */\n\n/**\n * @param {unknown[]} arguments_\n */\nconst api = function (...arguments_) {\n\tif (arguments_.length === 0) {\n\t\treturn;\n\t}\n\tconst callback = arguments_[arguments_.length - 1];\n\tif (typeof callback === 'function') {\n\t\tcallback(null, '0.0.0.0');\n\t}\n};\n\nexport {\n\tapi as lookup,\n\tapi as resolve4,\n\tapi as resolve6,\n\tapi as resolveCname,\n\tapi as resolveMx,\n\tapi as resolveNs,\n\tapi as resolveTxt,\n\tapi as resolveSrv,\n\tapi as resolveNaptr,\n\tapi as reverse,\n\tapi as resolve\n};\n"],"names":["api","_ref","arguments","length","callback","undefined"],"mappings":"AAAA;;AAEA;AACA;AACA;AACA,IAAMA,GAAG,GAAG,SAANA,GAAGA,GAA4B;AAAA,EAAA,IAAAC,IAAA,CAAA;AACpC,EAAA,IAAIC,SAAA,CAAWC,MAAM,KAAK,CAAC,EAAE;AAC5B,IAAA,OAAA;AACD,GAAA;EACA,IAAMC,QAAQ,IAAAH,IAAA,GAAcC,SAAA,CAAWC,MAAM,GAAG,CAAC,EAAAF,IAAA,QAAAC,SAAA,CAAAC,MAAA,IAAAF,IAAA,GAAAI,SAAA,GAAAH,SAAA,CAAAD,IAAA,CAAC,CAAA,CAAA;AAClD,EAAA,IAAI,OAAOG,QAAQ,KAAK,UAAU,EAAE;AACnCA,IAAAA,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;AAC1B,GAAA;AACD;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/empty.d.ts b/node_modules/node-stdlib-browser/esm/mock/empty.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..67b676d9ef871765c3878764215c9274d78a1e69 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/empty.d.ts @@ -0,0 +1,3 @@ +declare const _default: null; +export default _default; +//# sourceMappingURL=empty.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/empty.d.ts.map b/node_modules/node-stdlib-browser/esm/mock/empty.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..e355de3984d5f6872f525cedef7163049da14475 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/empty.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"empty.d.ts","sourceRoot":"","sources":["../../mock/empty.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/empty.js b/node_modules/node-stdlib-browser/esm/mock/empty.js new file mode 100644 index 0000000000000000000000000000000000000000..4bf4979f7243cc41967383d6d53a638b9c2d12b7 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/empty.js @@ -0,0 +1,4 @@ +var empty = null; + +export { empty as default }; +//# sourceMappingURL=empty.js.map diff --git a/node_modules/node-stdlib-browser/esm/mock/empty.js.map b/node_modules/node-stdlib-browser/esm/mock/empty.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1c4a0af6e75de026c347cd046d86b97c051fcfa4 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/empty.js.map @@ -0,0 +1 @@ +{"version":3,"file":"empty.js","sources":["../../mock/empty.js"],"sourcesContent":["export default null;\n"],"names":[],"mappings":"AAAA,YAAe,IAAI;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/net.d.ts b/node_modules/node-stdlib-browser/esm/mock/net.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..457f8879af60e14c17c4b730f9f1bd638abe826e --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/net.d.ts @@ -0,0 +1,4 @@ +declare function noop(): void; +declare function bool(): boolean; +export { noop as createServer, noop as createConnection, noop as connect, bool as isIP, bool as isIPv4, bool as isIPv6 }; +//# sourceMappingURL=net.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/net.d.ts.map b/node_modules/node-stdlib-browser/esm/mock/net.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..c770b3f7d3af86623dffe9e7308939efb12d4336 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/net.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"net.d.ts","sourceRoot":"","sources":["../../mock/net.js"],"names":[],"mappings":"AAAA,8BAAkB;AAClB,iCAEC"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/net.js b/node_modules/node-stdlib-browser/esm/mock/net.js new file mode 100644 index 0000000000000000000000000000000000000000..f3f4406c207893a94dbe95486937b34cf3d3b0dc --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/net.js @@ -0,0 +1,7 @@ +function noop() {} +function bool() { + return true; +} + +export { noop as connect, noop as createConnection, noop as createServer, bool as isIP, bool as isIPv4, bool as isIPv6 }; +//# sourceMappingURL=net.js.map diff --git a/node_modules/node-stdlib-browser/esm/mock/net.js.map b/node_modules/node-stdlib-browser/esm/mock/net.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad454fbbe311d0a1b7c709207b26bf16a44f97f4 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/net.js.map @@ -0,0 +1 @@ +{"version":3,"file":"net.js","sources":["../../mock/net.js"],"sourcesContent":["function noop() {}\nfunction bool() {\n\treturn true;\n}\n\nexport {\n\tnoop as createServer,\n\tnoop as createConnection,\n\tnoop as connect,\n\tbool as isIP,\n\tbool as isIPv4,\n\tbool as isIPv6\n};\n"],"names":["noop","bool"],"mappings":"AAAA,SAASA,IAAIA,GAAG,EAAC;AACjB,SAASC,IAAIA,GAAG;AACf,EAAA,OAAO,IAAI,CAAA;AACZ;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/process.d.ts b/node_modules/node-stdlib-browser/esm/mock/process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6c2521fe1798b8af275463a324bd54a05f2fb871 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/process.d.ts @@ -0,0 +1,23 @@ +export const features: {}; +/** + * @param {unknown[]} arguments_ + */ +export function nextTick(...arguments_: unknown[]): void; +export const pid: 1; +export const browser: true; +declare const environment: {}; +/** @type {string[]} */ +export const argv: string[]; +/** + * @param {unknown} name + */ +export function binding(name: unknown): void; +declare function getCwd(): string; +/** + * @param {string} dir + */ +declare function getChdir(dir: string): void; +declare function noop(): void; +declare const platformName: "browser"; +export { environment as env, getCwd as cwd, getChdir as chdir, noop as exit, noop as kill, noop as umask, noop as dlopen, noop as uptime, noop as memoryUsage, noop as uvCounters, platformName as platform, platformName as arch, platformName as execPath, platformName as title }; +//# sourceMappingURL=process.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/process.d.ts.map b/node_modules/node-stdlib-browser/esm/mock/process.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..adb32ac7abfb4e5aeb19d3013d6ef2485dfa4c0c --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/process.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"process.d.ts","sourceRoot":"","sources":["../../mock/process.js"],"names":[],"mappings":"AAyBA,0BAAoB;AApBpB;;GAEG;AACH,wCAFW,OAAO,EAAE,QAUnB;AAWD,oBAAc;AACd,2BAAqB;AACrB,8BAAuB;AACvB,uBAAuB;AACvB,mBADW,MAAM,EAAE,CACH;AAbhB;;GAEG;AACH,8BAFW,OAAO,QAIjB;AAWD,kCAEC;AACD;;GAEG;AACH,+BAFW,MAAM,QAIhB;AAtCD,8BAAkB;AAsBlB,sCAA+B"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/process.js b/node_modules/node-stdlib-browser/esm/mock/process.js new file mode 100644 index 0000000000000000000000000000000000000000..c5ccb403b426bfed93c8945b5659eff1593dcbaa --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/process.js @@ -0,0 +1,46 @@ +import path from 'path'; + +/* globals unknown */ +function noop() {} +/** + * @param {unknown[]} arguments_ + */ +function nextTick() { + for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) { + arguments_[_key] = arguments[_key]; + } + var function_ = arguments_[0]; + arguments_.shift(); + setTimeout(function () { + if (typeof function_ === 'function') { + function_.apply(null, arguments_); + } + }, 0); +} + +/** + * @param {unknown} name + */ +function binding(name) { + throw new Error('No such module. (Possibly not yet loaded)'); +} +var features = {}; +var platformName = 'browser'; +var pid = 1; +var browser = true; +var environment = {}; +/** @type {string[]} */ +var argv = []; +var cwd = '/'; +function getCwd() { + return cwd; +} +/** + * @param {string} dir + */ +function getChdir(dir) { + cwd = path.resolve(dir, cwd); +} + +export { platformName as arch, argv, binding, browser, getChdir as chdir, getCwd as cwd, noop as dlopen, environment as env, platformName as execPath, noop as exit, features, noop as kill, noop as memoryUsage, nextTick, pid, platformName as platform, platformName as title, noop as umask, noop as uptime, noop as uvCounters }; +//# sourceMappingURL=process.js.map diff --git a/node_modules/node-stdlib-browser/esm/mock/process.js.map b/node_modules/node-stdlib-browser/esm/mock/process.js.map new file mode 100644 index 0000000000000000000000000000000000000000..afb979cd41eb69dd504065213e0599dbe7b9e5f5 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/process.js.map @@ -0,0 +1 @@ +{"version":3,"file":"process.js","sources":["../../mock/process.js"],"sourcesContent":["/* globals unknown */\n\nimport path from 'path';\n\nfunction noop() {}\n/**\n * @param {unknown[]} arguments_\n */\nfunction nextTick(...arguments_) {\n\tconst [function_] = arguments_;\n\targuments_.shift();\n\tsetTimeout(function () {\n\t\tif (typeof function_ === 'function') {\n\t\t\tfunction_.apply(null, arguments_);\n\t\t}\n\t}, 0);\n}\n\n/**\n * @param {unknown} name\n */\nfunction binding(name) {\n\tthrow new Error('No such module. (Possibly not yet loaded)');\n}\n\nconst features = {};\nconst platformName = 'browser';\nconst pid = 1;\nconst browser = true;\nconst environment = {};\n/** @type {string[]} */\nconst argv = [];\n\nlet cwd = '/';\nfunction getCwd() {\n\treturn cwd;\n}\n/**\n * @param {string} dir\n */\nfunction getChdir(dir) {\n\tcwd = path.resolve(dir, cwd);\n}\n\nexport {\n\tfeatures,\n\tnextTick,\n\tpid,\n\tbrowser,\n\tenvironment as env,\n\targv,\n\tbinding,\n\tgetCwd as cwd,\n\tgetChdir as chdir,\n\tnoop as exit,\n\tnoop as kill,\n\tnoop as umask,\n\tnoop as dlopen,\n\tnoop as uptime,\n\tnoop as memoryUsage,\n\tnoop as uvCounters,\n\tplatformName as platform,\n\tplatformName as arch,\n\tplatformName as execPath,\n\tplatformName as title\n};\n"],"names":["noop","nextTick","_len","arguments","length","arguments_","Array","_key","function_","shift","setTimeout","apply","binding","name","Error","features","platformName","pid","browser","environment","argv","cwd","getCwd","getChdir","dir","path","resolve"],"mappings":";;AAAA;AAIA,SAASA,IAAIA,GAAG,EAAC;AACjB;AACA;AACA;AACA,SAASC,QAAQA,GAAgB;AAAA,EAAA,KAAA,IAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,EAAZC,UAAU,GAAAC,IAAAA,KAAA,CAAAJ,IAAA,GAAAK,IAAA,GAAA,CAAA,EAAAA,IAAA,GAAAL,IAAA,EAAAK,IAAA,EAAA,EAAA;AAAVF,IAAAA,UAAU,CAAAE,IAAA,CAAAJ,GAAAA,SAAA,CAAAI,IAAA,CAAA,CAAA;AAAA,GAAA;EAC9B,IAAOC,SAAS,GAAIH,UAAU,CAAA,CAAA,CAAA,CAAA;EAC9BA,UAAU,CAACI,KAAK,EAAE,CAAA;AAClBC,EAAAA,UAAU,CAAC,YAAY;AACtB,IAAA,IAAI,OAAOF,SAAS,KAAK,UAAU,EAAE;AACpCA,MAAAA,SAAS,CAACG,KAAK,CAAC,IAAI,EAAEN,UAAU,CAAC,CAAA;AAClC,KAAA;GACA,EAAE,CAAC,CAAC,CAAA;AACN,CAAA;;AAEA;AACA;AACA;AACA,SAASO,OAAOA,CAACC,IAAI,EAAE;AACtB,EAAA,MAAM,IAAIC,KAAK,CAAC,2CAA2C,CAAC,CAAA;AAC7D,CAAA;AAEMC,IAAAA,QAAQ,GAAG,GAAE;AACbC,IAAAA,YAAY,GAAG,UAAS;AACxBC,IAAAA,GAAG,GAAG,EAAC;AACPC,IAAAA,OAAO,GAAG,KAAI;AACdC,IAAAA,WAAW,GAAG,GAAE;AACtB;AACMC,IAAAA,IAAI,GAAG,GAAE;AAEf,IAAIC,GAAG,GAAG,GAAG,CAAA;AACb,SAASC,MAAMA,GAAG;AACjB,EAAA,OAAOD,GAAG,CAAA;AACX,CAAA;AACA;AACA;AACA;AACA,SAASE,QAAQA,CAACC,GAAG,EAAE;EACtBH,GAAG,GAAGI,IAAI,CAACC,OAAO,CAACF,GAAG,EAAEH,GAAG,CAAC,CAAA;AAC7B;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/punycode.d.ts b/node_modules/node-stdlib-browser/esm/mock/punycode.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f1cc8d68e2d13b31423595f5cf26cce11251876c --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/punycode.d.ts @@ -0,0 +1,11 @@ +export namespace ucs2 { + export { passthrough as encode }; + export { passthrough as decode }; +} +export const version: "0.0.0"; +/** + * @param {string} s + */ +declare function passthrough(s: string): string; +export { passthrough as encode, passthrough as decode, passthrough as toUnicode, passthrough as toASCII }; +//# sourceMappingURL=punycode.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/punycode.d.ts.map b/node_modules/node-stdlib-browser/esm/mock/punycode.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..b27e1ad2d7f56daf13905462ec2535d7a2306e3e --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/punycode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"punycode.d.ts","sourceRoot":"","sources":["../../mock/punycode.js"],"names":[],"mappings":";;;;AAYA,8BAAwB;AAZxB;;GAEG;AACH,gCAFW,MAAM,UAIhB"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/punycode.js b/node_modules/node-stdlib-browser/esm/mock/punycode.js new file mode 100644 index 0000000000000000000000000000000000000000..7f6aaa0d89a58253ddac7ef223d354d739855d4c --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/punycode.js @@ -0,0 +1,14 @@ +/** + * @param {string} s + */ +function passthrough(s) { + return s; +} +var ucs2 = { + encode: passthrough, + decode: passthrough +}; +var version = '0.0.0'; + +export { passthrough as decode, passthrough as encode, passthrough as toASCII, passthrough as toUnicode, ucs2, version }; +//# sourceMappingURL=punycode.js.map diff --git a/node_modules/node-stdlib-browser/esm/mock/punycode.js.map b/node_modules/node-stdlib-browser/esm/mock/punycode.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d58927bfe98fa20d41ba0b05448c193851e9244c --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/punycode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"punycode.js","sources":["../../mock/punycode.js"],"sourcesContent":["/**\n * @param {string} s\n */\nfunction passthrough(s) {\n\treturn s;\n}\n\nconst ucs2 = {\n\tencode: passthrough,\n\tdecode: passthrough\n};\n\nconst version = '0.0.0';\n\nexport {\n\tucs2,\n\tversion,\n\tpassthrough as encode,\n\tpassthrough as decode,\n\tpassthrough as toUnicode,\n\tpassthrough as toASCII\n};\n"],"names":["passthrough","s","ucs2","encode","decode","version"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,WAAWA,CAACC,CAAC,EAAE;AACvB,EAAA,OAAOA,CAAC,CAAA;AACT,CAAA;AAEA,IAAMC,IAAI,GAAG;AACZC,EAAAA,MAAM,EAAEH,WAAW;AACnBI,EAAAA,MAAM,EAAEJ,WAAAA;AACT,EAAC;AAEKK,IAAAA,OAAO,GAAG;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/tls.d.ts b/node_modules/node-stdlib-browser/esm/mock/tls.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ae7ac26fa5eb2f55f71d25fc1ecbec88ab0d4548 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/tls.d.ts @@ -0,0 +1 @@ +//# sourceMappingURL=tls.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/tls.d.ts.map b/node_modules/node-stdlib-browser/esm/mock/tls.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..05deb1ffb20824b389971585f1b261136a7464d7 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/tls.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tls.d.ts","sourceRoot":"","sources":["../../mock/tls.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/tls.js b/node_modules/node-stdlib-browser/esm/mock/tls.js new file mode 100644 index 0000000000000000000000000000000000000000..136f73756da6e987af1f1bba5760c668cbb8c3ce --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/tls.js @@ -0,0 +1,2 @@ + +//# sourceMappingURL=tls.js.map diff --git a/node_modules/node-stdlib-browser/esm/mock/tls.js.map b/node_modules/node-stdlib-browser/esm/mock/tls.js.map new file mode 100644 index 0000000000000000000000000000000000000000..df9eb3b6897159229ac7005e78167105b6f052f8 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/tls.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tls.js","sources":[],"sourcesContent":[],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/tty.d.ts b/node_modules/node-stdlib-browser/esm/mock/tty.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9bcb95422fe1b61d43b8d6a5f796f232e90640b6 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/tty.d.ts @@ -0,0 +1,3 @@ +declare function noop(): void; +export { noop as isatty, noop as setRawMode }; +//# sourceMappingURL=tty.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/tty.d.ts.map b/node_modules/node-stdlib-browser/esm/mock/tty.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..394e6afc25216ac770a25e32a635aed9406a5585 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/tty.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tty.d.ts","sourceRoot":"","sources":["../../mock/tty.js"],"names":[],"mappings":"AAAA,8BAAkB"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/mock/tty.js b/node_modules/node-stdlib-browser/esm/mock/tty.js new file mode 100644 index 0000000000000000000000000000000000000000..8419780513191c1faa230d55f2d68e9c6391fa74 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/tty.js @@ -0,0 +1,4 @@ +function noop() {} + +export { noop as isatty, noop as setRawMode }; +//# sourceMappingURL=tty.js.map diff --git a/node_modules/node-stdlib-browser/esm/mock/tty.js.map b/node_modules/node-stdlib-browser/esm/mock/tty.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6022bcd6707fe6b416d07620824ae65be0fe8afa --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/mock/tty.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tty.js","sources":["../../mock/tty.js"],"sourcesContent":["function noop() {}\n\nexport { noop as isatty, noop as setRawMode };\n"],"names":["noop"],"mappings":"AAAA,SAASA,IAAIA,GAAG;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/package.json b/node_modules/node-stdlib-browser/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7c34deb5837d8d5e168b54f95f7872b2c50eca13 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/package.json @@ -0,0 +1 @@ +{"type":"module"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/proxy/process.d.ts b/node_modules/node-stdlib-browser/esm/proxy/process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e7c91582c4e3c1cb3c490de10afc87a93524ab2 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/process.d.ts @@ -0,0 +1,73 @@ +export default api; +declare namespace api { + export { nextTick }; + export { title }; + export { browser }; + export { environment as env }; + export { argv }; + export { version }; + export { versions }; + export { on }; + export { addListener }; + export { once }; + export { off }; + export { removeListener }; + export { removeAllListeners }; + export { emit }; + export { emitWarning }; + export { prependListener }; + export { prependOnceListener }; + export { listeners }; + export { binding }; + export { cwd }; + export { chdir }; + export { umask }; + export { exit }; + export { pid }; + export { features }; + export { kill }; + export { dlopen }; + export { uptime }; + export { memoryUsage }; + export { uvCounters }; + export { platform }; + export { arch }; + export { execPath }; + export { execArgv }; +} +import { nextTick } from "node/process"; +import { title } from "node/process"; +export const browser: boolean; +import { env as environment } from "node/process"; +import { argv } from "node/process"; +import { version } from "node/process"; +import { versions } from "node/process"; +import { on } from "node/process"; +import { addListener } from "node/process"; +import { once } from "node/process"; +import { off } from "node/events"; +import { removeListener } from "node/events"; +import { removeAllListeners } from "node/events"; +import { emit } from "node/process"; +export function emitWarning(): void; +import { prependListener } from "node/process"; +import { prependOnceListener } from "node/process"; +import { listeners } from "node/process"; +export const binding: Function; +import { cwd } from "node/process"; +import { chdir } from "node/process"; +import { umask } from "node/process"; +export function exit(): void; +export const pid: 1; +export const features: {}; +export function kill(): void; +export function dlopen(): void; +export function uptime(): void; +export function memoryUsage(): void; +export function uvCounters(): void; +export const platform: "browser"; +export const arch: "browser"; +export const execPath: "browser"; +export const execArgv: string[]; +export { nextTick, title, environment as env, argv, version, versions, on, addListener, once, off, removeListener, removeAllListeners, emit, prependListener, prependOnceListener, listeners, cwd, chdir, umask }; +//# sourceMappingURL=process.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/proxy/process.d.ts.map b/node_modules/node-stdlib-browser/esm/proxy/process.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..dfe4b4a478cf2f6b7e18e104c560258093aca4f0 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/process.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"process.d.ts","sourceRoot":"","sources":["../../proxy/process.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,8BAAkD;;;;;;;;;;;;AAFlD,oCAAkB;;;;AAIlB,+BAAmD;;;;AAJnD,6BAAkB;AAMlB,oBAAc;AACd,0BAAoB;AAPpB,6BAAkB;AAAlB,+BAAkB;AAAlB,+BAAkB;AAAlB,oCAAkB;AAAlB,mCAAkB;AAalB,iCAA2B;AAC3B,6BAAuB;AACvB,iCAA2B;AAC3B,gCAA8C"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/proxy/process.js b/node_modules/node-stdlib-browser/esm/proxy/process.js new file mode 100644 index 0000000000000000000000000000000000000000..03193a22ae00acf8da5c5edcbdf05845ec2b40da --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/process.js @@ -0,0 +1,261 @@ +var browser$1 = {exports: {}}; + +// shim for using process in browser +var process = browser$1.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()); +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop$1() {} + +process.on = noop$1; +process.addListener = noop$1; +process.once = noop$1; +process.off = noop$1; +process.removeListener = noop$1; +process.removeAllListeners = noop$1; +process.emit = noop$1; +process.prependListener = noop$1; +process.prependOnceListener = noop$1; + +process.listeners = function (name) { return [] }; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +function noop() {} +var browser = /** @type {boolean} */browser$1.exports.browser; +var emitWarning = noop; +var binding = /** @type {Function} */browser$1.exports.binding; +var exit = noop; +var pid = 1; +var features = {}; +var kill = noop; +var dlopen = noop; +var uptime = noop; +var memoryUsage = noop; +var uvCounters = noop; +var platform = 'browser'; +var arch = 'browser'; +var execPath = 'browser'; +var execArgv = /** @type {string[]} */[]; +var api = { + nextTick: browser$1.exports.nextTick, + title: browser$1.exports.title, + browser: browser, + env: browser$1.exports.env, + argv: browser$1.exports.argv, + version: browser$1.exports.version, + versions: browser$1.exports.versions, + on: browser$1.exports.on, + addListener: browser$1.exports.addListener, + once: browser$1.exports.once, + off: browser$1.exports.off, + removeListener: browser$1.exports.removeListener, + removeAllListeners: browser$1.exports.removeAllListeners, + emit: browser$1.exports.emit, + emitWarning: emitWarning, + prependListener: browser$1.exports.prependListener, + prependOnceListener: browser$1.exports.prependOnceListener, + listeners: browser$1.exports.listeners, + binding: binding, + cwd: browser$1.exports.cwd, + chdir: browser$1.exports.chdir, + umask: browser$1.exports.umask, + exit: exit, + pid: pid, + features: features, + kill: kill, + dlopen: dlopen, + uptime: uptime, + memoryUsage: memoryUsage, + uvCounters: uvCounters, + platform: platform, + arch: arch, + execPath: execPath, + execArgv: execArgv +}; + +var addListener = browser$1.exports.addListener; +var argv = browser$1.exports.argv; +var chdir = browser$1.exports.chdir; +var cwd = browser$1.exports.cwd; +var emit = browser$1.exports.emit; +var env = browser$1.exports.env; +var listeners = browser$1.exports.listeners; +var nextTick = browser$1.exports.nextTick; +var off = browser$1.exports.off; +var on = browser$1.exports.on; +var once = browser$1.exports.once; +var prependListener = browser$1.exports.prependListener; +var prependOnceListener = browser$1.exports.prependOnceListener; +var removeAllListeners = browser$1.exports.removeAllListeners; +var removeListener = browser$1.exports.removeListener; +var title = browser$1.exports.title; +var umask = browser$1.exports.umask; +var version = browser$1.exports.version; +var versions = browser$1.exports.versions; +export { addListener, arch, argv, binding, browser, chdir, cwd, api as default, dlopen, emit, emitWarning, env, execArgv, execPath, exit, features, kill, listeners, memoryUsage, nextTick, off, on, once, pid, platform, prependListener, prependOnceListener, removeAllListeners, removeListener, title, umask, uptime, uvCounters, version, versions }; +//# sourceMappingURL=process.js.map diff --git a/node_modules/node-stdlib-browser/esm/proxy/process.js.map b/node_modules/node-stdlib-browser/esm/proxy/process.js.map new file mode 100644 index 0000000000000000000000000000000000000000..92315b37210efac386cabcdd0f7bd35c82d388df --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/process.js.map @@ -0,0 +1 @@ +{"version":3,"file":"process.js","sources":["../../node_modules/process/browser.js","../../proxy/process.js"],"sourcesContent":["// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import {\n\tnextTick,\n\ttitle,\n\tenv as environment,\n\targv,\n\tversion,\n\tversions,\n\ton,\n\taddListener,\n\tonce,\n\toff,\n\tremoveListener,\n\tremoveAllListeners,\n\temit,\n\tprependListener,\n\tprependOnceListener,\n\tlisteners,\n\tcwd,\n\tchdir,\n\tumask,\n\t// @ts-ignore\n\tbrowser as _browser,\n\t// @ts-ignore\n\tbinding as _binding\n} from 'process/browser.js';\n\nfunction noop() {}\n\nconst browser = /** @type {boolean} */ (_browser);\nconst emitWarning = noop;\nconst binding = /** @type {Function} */ (_binding);\nconst exit = noop;\nconst pid = 1;\nconst features = {};\nconst kill = noop;\nconst dlopen = noop;\nconst uptime = noop;\nconst memoryUsage = noop;\nconst uvCounters = noop;\nconst platform = 'browser';\nconst arch = 'browser';\nconst execPath = 'browser';\nconst execArgv = /** @type {string[]} */ ([]);\n\nconst api = {\n\tnextTick,\n\ttitle,\n\tbrowser,\n\tenv: environment,\n\targv,\n\tversion,\n\tversions,\n\ton,\n\taddListener,\n\tonce,\n\toff,\n\tremoveListener,\n\tremoveAllListeners,\n\temit,\n\temitWarning,\n\tprependListener,\n\tprependOnceListener,\n\tlisteners,\n\tbinding,\n\tcwd,\n\tchdir,\n\tumask,\n\texit,\n\tpid,\n\tfeatures,\n\tkill,\n\tdlopen,\n\tuptime,\n\tmemoryUsage,\n\tuvCounters,\n\tplatform,\n\tarch,\n\texecPath,\n\texecArgv\n};\n\nexport default api;\n\nexport {\n\tnextTick,\n\ttitle,\n\tbrowser,\n\tenvironment as env,\n\targv,\n\tversion,\n\tversions,\n\ton,\n\taddListener,\n\tonce,\n\toff,\n\tremoveListener,\n\tremoveAllListeners,\n\temit,\n\temitWarning,\n\tprependListener,\n\tprependOnceListener,\n\tlisteners,\n\tbinding,\n\tcwd,\n\tchdir,\n\tumask,\n\texit,\n\tpid,\n\tfeatures,\n\tkill,\n\tdlopen,\n\tuptime,\n\tmemoryUsage,\n\tuvCounters,\n\tplatform,\n\tarch,\n\texecPath,\n\texecArgv\n};\n"],"names":["browserModule","noop","browser","_browser","emitWarning","binding","_binding","exit","pid","features","kill","dlopen","uptime","memoryUsage","uvCounters","platform","arch","execPath","execArgv","api","nextTick","title","env","environment","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","cwd","chdir","umask"],"mappings":";;AAAA;AACA,IAAI,OAAO,GAAGA,SAAc,CAAA,OAAA,GAAG,EAAE,CAAC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,gBAAgB,CAAC;AACrB,IAAI,kBAAkB,CAAC;AACvB;AACA,SAAS,gBAAgB,GAAG;AAC5B,IAAI,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;AACvD,CA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b/node_modules/node-stdlib-browser/esm/proxy/process/browser.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..045aaede6ce3bcf090a6921ba61ccb8273a234c3 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/process/browser.d.ts @@ -0,0 +1,4 @@ +export default api; +export * from "../process.js"; +import api from "../process.js"; +//# sourceMappingURL=browser.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/proxy/process/browser.d.ts.map b/node_modules/node-stdlib-browser/esm/proxy/process/browser.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..0b79217798a33310d839008e9900b74aa1d2ebca --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/process/browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../../../proxy/process/browser.js"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/proxy/process/browser.js b/node_modules/node-stdlib-browser/esm/proxy/process/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..5b4f69bc860893e5721ce2ce47536428e9767e6c --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/process/browser.js @@ -0,0 +1,261 @@ +var browser$1 = {exports: {}}; + +// shim for using process in browser +var process = browser$1.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()); +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop$1() {} + +process.on = noop$1; +process.addListener = noop$1; +process.once = noop$1; +process.off = noop$1; +process.removeListener = noop$1; +process.removeAllListeners = noop$1; +process.emit = noop$1; +process.prependListener = noop$1; +process.prependOnceListener = noop$1; + +process.listeners = function (name) { return [] }; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +function noop() {} +var browser = /** @type {boolean} */browser$1.exports.browser; +var emitWarning = noop; +var binding = /** @type {Function} */browser$1.exports.binding; +var exit = noop; +var pid = 1; +var features = {}; +var kill = noop; +var dlopen = noop; +var uptime = noop; +var memoryUsage = noop; +var uvCounters = noop; +var platform = 'browser'; +var arch = 'browser'; +var execPath = 'browser'; +var execArgv = /** @type {string[]} */[]; +var api = { + nextTick: browser$1.exports.nextTick, + title: browser$1.exports.title, + browser: browser, + env: browser$1.exports.env, + argv: browser$1.exports.argv, + version: browser$1.exports.version, + versions: browser$1.exports.versions, + on: browser$1.exports.on, + addListener: browser$1.exports.addListener, + once: browser$1.exports.once, + off: browser$1.exports.off, + removeListener: browser$1.exports.removeListener, + removeAllListeners: browser$1.exports.removeAllListeners, + emit: browser$1.exports.emit, + emitWarning: emitWarning, + prependListener: browser$1.exports.prependListener, + prependOnceListener: browser$1.exports.prependOnceListener, + listeners: browser$1.exports.listeners, + binding: binding, + cwd: browser$1.exports.cwd, + chdir: browser$1.exports.chdir, + umask: browser$1.exports.umask, + exit: exit, + pid: pid, + features: features, + kill: kill, + dlopen: dlopen, + uptime: uptime, + memoryUsage: memoryUsage, + uvCounters: uvCounters, + platform: platform, + arch: arch, + execPath: execPath, + execArgv: execArgv +}; + +var addListener = browser$1.exports.addListener; +var argv = browser$1.exports.argv; +var chdir = browser$1.exports.chdir; +var cwd = browser$1.exports.cwd; +var emit = browser$1.exports.emit; +var env = browser$1.exports.env; +var listeners = browser$1.exports.listeners; +var nextTick = browser$1.exports.nextTick; +var off = browser$1.exports.off; +var on = browser$1.exports.on; +var once = browser$1.exports.once; +var prependListener = browser$1.exports.prependListener; +var prependOnceListener = browser$1.exports.prependOnceListener; +var removeAllListeners = browser$1.exports.removeAllListeners; +var removeListener = browser$1.exports.removeListener; +var title = browser$1.exports.title; +var umask = browser$1.exports.umask; +var version = browser$1.exports.version; +var versions = browser$1.exports.versions; +export { addListener, arch, argv, binding, browser, chdir, cwd, api as default, dlopen, emit, emitWarning, env, execArgv, execPath, exit, features, kill, listeners, memoryUsage, nextTick, off, on, once, pid, platform, prependListener, prependOnceListener, removeAllListeners, removeListener, title, umask, uptime, uvCounters, version, versions }; +//# sourceMappingURL=browser.js.map diff --git a/node_modules/node-stdlib-browser/esm/proxy/process/browser.js.map b/node_modules/node-stdlib-browser/esm/proxy/process/browser.js.map new file mode 100644 index 0000000000000000000000000000000000000000..042f445053a6ba9085e870408fa0634a76d74a48 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/process/browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"browser.js","sources":["../../../node_modules/process/browser.js","../../../proxy/process.js"],"sourcesContent":["// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import {\n\tnextTick,\n\ttitle,\n\tenv as environment,\n\targv,\n\tversion,\n\tversions,\n\ton,\n\taddListener,\n\tonce,\n\toff,\n\tremoveListener,\n\tremoveAllListeners,\n\temit,\n\tprependListener,\n\tprependOnceListener,\n\tlisteners,\n\tcwd,\n\tchdir,\n\tumask,\n\t// @ts-ignore\n\tbrowser as _browser,\n\t// @ts-ignore\n\tbinding as _binding\n} from 'process/browser.js';\n\nfunction noop() {}\n\nconst browser = /** @type {boolean} */ (_browser);\nconst emitWarning = noop;\nconst binding = /** @type {Function} */ (_binding);\nconst exit = noop;\nconst pid = 1;\nconst features = {};\nconst kill = noop;\nconst dlopen = noop;\nconst uptime = noop;\nconst memoryUsage = noop;\nconst uvCounters = noop;\nconst platform = 'browser';\nconst arch = 'browser';\nconst execPath = 'browser';\nconst execArgv = /** @type {string[]} */ ([]);\n\nconst api = {\n\tnextTick,\n\ttitle,\n\tbrowser,\n\tenv: environment,\n\targv,\n\tversion,\n\tversions,\n\ton,\n\taddListener,\n\tonce,\n\toff,\n\tremoveListener,\n\tremoveAllListeners,\n\temit,\n\temitWarning,\n\tprependListener,\n\tprependOnceListener,\n\tlisteners,\n\tbinding,\n\tcwd,\n\tchdir,\n\tumask,\n\texit,\n\tpid,\n\tfeatures,\n\tkill,\n\tdlopen,\n\tuptime,\n\tmemoryUsage,\n\tuvCounters,\n\tplatform,\n\tarch,\n\texecPath,\n\texecArgv\n};\n\nexport default api;\n\nexport {\n\tnextTick,\n\ttitle,\n\tbrowser,\n\tenvironment as env,\n\targv,\n\tversion,\n\tversions,\n\ton,\n\taddListener,\n\tonce,\n\toff,\n\tremoveListener,\n\tremoveAllListeners,\n\temit,\n\temitWarning,\n\tprependListener,\n\tprependOnceListener,\n\tlisteners,\n\tbinding,\n\tcwd,\n\tchdir,\n\tumask,\n\texit,\n\tpid,\n\tfeatures,\n\tkill,\n\tdlopen,\n\tuptime,\n\tmemoryUsage,\n\tuvCounters,\n\tplatform,\n\tarch,\n\texecPath,\n\texecArgv\n};\n"],"names":["browserModule","noop","browser","_browser","emitWarning","binding","_binding","exit","pid","features","kill","dlopen","uptime","memoryUsage","uvCounters","platform","arch","execPath","execArgv","api","nextTick","title","env","environment","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","cwd","chdir","umask"],"mappings":";;AAAA;AACA,IAAI,OAAO,GAAGA,SAAc,CAAA,OAAA,GAAG,EAAE,CAAC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,gBAAgB,CAAC;AACrB,IAAI,kBAAkB,CAAC;AACvB;AACA,SAAS,gBAAgB,GAAG;AAC5B,IAAI,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;AACvD,CAAC;AACD,SAAS,mBAAmB,IAAI;AAChC,IAAI,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;AACzD,CAAC;AACD,CAAC,YAAY;AACb,IAAI,IAAI;AACR,QAAQ,IAAI,OAAO,UAAU,KAAK,UAAU,EAAE;AAC9C,YAAY,gBAAgB,GAAG,UAAU,CAAC;AAC1C,SAAS,MAAM;AACf,YAAY,gBAAgB,GAAG,gBAAgB,CAAC;AAChD,SAAS;AACT,KAAK,CAAC,OAAO,CAAC,EAAE;AAChB,QAAQ,gBAAgB,GAAG,gBAAgB,CAAC;AAC5C,KAAK;AACL,IAAI,IAAI;AACR,QAAQ,IAAI,OAAO,YAAY,KAAK,UAAU,EAAE;AAChD,YAAY,kBAAkB,GAAG,YAAY,CAAC;AAC9C,SAAS,MAAM;AACf,YAAY,kBAAkB,GAAG,mBAAmB,CAAC;AACrD,SAAS;AACT,KAAK,CAAC,OAAO,CAAC,EAAE;AAChB,QAAQ,kBAAkB,GAAG,mBAAmB,CAAC;AACjD,KAAK;AACL,CAAC,GAAG,EAAC;AACL,SAAS,UAAU,CAAC,GAAG,EAAE;AACzB,IAAI,IAAI,gBAAgB,KAAK,UAAU,EAAE;AACzC;AACA,Q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AAAA,IAAI,EAAJA,IAAI;AACJC,EAAAA,GAAG,EAAHA,GAAG;AACHC,EAAAA,QAAQ,EAARA,QAAQ;AACRC,EAAAA,IAAI,EAAJA,IAAI;AACJC,EAAAA,MAAM,EAANA,MAAM;AACNC,EAAAA,MAAM,EAANA,MAAM;AACNC,EAAAA,WAAW,EAAXA,WAAW;AACXC,EAAAA,UAAU,EAAVA,UAAU;AACVC,EAAAA,QAAQ,EAARA,QAAQ;AACRC,EAAAA,IAAI,EAAJA,IAAI;AACJC,EAAAA,QAAQ,EAARA,QAAQ;AACRC,EAAAA,QAAQ,EAARA,QAAAA;AACD;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/proxy/querystring.d.ts b/node_modules/node-stdlib-browser/esm/proxy/querystring.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d1db762d2cb168b1696de2e8bae35faf28da9b3 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/querystring.d.ts @@ -0,0 +1,21 @@ +/// +/// +export default api; +export type qsEscape = typeof import("querystring").escape; +export type qsUnescape = typeof import("querystring").unescape; +declare namespace api { + export { decode }; + export { encode }; + export { parse }; + export { stringify }; + export { qsEscape as escape }; + export { qsUnescape as unescape }; +} +import { decode } from "querystring-es3"; +import { encode } from "querystring-es3"; +import { parse } from "querystring-es3"; +import { stringify } from "querystring-es3"; +declare function qsEscape(str: string): string; +declare function qsUnescape(str: string): string; +export { decode, encode, parse, stringify, qsEscape as escape, qsUnescape as unescape }; +//# sourceMappingURL=querystring.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/proxy/querystring.d.ts.map b/node_modules/node-stdlib-browser/esm/proxy/querystring.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..551d6e1f7397f5cb9e8facd03c9c339c3dcf07c4 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/querystring.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"querystring.d.ts","sourceRoot":"","sources":["../../proxy/querystring.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAwCm+I,+CAAslB;AAAA,iDAA+wB"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/proxy/querystring.js b/node_modules/node-stdlib-browser/esm/proxy/querystring.js new file mode 100644 index 0000000000000000000000000000000000000000..6490efef85cbdc4d12ceb8969c3b33c70757d88d --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/querystring.js @@ -0,0 +1,32 @@ +import { decode, encode, parse, stringify } from 'querystring-es3'; +export { decode, encode, parse, stringify } from 'querystring-es3'; + +/** + * @typedef {import('querystring').escape} qsEscape + * @typedef {import('querystring').unescape} qsUnescape + */ + +/** + * @type {qsEscape} + */ +function qsEscape(string) { + return encodeURIComponent(string); +} + +/** + * @type {qsUnescape} + */ +function qsUnescape(string) { + return decodeURIComponent(string); +} +var api = { + decode: decode, + encode: encode, + parse: parse, + stringify: stringify, + escape: qsEscape, + unescape: qsUnescape +}; + +export { api as default, qsEscape as escape, qsUnescape as unescape }; +//# sourceMappingURL=querystring.js.map diff --git a/node_modules/node-stdlib-browser/esm/proxy/querystring.js.map b/node_modules/node-stdlib-browser/esm/proxy/querystring.js.map new file mode 100644 index 0000000000000000000000000000000000000000..27d5be06620a013e5b4060f15e30afa16c981de0 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/querystring.js.map @@ -0,0 +1 @@ +{"version":3,"file":"querystring.js","sources":["../../proxy/querystring.js"],"sourcesContent":["/**\n * @typedef {import('querystring').escape} qsEscape\n * @typedef {import('querystring').unescape} qsUnescape\n */\n\nimport { decode, encode, parse, stringify } from 'querystring-es3';\n\n/**\n * @type {qsEscape}\n */\nfunction qsEscape(string) {\n\treturn encodeURIComponent(string);\n}\n\n/**\n * @type {qsUnescape}\n */\nfunction qsUnescape(string) {\n\treturn decodeURIComponent(string);\n}\n\nconst api = {\n\tdecode,\n\tencode,\n\tparse,\n\tstringify,\n\tescape: qsEscape,\n\tunescape: qsUnescape\n};\n\nexport default api;\n\nexport {\n\tdecode,\n\tencode,\n\tparse,\n\tstringify,\n\tqsEscape as escape,\n\tqsUnescape as unescape\n};\n"],"names":["qsEscape","string","encodeURIComponent","qsUnescape","decodeURIComponent","api","decode","encode","parse","stringify","escape","unescape"],"mappings":";;;AAAA;AACA;AACA;AACA;;AAIA;AACA;AACA;AACA,SAASA,QAAQA,CAACC,MAAM,EAAE;EACzB,OAAOC,kBAAkB,CAACD,MAAM,CAAC,CAAA;AAClC,CAAA;;AAEA;AACA;AACA;AACA,SAASE,UAAUA,CAACF,MAAM,EAAE;EAC3B,OAAOG,kBAAkB,CAACH,MAAM,CAAC,CAAA;AAClC,CAAA;AAEA,IAAMI,GAAG,GAAG;AACXC,EAAAA,MAAM,EAANA,MAAM;AACNC,EAAAA,MAAM,EAANA,MAAM;AACNC,EAAAA,KAAK,EAALA,KAAK;AACLC,EAAAA,SAAS,EAATA,SAAS;AACTC,EAAAA,MAAM,EAAEV,QAAQ;AAChBW,EAAAA,QAAQ,EAAER,UAAAA;AACX;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/proxy/url.d.ts b/node_modules/node-stdlib-browser/esm/proxy/url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5df2d7d49d48c352ef62218761a19c96188ed1b7 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/url.d.ts @@ -0,0 +1,50 @@ +/// +export default api; +export type domainToASCII = typeof import("url").domainToASCII; +export type domainToUnicode = typeof import("url").domainToUnicode; +export type pathToFileURL = typeof import("url").pathToFileURL; +export type fileURLToPath = typeof import("url").fileURLToPath; +export type URLFormatOptions = import('url').URLFormatOptions; +export type UrlObject = import('url').UrlObject; +export type formatImport = typeof format; +export type parseImport = typeof parse; +export type resolveImport = typeof resolve; +export type UrlImport = import('url').Url; +declare namespace api { + export { formatImportWithOverloads as format }; + export { parseImport as parse }; + export { resolveImport as resolve }; + export { resolveObject }; + export { UrlImport as Url }; + export { URL }; + export { URLSearchParams }; + export { domainToASCII }; + export { domainToUnicode }; + export { pathToFileURL }; + export { fileURLToPath }; +} +declare const formatImportWithOverloads: ((urlObject: URL, options?: URLFormatOptions) => string) & ((urlObject: UrlObject | string, options?: never) => string); +declare const parseImport: typeof parse; +declare const resolveImport: typeof resolve; +declare const UrlImport: Url; +export const URL: { + new (url: string | URL, base?: string | URL | undefined): URL; + prototype: URL; + createObjectURL(obj: Blob | MediaSource): string; + revokeObjectURL(url: string): void; +}; +export const URLSearchParams: { + new (init?: string | URLSearchParams | string[][] | Record | undefined): URLSearchParams; + prototype: URLSearchParams; + toString(): string; +}; +export const domainToASCII: domainToASCII; +export const domainToUnicode: domainToUnicode; +export const pathToFileURL: (url: string) => URL; +export const fileURLToPath: typeof import("url").fileURLToPath & ((path: string | URL) => string); +import { format } from "url"; +import { parse } from "url"; +import { resolve } from "url"; +import { Url } from "url"; +export { formatImportWithOverloads as format, parseImport as parse, resolveImport as resolve, resolveObject, UrlImport as Url }; +//# sourceMappingURL=url.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/proxy/url.d.ts.map b/node_modules/node-stdlib-browser/esm/proxy/url.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..36c8f7806bf35955b16426fd2caa98bd8a161c59 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/url.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"url.d.ts","sourceRoot":"","sources":["../../proxy/url.js"],"names":[],"mappings":";;;;;;+BAGa,OAAO,KAAK,EAAE,gBAAgB;wBAC9B,OAAO,KAAK,EAAE,SAAS;;;;wBAIvB,OAAO,KAAK,EAAE,GAAG;;;;;;;;;;;;;;AA2I9B,sDAGmB,GAAG,YAAY,gBAAgB,KAAK,MAAM,iBAC1C,SAAS,GAAG,MAAM,YAAY,KAAK,KAAK,MAAM,EAuC9D;AA1KH,wCAAsD;AACtD,4CAA4D;AAE5D,6BAAgD;AAEhD;;;;;EAA2B;AAE3B;;;;EAAmD;AA+DnD,4BAEW,aAAa,CAOrB;AAEH,8BAEW,eAAe,CAOvB;AAEH,kCAEiB,MAAM,KAAK,GAAG,CAc5B;AAEH,yEAEmC,MAAM,GAAG,GAAG,KAAK,MAAM,EAavD"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/proxy/url.js b/node_modules/node-stdlib-browser/esm/proxy/url.js new file mode 100644 index 0000000000000000000000000000000000000000..3c06d61cb18f51710585b5d52cbe4b0d4efea102 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/url.js @@ -0,0 +1,1050 @@ +import require$$0 from 'punycode/'; +import require$$1 from 'qs'; + +/* + * Copyright Joyent, Inc. and other Node contributors. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to permit + * persons to whom the Software is furnished to do so, subject to the + * following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + * USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +var punycode = require$$0; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +/* + * define these here so at least they only have to be + * compiled once on the first module load. + */ +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/, + + /* + * RFC 2396: characters reserved for delimiting URLs. + * We actually just auto-escape these. + */ + delims = [ + '<', '>', '"', '`', ' ', '\r', '\n', '\t' + ], + + // RFC 2396: characters not allowed for various reasons. + unwise = [ + '{', '}', '|', '\\', '^', '`' + ].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + /* + * Characters that are never ever allowed in a hostname. + * Note that any invalid chars are also handled, but these + * are the ones that are *expected* to be seen, so we fast-path + * them. + */ + nonHostChars = [ + '%', '/', '?', ';', '#' + ].concat(autoEscape), + hostEndingChars = [ + '/', '?', '#' + ], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + javascript: true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + javascript: true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + http: true, + https: true, + ftp: true, + gopher: true, + file: true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require$$1; + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && typeof url === 'object' && url instanceof Url) { return url; } + + var u = new Url(); + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) { + if (typeof url !== 'string') { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + /* + * Copy chrome, IE, opera backslash-handling behavior. + * Back slashes before the query string get converted to forward slashes + * See: https://code.google.com/p/chromium/issues/detail?id=25916 + */ + var queryIndex = url.indexOf('?'), + splitter = queryIndex !== -1 && queryIndex < url.indexOf('#') ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + /* + * trim before proceeding. + * This is to support parse stuff like " http://foo.com \n" + */ + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + /* + * figure out if it's got a host + * user@server is *always* interpreted as a hostname, and url + * resolution will treat //foo/bar as host=foo,path=bar because that's + * how the browser resolves relative URLs. + */ + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@/]+@[^@/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { + + /* + * there's a hostname. + * the first instance of /, ?, ;, or # ends the host. + * + * If there is an @ in the hostname, then non-host chars *are* allowed + * to the left of the last @ sign, unless some host-ending character + * comes *before* the @-sign. + * URLs are obnoxious. + * + * ex: + * http://a@b@c/ => user:a@b host:c + * http://a@b?@c => user:a host:c path:/?@c + */ + + /* + * v0.12 TODO(isaacs): This is not quite how Chrome does things. + * Review our test case against browsers more comprehensively. + */ + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; } + } + + /* + * at this point, either we have an explicit point where the + * auth portion cannot go past, or the last @ char is the decider. + */ + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + /* + * atSign must be in auth portion. + * http://a@b/c@d => host:b auth:a path:/c@d + */ + atSign = rest.lastIndexOf('@', hostEnd); + } + + /* + * Now we have a portion which is definitely the auth. + * Pull that off. + */ + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; } + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) { hostEnd = rest.length; } + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + /* + * we've indicated that there is a hostname, + * so even if it's empty, it has to be present. + */ + this.hostname = this.hostname || ''; + + /* + * if hostname begins with [ and ends with ] + * assume that it's an IPv6 address. + */ + var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) { continue; } + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + /* + * we replace non-ASCII char with a temporary placeholder + * we need this to make sure size of hostname is not + * broken by replacing non-ASCII by nothing + */ + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + /* + * IDNA Support: Returns a punycoded representation of "domain". + * It only converts parts of the domain name that + * have non-ASCII characters, i.e. it doesn't matter if + * you call it with a domain that already is ASCII-only. + */ + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + /* + * strip [ and ] from the hostname + * the host field still retains them, though + */ + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + /* + * now rest is set to the post-host stuff. + * chop off any delim chars. + */ + if (!unsafeProtocol[lowerProto]) { + + /* + * First, make 100% sure that any "autoEscape" chars get + * escaped, even if encodeURIComponent doesn't think they + * need to be. + */ + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) { continue; } + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) { this.pathname = rest; } + if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { + this.pathname = '/'; + } + + // to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + /* + * ensure it's an object, and not a string url. + * If it's an obj, this is a no-op. + * this way, you can call url_format() on strings + * to clean up potentially wonky urls. + */ + if (typeof obj === 'string') { obj = urlParse(obj); } + if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); } + return obj.format(); +} + +Url.prototype.format = function () { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && typeof this.query === 'object' && Object.keys(this.query).length) { + query = querystring.stringify(this.query, { + arrayFormat: 'repeat', + addQueryPrefix: false + }); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; } + + /* + * only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + * unless they had them to begin with. + */ + if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; } + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; } + if (search && search.charAt(0) !== '?') { search = '?' + search; } + + pathname = pathname.replace(/[?#]/g, function (match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function (relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) { return relative; } + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function (relative) { + if (typeof relative === 'string') { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + /* + * hash is always overridden, no matter what. + * even href="" will remove it. + */ + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') { result[rkey] = relative[rkey]; } + } + + // urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { + result.pathname = '/'; + result.path = result.pathname; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + /* + * if it's a known url protocol, then changing + * the protocol does weird things + * first, if it's not file:, then we MUST have a host, + * and if there was a path + * to begin with, then we MUST have a path. + * if it is file:, then the host is dropped, + * because that's known to be hostless. + * anything else is assumed to be absolute. + */ + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())) { } + if (!relative.host) { relative.host = ''; } + if (!relative.hostname) { relative.hostname = ''; } + if (relPath[0] !== '') { relPath.unshift(''); } + if (relPath.length < 2) { relPath.unshift(''); } + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = result.pathname && result.pathname.charAt(0) === '/', + isRelAbs = relative.host || relative.pathname && relative.pathname.charAt(0) === '/', + mustEndAbs = isRelAbs || isSourceAbs || (result.host && relative.pathname), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + /* + * if the url is a non-slashed url, then relative + * links like ../.. should be able + * to crawl up to the hostname, as well. This is strange. + * result.protocol has already been set by now. + * Later on, put the first path part into the host field. + */ + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') { srcPath[0] = result.host; } else { srcPath.unshift(result.host); } + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') { relPath[0] = relative.host; } else { relPath.unshift(relative.host); } + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = relative.host || relative.host === '' ? relative.host : result.host; + result.hostname = relative.hostname || relative.hostname === '' ? relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + /* + * it's relative + * throw away the existing file, and take the new path instead. + */ + if (!srcPath) { srcPath = []; } + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (relative.search != null) { + /* + * just pull out the search. + * like href='?foo'. + * Put this after the other two cases because it simplifies the booleans + */ + if (psychotic) { + result.host = srcPath.shift(); + result.hostname = result.host; + /* + * occationaly the auth can get stuck only in host + * this especially happens in cases like + * url.resolveObject('mailto:local1@domain1', 'local2@domain2') + */ + var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.hostname = authInHost.shift(); + result.host = result.hostname; + } + } + result.search = relative.search; + result.query = relative.query; + // to support http.request + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + /* + * no path at all. easy. + * we've already handled the other stuff above. + */ + result.pathname = null; + // to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + /* + * if a url ENDs in . or .., then it must get a trailing slash. + * however, if it ends in anything else non-slashy, + * then it must NOT get a trailing slash. + */ + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''; + + /* + * strip single dots, resolve double dots to parent dir + * if the path tries to go above the root, `up` ends up > 0 + */ + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; + result.host = result.hostname; + /* + * occationaly the auth can get stuck only in host + * this especially happens in cases like + * url.resolveObject('mailto:local1@domain1', 'local2@domain2') + */ + var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.hostname = authInHost.shift(); + result.host = result.hostname; + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (srcPath.length > 0) { + result.pathname = srcPath.join('/'); + } else { + result.pathname = null; + result.path = null; + } + + // to support request.http + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function () { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) { this.hostname = host; } +}; + +var parse = urlParse; +var resolve$1 = urlResolve; +var resolveObject = urlResolveObject; +var format = urlFormat; + +var Url_1 = Url; + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// path.resolve([from ...], to) +// posix version +function resolve() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : '/'; + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +var _globalThis = function (Object) { + function get() { + var _global = this || self; + delete Object.prototype.__magic__; + return _global; + } + if (typeof globalThis === "object") { + return globalThis; + } + if (this) { + return get(); + } else { + Object.defineProperty(Object.prototype, "__magic__", { + configurable: true, + get: get + }); + var _global = __magic__; + return _global; + } +}(Object); +var formatImport = /** @type {formatImport}*/format; +var parseImport = /** @type {parseImport}*/parse; +var resolveImport = /** @type {resolveImport}*/resolve$1; +// @ts-ignore +var UrlImport = /** @type {UrlImport}*/Url_1; +var URL = _globalThis.URL; +/* eslint-disable-next-line unicorn/prevent-abbreviations */ +var URLSearchParams = _globalThis.URLSearchParams; +var percentRegEx = /%/g; +var backslashRegEx = /\\/g; +var newlineRegEx = /\n/g; +var carriageReturnRegEx = /\r/g; +var tabRegEx = /\t/g; +var CHAR_FORWARD_SLASH = 47; + +/** + * @param {unknown} instance + */ +function isURLInstance(instance) { + var resolved = /** @type {URL|null} */instance != null ? instance : null; + return Boolean(resolved !== null && (resolved == null ? void 0 : resolved.href) && (resolved == null ? void 0 : resolved.origin)); +} + +/** + * @param {URL} url + */ +function getPathFromURLPosix(url) { + if (url.hostname !== '') { + throw new TypeError("File URL host must be \"localhost\" or empty on browser"); + } + var pathname = url.pathname; + for (var n = 0; n < pathname.length; n++) { + if (pathname[n] === '%') { + // @ts-ignore + var third = pathname.codePointAt(n + 2) | 0x20; + if (pathname[n + 1] === '2' && third === 102) { + throw new TypeError('File URL path must not include encoded / characters'); + } + } + } + return decodeURIComponent(pathname); +} + +/** + * @param {string} filepath + */ +function encodePathChars(filepath) { + if (filepath.includes('%')) { + filepath = filepath.replace(percentRegEx, '%25'); + } + if (filepath.includes('\\')) { + filepath = filepath.replace(backslashRegEx, '%5C'); + } + if (filepath.includes('\n')) { + filepath = filepath.replace(newlineRegEx, '%0A'); + } + if (filepath.includes('\r')) { + filepath = filepath.replace(carriageReturnRegEx, '%0D'); + } + if (filepath.includes('\t')) { + filepath = filepath.replace(tabRegEx, '%09'); + } + return filepath; +} +var domainToASCII = +/** + * @type {domainToASCII} + */ +function domainToASCII(domain) { + if (typeof domain === 'undefined') { + throw new TypeError('The "domain" argument must be specified'); + } + return new URL("http://" + domain).hostname; +}; +var domainToUnicode = +/** + * @type {domainToUnicode} + */ +function domainToUnicode(domain) { + if (typeof domain === 'undefined') { + throw new TypeError('The "domain" argument must be specified'); + } + return new URL("http://" + domain).hostname; +}; +var pathToFileURL = +/** + * @type {(url: string) => URL} + */ +function pathToFileURL(filepath) { + var outURL = new URL('file://'); + var resolved = resolve(filepath); + var filePathLast = filepath.charCodeAt(filepath.length - 1); + if (filePathLast === CHAR_FORWARD_SLASH && resolved[resolved.length - 1] !== '/') { + resolved += '/'; + } + outURL.pathname = encodePathChars(resolved); + return outURL; +}; +var fileURLToPath = +/** + * @type {fileURLToPath & ((path: string | URL) => string)} + */ +function fileURLToPath(path) { + if (!isURLInstance(path) && typeof path !== 'string') { + throw new TypeError("The \"path\" argument must be of type string or an instance of URL. Received type " + typeof path + " (" + path + ")"); + } + var resolved = new URL(path); + if (resolved.protocol !== 'file:') { + throw new TypeError('The URL must be of scheme file'); + } + return getPathFromURLPosix(resolved); +}; +var formatImportWithOverloads = +/** + * @type {( + * ((urlObject: URL, options?: URLFormatOptions) => string) & + * ((urlObject: UrlObject | string, options?: never) => string) + * )} + */ +function formatImportWithOverloads(urlObject, options) { + var _options$auth, _options$fragment, _options$search, _options$unicode; + if (options === void 0) { + options = {}; + } + if (!(urlObject instanceof URL)) { + return formatImport(urlObject); + } + if (typeof options !== 'object' || options === null) { + throw new TypeError('The "options" argument must be of type object.'); + } + var auth = (_options$auth = options.auth) != null ? _options$auth : true; + var fragment = (_options$fragment = options.fragment) != null ? _options$fragment : true; + var search = (_options$search = options.search) != null ? _options$search : true; + (_options$unicode = options.unicode) != null ? _options$unicode : false; + var parsed = new URL(urlObject.toString()); + if (!auth) { + parsed.username = ''; + parsed.password = ''; + } + if (!fragment) { + parsed.hash = ''; + } + if (!search) { + parsed.search = ''; + } + return parsed.toString(); +}; +var api = { + format: formatImportWithOverloads, + parse: parseImport, + resolve: resolveImport, + resolveObject: resolveObject, + Url: UrlImport, + URL: URL, + URLSearchParams: URLSearchParams, + domainToASCII: domainToASCII, + domainToUnicode: domainToUnicode, + pathToFileURL: pathToFileURL, + fileURLToPath: fileURLToPath +}; + +export { URL, URLSearchParams, UrlImport as Url, api as default, domainToASCII, domainToUnicode, fileURLToPath, formatImportWithOverloads as format, parseImport as parse, pathToFileURL, resolveImport as resolve, resolveObject }; +//# sourceMappingURL=url.js.map diff --git a/node_modules/node-stdlib-browser/esm/proxy/url.js.map b/node_modules/node-stdlib-browser/esm/proxy/url.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8c4656c24f59a1bb5b894545a73aa9b232bbf495 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/proxy/url.js.map @@ -0,0 +1 @@ +{"version":3,"file":"url.js","sources":["../../node_modules/url/url.js","../../node_modules/rollup-plugin-node-builtins/src/es6/path.js","../../proxy/url.js"],"sourcesContent":["/*\n * Copyright Joyent, Inc. and other Node contributors.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to permit\n * persons to whom the Software is furnished to do so, subject to the\n * following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n * USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n'use strict';\n\nvar punycode = require('punycode/');\n\nfunction Url() {\n this.protocol = null;\n this.slashes = null;\n this.auth = null;\n this.host = null;\n this.port = null;\n this.hostname = null;\n this.hash = null;\n this.search = null;\n this.query = null;\n this.pathname = null;\n this.path = null;\n this.href = null;\n}\n\n// Reference: RFC 3986, RFC 1808, RFC 2396\n\n/*\n * define these here so at least they only have to be\n * compiled once on the first module load.\n */\nvar protocolPattern = /^([a-z0-9.+-]+:)/i,\n portPattern = /:[0-9]*$/,\n\n // Special case for a simple path URL\n simplePathPattern = /^(\\/\\/?(?!\\/)[^?\\s]*)(\\?[^\\s]*)?$/,\n\n /*\n * RFC 2396: characters reserved for delimiting URLs.\n * We actually just auto-escape these.\n */\n delims = [\n '<', '>', '\"', '`', ' ', '\\r', '\\n', '\\t'\n ],\n\n // RFC 2396: characters not allowed for various reasons.\n unwise = [\n '{', '}', '|', '\\\\', '^', '`'\n ].concat(delims),\n\n // Allowed by RFCs, but cause of XSS attacks. Always escape these.\n autoEscape = ['\\''].concat(unwise),\n /*\n * Characters that are never ever allowed in a hostname.\n * Note that any invalid chars are also handled, but these\n * are the ones that are *expected* to be seen, so we fast-path\n * them.\n */\n nonHostChars = [\n '%', '/', '?', ';', '#'\n ].concat(autoEscape),\n hostEndingChars = [\n '/', '?', '#'\n ],\n hostnameMaxLen = 255,\n hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,\n hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,\n // protocols that can allow \"unsafe\" and \"unwise\" chars.\n unsafeProtocol = {\n javascript: true,\n 'javascript:': true\n },\n // protocols that never have a hostname.\n hostlessProtocol = {\n javascript: true,\n 'javascript:': true\n },\n // protocols that always contain a // bit.\n slashedProtocol = {\n http: true,\n https: true,\n ftp: true,\n gopher: true,\n file: true,\n 'http:': true,\n 'https:': true,\n 'ftp:': true,\n 'gopher:': true,\n 'file:': true\n },\n querystring = require('qs');\n\nfunction urlParse(url, parseQueryString, slashesDenoteHost) {\n if (url && typeof url === 'object' && url instanceof Url) { return url; }\n\n var u = new Url();\n u.parse(url, parseQueryString, slashesDenoteHost);\n return u;\n}\n\nUrl.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {\n if (typeof url !== 'string') {\n throw new TypeError(\"Parameter 'url' must be a string, not \" + typeof url);\n }\n\n /*\n * Copy chrome, IE, opera backslash-handling behavior.\n * Back slashes before the query string get converted to forward slashes\n * See: https://code.google.com/p/chromium/issues/detail?id=25916\n */\n var queryIndex = url.indexOf('?'),\n splitter = queryIndex !== -1 && queryIndex < url.indexOf('#') ? '?' : '#',\n uSplit = url.split(splitter),\n slashRegex = /\\\\/g;\n uSplit[0] = uSplit[0].replace(slashRegex, '/');\n url = uSplit.join(splitter);\n\n var rest = url;\n\n /*\n * trim before proceeding.\n * This is to support parse stuff like \" http://foo.com \\n\"\n */\n rest = rest.trim();\n\n if (!slashesDenoteHost && url.split('#').length === 1) {\n // Try fast path regexp\n var simplePath = simplePathPattern.exec(rest);\n if (simplePath) {\n this.path = rest;\n this.href = rest;\n this.pathname = simplePath[1];\n if (simplePath[2]) {\n this.search = simplePath[2];\n if (parseQueryString) {\n this.query = querystring.parse(this.search.substr(1));\n } else {\n this.query = this.search.substr(1);\n }\n } else if (parseQueryString) {\n this.search = '';\n this.query = {};\n }\n return this;\n }\n }\n\n var proto = protocolPattern.exec(rest);\n if (proto) {\n proto = proto[0];\n var lowerProto = proto.toLowerCase();\n this.protocol = lowerProto;\n rest = rest.substr(proto.length);\n }\n\n /*\n * figure out if it's got a host\n * user@server is *always* interpreted as a hostname, and url\n * resolution will treat //foo/bar as host=foo,path=bar because that's\n * how the browser resolves relative URLs.\n */\n if (slashesDenoteHost || proto || rest.match(/^\\/\\/[^@/]+@[^@/]+/)) {\n var slashes = rest.substr(0, 2) === '//';\n if (slashes && !(proto && hostlessProtocol[proto])) {\n rest = rest.substr(2);\n this.slashes = true;\n }\n }\n\n if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) {\n\n /*\n * there's a hostname.\n * the first instance of /, ?, ;, or # ends the host.\n *\n * If there is an @ in the hostname, then non-host chars *are* allowed\n * to the left of the last @ sign, unless some host-ending character\n * comes *before* the @-sign.\n * URLs are obnoxious.\n *\n * ex:\n * http://a@b@c/ => user:a@b host:c\n * http://a@b?@c => user:a host:c path:/?@c\n */\n\n /*\n * v0.12 TODO(isaacs): This is not quite how Chrome does things.\n * Review our test case against browsers more comprehensively.\n */\n\n // find the first instance of any hostEndingChars\n var hostEnd = -1;\n for (var i = 0; i < hostEndingChars.length; i++) {\n var hec = rest.indexOf(hostEndingChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; }\n }\n\n /*\n * at this point, either we have an explicit point where the\n * auth portion cannot go past, or the last @ char is the decider.\n */\n var auth, atSign;\n if (hostEnd === -1) {\n // atSign can be anywhere.\n atSign = rest.lastIndexOf('@');\n } else {\n /*\n * atSign must be in auth portion.\n * http://a@b/c@d => host:b auth:a path:/c@d\n */\n atSign = rest.lastIndexOf('@', hostEnd);\n }\n\n /*\n * Now we have a portion which is definitely the auth.\n * Pull that off.\n */\n if (atSign !== -1) {\n auth = rest.slice(0, atSign);\n rest = rest.slice(atSign + 1);\n this.auth = decodeURIComponent(auth);\n }\n\n // the host is the remaining to the left of the first non-host char\n hostEnd = -1;\n for (var i = 0; i < nonHostChars.length; i++) {\n var hec = rest.indexOf(nonHostChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; }\n }\n // if we still have not hit it, then the entire thing is a host.\n if (hostEnd === -1) { hostEnd = rest.length; }\n\n this.host = rest.slice(0, hostEnd);\n rest = rest.slice(hostEnd);\n\n // pull out port.\n this.parseHost();\n\n /*\n * we've indicated that there is a hostname,\n * so even if it's empty, it has to be present.\n */\n this.hostname = this.hostname || '';\n\n /*\n * if hostname begins with [ and ends with ]\n * assume that it's an IPv6 address.\n */\n var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']';\n\n // validate a little.\n if (!ipv6Hostname) {\n var hostparts = this.hostname.split(/\\./);\n for (var i = 0, l = hostparts.length; i < l; i++) {\n var part = hostparts[i];\n if (!part) { continue; }\n if (!part.match(hostnamePartPattern)) {\n var newpart = '';\n for (var j = 0, k = part.length; j < k; j++) {\n if (part.charCodeAt(j) > 127) {\n /*\n * we replace non-ASCII char with a temporary placeholder\n * we need this to make sure size of hostname is not\n * broken by replacing non-ASCII by nothing\n */\n newpart += 'x';\n } else {\n newpart += part[j];\n }\n }\n // we test again with ASCII char only\n if (!newpart.match(hostnamePartPattern)) {\n var validParts = hostparts.slice(0, i);\n var notHost = hostparts.slice(i + 1);\n var bit = part.match(hostnamePartStart);\n if (bit) {\n validParts.push(bit[1]);\n notHost.unshift(bit[2]);\n }\n if (notHost.length) {\n rest = '/' + notHost.join('.') + rest;\n }\n this.hostname = validParts.join('.');\n break;\n }\n }\n }\n }\n\n if (this.hostname.length > hostnameMaxLen) {\n this.hostname = '';\n } else {\n // hostnames are always lower case.\n this.hostname = this.hostname.toLowerCase();\n }\n\n if (!ipv6Hostname) {\n /*\n * IDNA Support: Returns a punycoded representation of \"domain\".\n * It only converts parts of the domain name that\n * have non-ASCII characters, i.e. it doesn't matter if\n * you call it with a domain that already is ASCII-only.\n */\n this.hostname = punycode.toASCII(this.hostname);\n }\n\n var p = this.port ? ':' + this.port : '';\n var h = this.hostname || '';\n this.host = h + p;\n this.href += this.host;\n\n /*\n * strip [ and ] from the hostname\n * the host field still retains them, though\n */\n if (ipv6Hostname) {\n this.hostname = this.hostname.substr(1, this.hostname.length - 2);\n if (rest[0] !== '/') {\n rest = '/' + rest;\n }\n }\n }\n\n /*\n * now rest is set to the post-host stuff.\n * chop off any delim chars.\n */\n if (!unsafeProtocol[lowerProto]) {\n\n /*\n * First, make 100% sure that any \"autoEscape\" chars get\n * escaped, even if encodeURIComponent doesn't think they\n * need to be.\n */\n for (var i = 0, l = autoEscape.length; i < l; i++) {\n var ae = autoEscape[i];\n if (rest.indexOf(ae) === -1) { continue; }\n var esc = encodeURIComponent(ae);\n if (esc === ae) {\n esc = escape(ae);\n }\n rest = rest.split(ae).join(esc);\n }\n }\n\n // chop off from the tail first.\n var hash = rest.indexOf('#');\n if (hash !== -1) {\n // got a fragment string.\n this.hash = rest.substr(hash);\n rest = rest.slice(0, hash);\n }\n var qm = rest.indexOf('?');\n if (qm !== -1) {\n this.search = rest.substr(qm);\n this.query = rest.substr(qm + 1);\n if (parseQueryString) {\n this.query = querystring.parse(this.query);\n }\n rest = rest.slice(0, qm);\n } else if (parseQueryString) {\n // no query string, but parseQueryString still requested\n this.search = '';\n this.query = {};\n }\n if (rest) { this.pathname = rest; }\n if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) {\n this.pathname = '/';\n }\n\n // to support http.request\n if (this.pathname || this.search) {\n var p = this.pathname || '';\n var s = this.search || '';\n this.path = p + s;\n }\n\n // finally, reconstruct the href based on what has been validated.\n this.href = this.format();\n return this;\n};\n\n// format a parsed object into a url string\nfunction urlFormat(obj) {\n /*\n * ensure it's an object, and not a string url.\n * If it's an obj, this is a no-op.\n * this way, you can call url_format() on strings\n * to clean up potentially wonky urls.\n */\n if (typeof obj === 'string') { obj = urlParse(obj); }\n if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); }\n return obj.format();\n}\n\nUrl.prototype.format = function () {\n var auth = this.auth || '';\n if (auth) {\n auth = encodeURIComponent(auth);\n auth = auth.replace(/%3A/i, ':');\n auth += '@';\n }\n\n var protocol = this.protocol || '',\n pathname = this.pathname || '',\n hash = this.hash || '',\n host = false,\n query = '';\n\n if (this.host) {\n host = auth + this.host;\n } else if (this.hostname) {\n host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']');\n if (this.port) {\n host += ':' + this.port;\n }\n }\n\n if (this.query && typeof this.query === 'object' && Object.keys(this.query).length) {\n query = querystring.stringify(this.query, {\n arrayFormat: 'repeat',\n addQueryPrefix: false\n });\n }\n\n var search = this.search || (query && ('?' + query)) || '';\n\n if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; }\n\n /*\n * only the slashedProtocols get the //. Not mailto:, xmpp:, etc.\n * unless they had them to begin with.\n */\n if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) {\n host = '//' + (host || '');\n if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; }\n } else if (!host) {\n host = '';\n }\n\n if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; }\n if (search && search.charAt(0) !== '?') { search = '?' + search; }\n\n pathname = pathname.replace(/[?#]/g, function (match) {\n return encodeURIComponent(match);\n });\n search = search.replace('#', '%23');\n\n return protocol + host + pathname + search + hash;\n};\n\nfunction urlResolve(source, relative) {\n return urlParse(source, false, true).resolve(relative);\n}\n\nUrl.prototype.resolve = function (relative) {\n return this.resolveObject(urlParse(relative, false, true)).format();\n};\n\nfunction urlResolveObject(source, relative) {\n if (!source) { return relative; }\n return urlParse(source, false, true).resolveObject(relative);\n}\n\nUrl.prototype.resolveObject = function (relative) {\n if (typeof relative === 'string') {\n var rel = new Url();\n rel.parse(relative, false, true);\n relative = rel;\n }\n\n var result = new Url();\n var tkeys = Object.keys(this);\n for (var tk = 0; tk < tkeys.length; tk++) {\n var tkey = tkeys[tk];\n result[tkey] = this[tkey];\n }\n\n /*\n * hash is always overridden, no matter what.\n * even href=\"\" will remove it.\n */\n result.hash = relative.hash;\n\n // if the relative url is empty, then there's nothing left to do here.\n if (relative.href === '') {\n result.href = result.format();\n return result;\n }\n\n // hrefs like //foo/bar always cut to the protocol.\n if (relative.slashes && !relative.protocol) {\n // take everything except the protocol from relative\n var rkeys = Object.keys(relative);\n for (var rk = 0; rk < rkeys.length; rk++) {\n var rkey = rkeys[rk];\n if (rkey !== 'protocol') { result[rkey] = relative[rkey]; }\n }\n\n // urlParse appends trailing / to urls like http://www.example.com\n if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) {\n result.pathname = '/';\n result.path = result.pathname;\n }\n\n result.href = result.format();\n return result;\n }\n\n if (relative.protocol && relative.protocol !== result.protocol) {\n /*\n * if it's a known url protocol, then changing\n * the protocol does weird things\n * first, if it's not file:, then we MUST have a host,\n * and if there was a path\n * to begin with, then we MUST have a path.\n * if it is file:, then the host is dropped,\n * because that's known to be hostless.\n * anything else is assumed to be absolute.\n */\n if (!slashedProtocol[relative.protocol]) {\n var keys = Object.keys(relative);\n for (var v = 0; v < keys.length; v++) {\n var k = keys[v];\n result[k] = relative[k];\n }\n result.href = result.format();\n return result;\n }\n\n result.protocol = relative.protocol;\n if (!relative.host && !hostlessProtocol[relative.protocol]) {\n var relPath = (relative.pathname || '').split('/');\n while (relPath.length && !(relative.host = relPath.shift())) { }\n if (!relative.host) { relative.host = ''; }\n if (!relative.hostname) { relative.hostname = ''; }\n if (relPath[0] !== '') { relPath.unshift(''); }\n if (relPath.length < 2) { relPath.unshift(''); }\n result.pathname = relPath.join('/');\n } else {\n result.pathname = relative.pathname;\n }\n result.search = relative.search;\n result.query = relative.query;\n result.host = relative.host || '';\n result.auth = relative.auth;\n result.hostname = relative.hostname || relative.host;\n result.port = relative.port;\n // to support http.request\n if (result.pathname || result.search) {\n var p = result.pathname || '';\n var s = result.search || '';\n result.path = p + s;\n }\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n }\n\n var isSourceAbs = result.pathname && result.pathname.charAt(0) === '/',\n isRelAbs = relative.host || relative.pathname && relative.pathname.charAt(0) === '/',\n mustEndAbs = isRelAbs || isSourceAbs || (result.host && relative.pathname),\n removeAllDots = mustEndAbs,\n srcPath = result.pathname && result.pathname.split('/') || [],\n relPath = relative.pathname && relative.pathname.split('/') || [],\n psychotic = result.protocol && !slashedProtocol[result.protocol];\n\n /*\n * if the url is a non-slashed url, then relative\n * links like ../.. should be able\n * to crawl up to the hostname, as well. This is strange.\n * result.protocol has already been set by now.\n * Later on, put the first path part into the host field.\n */\n if (psychotic) {\n result.hostname = '';\n result.port = null;\n if (result.host) {\n if (srcPath[0] === '') { srcPath[0] = result.host; } else { srcPath.unshift(result.host); }\n }\n result.host = '';\n if (relative.protocol) {\n relative.hostname = null;\n relative.port = null;\n if (relative.host) {\n if (relPath[0] === '') { relPath[0] = relative.host; } else { relPath.unshift(relative.host); }\n }\n relative.host = null;\n }\n mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');\n }\n\n if (isRelAbs) {\n // it's absolute.\n result.host = relative.host || relative.host === '' ? relative.host : result.host;\n result.hostname = relative.hostname || relative.hostname === '' ? relative.hostname : result.hostname;\n result.search = relative.search;\n result.query = relative.query;\n srcPath = relPath;\n // fall through to the dot-handling below.\n } else if (relPath.length) {\n /*\n * it's relative\n * throw away the existing file, and take the new path instead.\n */\n if (!srcPath) { srcPath = []; }\n srcPath.pop();\n srcPath = srcPath.concat(relPath);\n result.search = relative.search;\n result.query = relative.query;\n } else if (relative.search != null) {\n /*\n * just pull out the search.\n * like href='?foo'.\n * Put this after the other two cases because it simplifies the booleans\n */\n if (psychotic) {\n result.host = srcPath.shift();\n result.hostname = result.host;\n /*\n * occationaly the auth can get stuck only in host\n * this especially happens in cases like\n * url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n */\n var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.hostname = authInHost.shift();\n result.host = result.hostname;\n }\n }\n result.search = relative.search;\n result.query = relative.query;\n // to support http.request\n if (result.pathname !== null || result.search !== null) {\n result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : '');\n }\n result.href = result.format();\n return result;\n }\n\n if (!srcPath.length) {\n /*\n * no path at all. easy.\n * we've already handled the other stuff above.\n */\n result.pathname = null;\n // to support http.request\n if (result.search) {\n result.path = '/' + result.search;\n } else {\n result.path = null;\n }\n result.href = result.format();\n return result;\n }\n\n /*\n * if a url ENDs in . or .., then it must get a trailing slash.\n * however, if it ends in anything else non-slashy,\n * then it must NOT get a trailing slash.\n */\n var last = srcPath.slice(-1)[0];\n var hasTrailingSlash = (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === '';\n\n /*\n * strip single dots, resolve double dots to parent dir\n * if the path tries to go above the root, `up` ends up > 0\n */\n var up = 0;\n for (var i = srcPath.length; i >= 0; i--) {\n last = srcPath[i];\n if (last === '.') {\n srcPath.splice(i, 1);\n } else if (last === '..') {\n srcPath.splice(i, 1);\n up++;\n } else if (up) {\n srcPath.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (!mustEndAbs && !removeAllDots) {\n for (; up--; up) {\n srcPath.unshift('..');\n }\n }\n\n if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {\n srcPath.unshift('');\n }\n\n if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {\n srcPath.push('');\n }\n\n var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/');\n\n // put the host back\n if (psychotic) {\n result.hostname = isAbsolute ? '' : srcPath.length ? srcPath.shift() : '';\n result.host = result.hostname;\n /*\n * occationaly the auth can get stuck only in host\n * this especially happens in cases like\n * url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n */\n var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.hostname = authInHost.shift();\n result.host = result.hostname;\n }\n }\n\n mustEndAbs = mustEndAbs || (result.host && srcPath.length);\n\n if (mustEndAbs && !isAbsolute) {\n srcPath.unshift('');\n }\n\n if (srcPath.length > 0) {\n result.pathname = srcPath.join('/');\n } else {\n result.pathname = null;\n result.path = null;\n }\n\n // to support request.http\n if (result.pathname !== null || result.search !== null) {\n result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : '');\n }\n result.auth = relative.auth || result.auth;\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n};\n\nUrl.prototype.parseHost = function () {\n var host = this.host;\n var port = portPattern.exec(host);\n if (port) {\n port = port[0];\n if (port !== ':') {\n this.port = port.substr(1);\n }\n host = host.substr(0, host.length - port.length);\n }\n if (host) { this.hostname = host; }\n};\n\nexports.parse = urlParse;\nexports.resolve = urlResolve;\nexports.resolveObject = urlResolveObject;\nexports.format = urlFormat;\n\nexports.Url = Url;\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// resolves . and .. elements in a path array with directory names there\n// must be no slashes, empty elements, or device names (c:\\) in the array\n// (so also no leading and trailing slashes - it does not distinguish\n// relative and absolute paths)\nfunction normalizeArray(parts, allowAboveRoot) {\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = parts.length - 1; i >= 0; i--) {\n var last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// Split a filename into [root, dir, basename, ext], unix version\n// 'root' is just a slash, or nothing.\nvar splitPathRe =\n /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/;\nvar splitPath = function(filename) {\n return splitPathRe.exec(filename).slice(1);\n};\n\n// path.resolve([from ...], to)\n// posix version\nexport function resolve() {\n var resolvedPath = '',\n resolvedAbsolute = false;\n\n for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path = (i >= 0) ? arguments[i] : '/';\n\n // Skip empty and invalid entries\n if (typeof path !== 'string') {\n throw new TypeError('Arguments to path.resolve must be strings');\n } else if (!path) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {\n return !!p;\n }), !resolvedAbsolute).join('/');\n\n return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';\n};\n\n// path.normalize(path)\n// posix version\nexport function normalize(path) {\n var isPathAbsolute = isAbsolute(path),\n trailingSlash = substr(path, -1) === '/';\n\n // Normalize the path\n path = normalizeArray(filter(path.split('/'), function(p) {\n return !!p;\n }), !isPathAbsolute).join('/');\n\n if (!path && !isPathAbsolute) {\n path = '.';\n }\n if (path && trailingSlash) {\n path += '/';\n }\n\n return (isPathAbsolute ? '/' : '') + path;\n};\n\n// posix version\nexport function isAbsolute(path) {\n return path.charAt(0) === '/';\n}\n\n// posix version\nexport function join() {\n var paths = Array.prototype.slice.call(arguments, 0);\n return normalize(filter(paths, function(p, index) {\n if (typeof p !== 'string') {\n throw new TypeError('Arguments to path.join must be strings');\n }\n return p;\n }).join('/'));\n}\n\n\n// path.relative(from, to)\n// posix version\nexport function relative(from, to) {\n from = resolve(from).substr(1);\n to = resolve(to).substr(1);\n\n function trim(arr) {\n var start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') break;\n }\n\n var end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') break;\n }\n\n if (start > end) return [];\n return arr.slice(start, end - start + 1);\n }\n\n var fromParts = trim(from.split('/'));\n var toParts = trim(to.split('/'));\n\n var length = Math.min(fromParts.length, toParts.length);\n var samePartsLength = length;\n for (var i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n var outputParts = [];\n for (var i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n}\n\nexport var sep = '/';\nexport var delimiter = ':';\n\nexport function dirname(path) {\n var result = splitPath(path),\n root = result[0],\n dir = result[1];\n\n if (!root && !dir) {\n // No dirname whatsoever\n return '.';\n }\n\n if (dir) {\n // It has a dirname, strip trailing slash\n dir = dir.substr(0, dir.length - 1);\n }\n\n return root + dir;\n}\n\nexport function basename(path, ext) {\n var f = splitPath(path)[2];\n // TODO: make this comparison case-insensitive on windows?\n if (ext && f.substr(-1 * ext.length) === ext) {\n f = f.substr(0, f.length - ext.length);\n }\n return f;\n}\n\n\nexport function extname(path) {\n return splitPath(path)[3];\n}\nexport default {\n extname: extname,\n basename: basename,\n dirname: dirname,\n sep: sep,\n delimiter: delimiter,\n relative: relative,\n join: join,\n isAbsolute: isAbsolute,\n normalize: normalize,\n resolve: resolve\n};\nfunction filter (xs, f) {\n if (xs.filter) return xs.filter(f);\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n if (f(xs[i], i, xs)) res.push(xs[i]);\n }\n return res;\n}\n\n// String.prototype.substr - negative index don't work in IE8\nvar substr = 'ab'.substr(-1) === 'b' ?\n function (str, start, len) { return str.substr(start, len) } :\n function (str, start, len) {\n if (start < 0) start = str.length + start;\n return str.substr(start, len);\n }\n;\n","/* globals unknown */\n\n/**\n * @typedef {import('url').URLFormatOptions} URLFormatOptions\n * @typedef {import('url').UrlObject} UrlObject\n * @typedef {import('url').format} formatImport\n * @typedef {import('url').parse} parseImport\n * @typedef {import('url').resolve} resolveImport\n * @typedef {import('url').Url} UrlImport\n * @typedef {import('url').fileURLToPath} fileURLToPath\n * @typedef {import('url').pathToFileURL} pathToFileURL\n * @typedef {import('url').domainToUnicode} domainToUnicode\n * @typedef {import('url').domainToASCII} domainToASCII\n */\n\n// @ts-ignore\nimport { format, parse, resolve, resolveObject, Url } from 'url';\nimport { resolve as pathResolve } from 'path';\n\nconst formatImport = /** @type {formatImport}*/ (format);\nconst parseImport = /** @type {parseImport}*/ (parse);\nconst resolveImport = /** @type {resolveImport}*/ (resolve);\n// @ts-ignore\nconst UrlImport = /** @type {UrlImport}*/ (Url);\n\nconst URL = globalThis.URL;\n/* eslint-disable-next-line unicorn/prevent-abbreviations */\nconst URLSearchParams = globalThis.URLSearchParams;\n\nconst percentRegEx = /%/g;\nconst backslashRegEx = /\\\\/g;\nconst newlineRegEx = /\\n/g;\nconst carriageReturnRegEx = /\\r/g;\nconst tabRegEx = /\\t/g;\nconst CHAR_FORWARD_SLASH = 47;\n\n/**\n * @param {unknown} instance\n */\nfunction isURLInstance(instance) {\n\tconst resolved = /** @type {URL|null} */ (instance ?? null);\n\treturn Boolean(resolved !== null && resolved?.href && resolved?.origin);\n}\n\n/**\n * @param {URL} url\n */\nfunction getPathFromURLPosix(url) {\n\tif (url.hostname !== '') {\n\t\tthrow new TypeError(\n\t\t\t`File URL host must be \"localhost\" or empty on browser`\n\t\t);\n\t}\n\tconst pathname = url.pathname;\n\tfor (let n = 0; n < pathname.length; n++) {\n\t\tif (pathname[n] === '%') {\n\t\t\t// @ts-ignore\n\t\t\tconst third = pathname.codePointAt(n + 2) | 0x20;\n\t\t\tif (pathname[n + 1] === '2' && third === 102) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t'File URL path must not include encoded / characters'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn decodeURIComponent(pathname);\n}\n\n/**\n * @param {string} filepath\n */\nfunction encodePathChars(filepath) {\n\tif (filepath.includes('%')) {\n\t\tfilepath = filepath.replace(percentRegEx, '%25');\n\t}\n\tif (filepath.includes('\\\\')) {\n\t\tfilepath = filepath.replace(backslashRegEx, '%5C');\n\t}\n\tif (filepath.includes('\\n')) {\n\t\tfilepath = filepath.replace(newlineRegEx, '%0A');\n\t}\n\tif (filepath.includes('\\r')) {\n\t\tfilepath = filepath.replace(carriageReturnRegEx, '%0D');\n\t}\n\tif (filepath.includes('\\t')) {\n\t\tfilepath = filepath.replace(tabRegEx, '%09');\n\t}\n\treturn filepath;\n}\n\nconst domainToASCII =\n\t/**\n\t * @type {domainToASCII}\n\t */\n\tfunction (domain) {\n\t\tif (typeof domain === 'undefined') {\n\t\t\tthrow new TypeError('The \"domain\" argument must be specified');\n\t\t}\n\t\treturn new URL(`http://${domain}`).hostname;\n\t};\n\nconst domainToUnicode =\n\t/**\n\t * @type {domainToUnicode}\n\t */\n\tfunction (domain) {\n\t\tif (typeof domain === 'undefined') {\n\t\t\tthrow new TypeError('The \"domain\" argument must be specified');\n\t\t}\n\t\treturn new URL(`http://${domain}`).hostname;\n\t};\n\nconst pathToFileURL =\n\t/**\n\t * @type {(url: string) => URL}\n\t */\n\tfunction (filepath) {\n\t\tconst outURL = new URL('file://');\n\t\tlet resolved = pathResolve(filepath);\n\t\tconst filePathLast = filepath.charCodeAt(filepath.length - 1);\n\t\tif (\n\t\t\tfilePathLast === CHAR_FORWARD_SLASH &&\n\t\t\tresolved[resolved.length - 1] !== '/'\n\t\t) {\n\t\t\tresolved += '/';\n\t\t}\n\t\toutURL.pathname = encodePathChars(resolved);\n\t\treturn outURL;\n\t};\n\nconst fileURLToPath =\n\t/**\n\t * @type {fileURLToPath & ((path: string | URL) => string)}\n\t */\n\tfunction (path) {\n\t\tif (!isURLInstance(path) && typeof path !== 'string') {\n\t\t\tthrow new TypeError(\n\t\t\t\t`The \"path\" argument must be of type string or an instance of URL. Received type ${typeof path} (${path})`\n\t\t\t);\n\t\t}\n\t\tconst resolved = new URL(path);\n\t\tif (resolved.protocol !== 'file:') {\n\t\t\tthrow new TypeError('The URL must be of scheme file');\n\t\t}\n\t\treturn getPathFromURLPosix(resolved);\n\t};\n\nconst formatImportWithOverloads =\n\t/**\n\t * @type {(\n\t * ((urlObject: URL, options?: URLFormatOptions) => string) &\n\t * ((urlObject: UrlObject | string, options?: never) => string)\n\t * )}\n\t */\n\tfunction (urlObject, options = {}) {\n\t\tif (!(urlObject instanceof URL)) {\n\t\t\treturn formatImport(urlObject);\n\t\t}\n\n\t\tif (typeof options !== 'object' || options === null) {\n\t\t\tthrow new TypeError(\n\t\t\t\t'The \"options\" argument must be of type object.'\n\t\t\t);\n\t\t}\n\n\t\tconst auth = options.auth ?? true;\n\t\tconst fragment = options.fragment ?? true;\n\t\tconst search = options.search ?? true;\n\t\tconst unicode = options.unicode ?? false;\n\n\t\tconst parsed = new URL(urlObject.toString());\n\n\t\tif (!auth) {\n\t\t\tparsed.username = '';\n\t\t\tparsed.password = '';\n\t\t}\n\n\t\tif (!fragment) {\n\t\t\tparsed.hash = '';\n\t\t}\n\n\t\tif (!search) {\n\t\t\tparsed.search = '';\n\t\t}\n\n\t\tif (unicode) {\n\t\t\t// Not implemented\n\t\t}\n\n\t\treturn parsed.toString();\n\t};\n\nconst api = {\n\tformat: formatImportWithOverloads,\n\tparse: parseImport,\n\tresolve: resolveImport,\n\tresolveObject,\n\tUrl: UrlImport,\n\tURL,\n\tURLSearchParams,\n\tdomainToASCII,\n\tdomainToUnicode,\n\tpathToFileURL,\n\tfileURLToPath\n};\n\nexport default api;\n\nexport {\n\tformatImportWithOverloads as format,\n\tparseImport as parse,\n\tresolveImport as resolve,\n\tresolveObject,\n\tUrlImport as Url,\n\tURL,\n\tURLSearchParams,\n\tdomainToASCII,\n\tdomainToUnicode,\n\tpathToFileURL,\n\tfileURLToPath\n};\n"],"names":["resolve","formatImport","format","parseImport","parse","resolveImport","UrlImport","Url","URL","_globalThis","URLSearchParams","percentRegEx","backslashRegEx","newlineRegEx","carriageReturnRegEx","tabRegEx","CHAR_FORWARD_SLASH","isURLInstance","instance","resolved","Boolean","href","origin","getPathFromURLPosix","url","hostname","TypeError","pathname","n","length","third","codePointAt","decodeURIComponent","encodePathChars","filepath","includes","replace","domainToASCII","domain","domainToUnicode","pathToFileURL","outURL","pathResolve","filePathLast","charCodeAt","fileURLToPath","path","protocol","formatImportWithOverloads","urlObject","options","_options$auth","_options$fragment","_options$search","_options$unicode","auth","fragment","search","unicode","parsed","toString","username","password","hash","api","resolveObject"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwBA;AACA,IAAI,QAAQ,GAAG,UAAoB,CAAC;AACpC;AACA,SAAS,GAAG,GAAG;AACf,EAAE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;AACvB,EAAE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;AACtB,EAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACnB,EAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACnB,EAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACnB,EAAE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;AACvB,EAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACnB,EAAE,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;AACrB,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;AACpB,EAAE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;AACvB,EAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACnB,EAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACnB,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,eAAe,GAAG,mBAAmB;AACzC,EAAE,WAAW,GAAG,UAAU;AAC1B;AACA;AACA,EAAE,iBAAiB,GAAG,mCAAmC;AACzD;AACA;AACA;AACA;AACA;AACA,EAAE,MAAM,GAAG;AACX,IAAI,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI;AAC7C,GAAG;AACH;AACA;AACA,EAAE,MAAM,GAAG;AACX,IAAI,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG;AACjC,GAAG,CAAC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AM,CAACG,QAAQ,GAAG,EAAE,CAAA;AACrB,GAAA;EAEA,IAAI,CAACN,QAAQ,EAAE;IACdG,MAAM,CAACI,IAAI,GAAG,EAAE,CAAA;AACjB,GAAA;EAEA,IAAI,CAACN,MAAM,EAAE;IACZE,MAAM,CAACF,MAAM,GAAG,EAAE,CAAA;AACnB,GAAA;AAMA,EAAA,OAAOE,MAAM,CAACC,QAAQ,EAAE,CAAA;AACzB,EAAC;AAEF,IAAMI,GAAG,GAAG;AACX9D,EAAAA,MAAM,EAAE8C,yBAAyB;AACjC5C,EAAAA,KAAK,EAAED,WAAW;AAClBH,EAAAA,OAAO,EAAEK,aAAa;AACtB4D,EAAAA,aAAa,EAAbA,aAAa;AACb1D,EAAAA,GAAG,EAAED,SAAS;AACdE,EAAAA,GAAG,EAAHA,GAAG;AACHE,EAAAA,eAAe,EAAfA,eAAe;AACf2B,EAAAA,aAAa,EAAbA,aAAa;AACbE,EAAAA,eAAe,EAAfA,eAAe;AACfC,EAAAA,aAAa,EAAbA,aAAa;AACbK,EAAAA,aAAa,EAAbA,aAAAA;AACD;;;;"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/types/lib.d.ts b/node_modules/node-stdlib-browser/esm/types/lib.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4048e05ef034ef2b1a8a7d5c6bfa6cc8f3fa8176 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/types/lib.d.ts @@ -0,0 +1,10 @@ +/// +declare module 'querystring-es3' { + import { decode, encode, parse, stringify } from 'querystring'; + export { decode, encode, parse, stringify }; +} +declare module 'process/browser.js' { + const process: NodeJS.Process; + export = process; +} +//# sourceMappingURL=lib.d.ts.map \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/esm/types/lib.d.ts.map b/node_modules/node-stdlib-browser/esm/types/lib.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..28642c78d2fb4a234df06188d07a53d92d302293 --- /dev/null +++ b/node_modules/node-stdlib-browser/esm/types/lib.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"lib.d.ts","sourceRoot":"","sources":["../../types/lib.ts"],"names":[],"mappings":";AAAA,OAAO,QAAQ,iBAAiB,CAAC;IAChC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;IAC/D,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;CAC5C;AAED,OAAO,QAAQ,oBAAoB,CAAC;IACnC,MAAM,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC;IAC9B,SAAS,OAAO,CAAC;CACjB"} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/helpers/esbuild/plugin.js b/node_modules/node-stdlib-browser/helpers/esbuild/plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..d28f46403cb760aa2db9401db0b29215f7c3d38a --- /dev/null +++ b/node_modules/node-stdlib-browser/helpers/esbuild/plugin.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * @typedef {import('../../')} Packages + * @typedef {import('esbuild').Plugin} esbuild.Plugin + */ + +const { promisify } = require('util'); +const browserResolve = require('browser-resolve'); + +const pBrowserResolve = promisify(browserResolve); + +const plugin = ( + /** @type {Packages | {[key: string]: string}} */ stdLibBrowser +) => { + /** @type {esbuild.Plugin} */ + const main = { + name: 'node-stdlib-browser-alias', + async setup(build) { + const map = new Map(); + const promises = Object.entries(stdLibBrowser).map( + async ([name, path]) => { + // @ts-ignore + const resolvedPath = await pBrowserResolve(path, {}); + map.set(name, resolvedPath); + } + ); + await Promise.all(promises); + + map.forEach((path, name) => { + build.onResolve({ filter: new RegExp(`^${name}$`) }, () => { + return { + path + }; + }); + }); + } + }; + return main; +}; + +module.exports = plugin; diff --git a/node_modules/node-stdlib-browser/helpers/esbuild/shim.js b/node_modules/node-stdlib-browser/helpers/esbuild/shim.js new file mode 100644 index 0000000000000000000000000000000000000000..ccdc55d1b130503ec2e4a9bb5dc493a2c2bef9ba --- /dev/null +++ b/node_modules/node-stdlib-browser/helpers/esbuild/shim.js @@ -0,0 +1,24 @@ +var _globalThis = function (Object) { + function get() { + var _global = this || self; + delete Object.prototype.__magic__; + return _global; + } + if (typeof globalThis === "object") { + return globalThis; + } + if (this) { + return get(); + } else { + Object.defineProperty(Object.prototype, "__magic__", { + configurable: true, + get: get + }); + var _global = __magic__; + return _global; + } +}(Object); +import { Buffer } from 'buffer'; +import process from 'process'; +var _global = _globalThis; +export { Buffer, process, _global as global }; diff --git a/node_modules/node-stdlib-browser/helpers/rollup/plugin.js b/node_modules/node-stdlib-browser/helpers/rollup/plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..1a7c728bf48986a488eeae1c3bf53dccf7277496 --- /dev/null +++ b/node_modules/node-stdlib-browser/helpers/rollup/plugin.js @@ -0,0 +1,34 @@ +'use strict'; + +/** + * @typedef {import('rollup')} rollup + * @typedef {import('rollup').WarningHandlerWithDefault} rollup.WarningHandlerWithDefault + */ + +/** + * @type {rollup.WarningHandlerWithDefault} + */ +function handleCircularDependancyWarning(warning, warningHandler) { + const packagesWithCircularDependencies = [ + 'util/', + 'assert/', + 'readable-stream/', + 'crypto-browserify/' + ]; + if ( + !( + warning.code === 'CIRCULAR_DEPENDENCY' && + packagesWithCircularDependencies.some((modulePath) => { + if (typeof warning.importer !== 'string') { + return false; + } + return warning.importer.includes(modulePath); + }) + ) + ) { + warningHandler(warning); + } +} + +module.exports.handleCircularDependancyWarning = + handleCircularDependancyWarning; diff --git a/node_modules/node-stdlib-browser/helpers/webpack/plugin.js b/node_modules/node-stdlib-browser/helpers/webpack/plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..9dd651480f340b3655f6d800b5fa4d74c6a1ee45 --- /dev/null +++ b/node_modules/node-stdlib-browser/helpers/webpack/plugin.js @@ -0,0 +1,16 @@ +'use strict'; + +const webpack = require('webpack'); + +const nodeProtocolRegex = /^node:/; + +function NodeProtocolUrlPlugin() { + return new webpack.NormalModuleReplacementPlugin( + nodeProtocolRegex, + (resource) => { + resource.request = resource.request.replace(nodeProtocolRegex, ''); + } + ); +} + +module.exports.NodeProtocolUrlPlugin = NodeProtocolUrlPlugin; diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/CONTRIBUTING.md b/node_modules/node-stdlib-browser/node_modules/readable-stream/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..f478d58dca85b2c396e2da8a2251be0071c4e9e0 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Moderation Policy + +The [Node.js Moderation Policy] applies to this WG. + +## Code of Conduct + +The [Node.js Code of Conduct][] applies to this WG. + +[Node.js Code of Conduct]: +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md +[Node.js Moderation Policy]: +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/GOVERNANCE.md b/node_modules/node-stdlib-browser/node_modules/readable-stream/GOVERNANCE.md new file mode 100644 index 0000000000000000000000000000000000000000..16ffb93f24bece9519cc4a220a0c1d3c91481453 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/GOVERNANCE.md @@ -0,0 +1,136 @@ +### Streams Working Group + +The Node.js Streams is jointly governed by a Working Group +(WG) +that is responsible for high-level guidance of the project. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Conduct guidelines +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project +[README.md](./README.md#current-project-team-members). + +### Collaborators + +The readable-stream GitHub repository is +maintained by the WG and additional Collaborators who are added by the +WG on an ongoing basis. + +Individuals making significant and valuable contributions are made +Collaborators and given commit-access to the project. These +individuals are identified by the WG and their addition as +Collaborators is discussed during the WG meeting. + +_Note:_ If you make a significant contribution and are not considered +for commit-access log an issue or contact a WG member directly and it +will be brought up in the next WG meeting. + +Modifications of the contents of the readable-stream repository are +made on +a collaborative basis. Anybody with a GitHub account may propose a +modification via pull request and it will be considered by the project +Collaborators. All pull requests must be reviewed and accepted by a +Collaborator with sufficient expertise who is able to take full +responsibility for the change. In the case of pull requests proposed +by an existing Collaborator, an additional Collaborator is required +for sign-off. Consensus should be sought if additional Collaborators +participate and there is disagreement around a particular +modification. See _Consensus Seeking Process_ below for further detail +on the consensus model used for governance. + +Collaborators may opt to elevate significant or controversial +modifications, or modifications that have not found consensus to the +WG for discussion by assigning the ***WG-agenda*** tag to a pull +request or issue. The WG should serve as the final arbiter where +required. + +For the current list of Collaborators, see the project +[README.md](./README.md#members). + +### WG Membership + +WG seats are not time-limited. There is no fixed size of the WG. +However, the expected target is between 6 and 12, to ensure adequate +coverage of important areas of expertise, balanced with the ability to +make decisions efficiently. + +There is no specific set of requirements or qualifications for WG +membership beyond these rules. + +The WG may add additional members to the WG by unanimous consensus. + +A WG member may be removed from the WG by voluntary resignation, or by +unanimous consensus of all other WG members. + +Changes to WG membership should be posted in the agenda, and may be +suggested as any other agenda item (see "WG Meetings" below). + +If an addition or removal is proposed during a meeting, and the full +WG is not in attendance to participate, then the addition or removal +is added to the agenda for the subsequent meeting. This is to ensure +that all members are given the opportunity to participate in all +membership decisions. If a WG member is unable to attend a meeting +where a planned membership decision is being made, then their consent +is assumed. + +No more than 1/3 of the WG members may be affiliated with the same +employer. If removal or resignation of a WG member, or a change of +employment by a WG member, creates a situation where more than 1/3 of +the WG membership shares an employer, then the situation must be +immediately remedied by the resignation or removal of one or more WG +members affiliated with the over-represented employer(s). + +### WG Meetings + +The WG meets occasionally on a Google Hangout On Air. A designated moderator +approved by the WG runs the meeting. Each meeting should be +published to YouTube. + +Items are added to the WG agenda that are considered contentious or +are modifications of governance, contribution policy, WG membership, +or release process. + +The intention of the agenda is not to approve or review all patches; +that should happen continuously on GitHub and be handled by the larger +group of Collaborators. + +Any community member or contributor can ask that something be added to +the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +WG member or the moderator can add the item to the agenda by adding +the ***WG-agenda*** tag to the issue. + +Prior to each WG meeting the moderator will share the Agenda with +members of the WG. WG members can add any items they like to the +agenda at the beginning of each meeting. The moderator and the WG +cannot veto or remove items. + +The WG may invite persons or representatives from certain projects to +participate in a non-voting capacity. + +The moderator is responsible for summarizing the discussion of each +agenda item and sends it as a pull request after the meeting. + +### Consensus Seeking Process + +The WG follows a +[Consensus +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) +decision-making model. + +When an agenda item has appeared to reach a consensus the moderator +will ask "Does anyone object?" as a final call for dissent from the +consensus. + +If an agenda item cannot reach a consensus a WG member can call for +either a closing vote or a vote to table the issue to the next +meeting. The call for a vote must be seconded by a majority of the WG +or else the discussion will continue. Simple majority wins. + +Note that changes to WG membership require a majority consensus. See +"WG Membership" above. diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/LICENSE b/node_modules/node-stdlib-browser/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2873b3b2e595072e66330369d83e8af46655970c --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/README.md b/node_modules/node-stdlib-browser/node_modules/readable-stream/README.md new file mode 100644 index 0000000000000000000000000000000000000000..19117c1a059d1bfa7c6ff04d430bf21bb05b0621 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/README.md @@ -0,0 +1,106 @@ +# readable-stream + +***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) + +```bash +npm install --save readable-stream +``` + +This package is a mirror of the streams implementations in Node.js. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.18.1/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +## Version 3.x.x + +v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: + +1. Error codes: https://github.com/nodejs/node/pull/13310, + https://github.com/nodejs/node/pull/13291, + https://github.com/nodejs/node/pull/16589, + https://github.com/nodejs/node/pull/15042, + https://github.com/nodejs/node/pull/15665, + https://github.com/nodejs/readable-stream/pull/344 +2. 'readable' have precedence over flowing + https://github.com/nodejs/node/pull/18994 +3. make virtual methods errors consistent + https://github.com/nodejs/node/pull/18813 +4. updated streams error handling + https://github.com/nodejs/node/pull/18438 +5. writable.end should return this. + https://github.com/nodejs/node/pull/18780 +6. readable continues to read when push('') + https://github.com/nodejs/node/pull/18211 +7. add custom inspect to BufferList + https://github.com/nodejs/node/pull/17907 +8. always defer 'readable' with nextTick + https://github.com/nodejs/node/pull/17979 + +## Version 2.x.x +v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. + +### Big Thanks + +Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] + +# Usage + +You can swap your `require('stream')` with `require('readable-stream')` +without any changes, if you are just using one of the main classes and +functions. + +```js +const { + Readable, + Writable, + Transform, + Duplex, + pipeline, + finished +} = require('readable-stream') +```` + +Note that `require('stream')` will return `Stream`, while +`require('readable-stream')` will return `Readable`. We discourage using +whatever is exported directly, but rather use one of the properties as +shown in the example above. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + + +## Team Members + +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> +* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com> + +[sauce]: https://saucelabs.com diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/errors-browser.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/errors-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..fb8e73e1893b100932468397b89076261f47ae61 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/errors-browser.js @@ -0,0 +1,127 @@ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.codes = codes; diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/errors.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..8471526d6e7f752d581942611d749ef6355ad1f5 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/errors.js @@ -0,0 +1,116 @@ +'use strict'; + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.codes = codes; diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/experimentalWarning.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/experimentalWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..78e841495bf24d46a2995496bdf2816935b1e66e --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/experimentalWarning.js @@ -0,0 +1,17 @@ +'use strict' + +var experimentalWarnings = new Set(); + +function emitExperimentalWarning(feature) { + if (experimentalWarnings.has(feature)) return; + var msg = feature + ' is an experimental feature. This feature could ' + + 'change at any time'; + experimentalWarnings.add(feature); + process.emitWarning(msg, 'ExperimentalWarning'); +} + +function noop() {} + +module.exports.emitExperimentalWarning = process.emitWarning + ? emitExperimentalWarning + : noop; diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000000000000000000000000000000000000..19abfa604d5ef7bf3646c1a70a848c3f0df8105a --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,126 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; +/**/ + +module.exports = Duplex; +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); +require('inherits')(Duplex, Readable); +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +// the no-half-open enforcer +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(onEndNT, this); +} +function onEndNT(self) { + self.end(); +} +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000000000000000000000000000000000000..24a6bdde2903fac66f638e578b831a7600761207 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; +var Transform = require('./_stream_transform'); +require('inherits')(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000000000000000000000000000000000000..df1f608d532606ba1df4eeaf3b6f577791dcd9ad --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,1027 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +module.exports = Readable; + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ +var debugUtil = require('util'); +var debug; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + +var BufferList = require('./internal/streams/buffer_list'); +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + +// Lazy loaded to improve the startup performance. +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; +require('inherits')(Readable, Stream); +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + if (!(this instanceof Readable)) return new Readable(options); + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + + // legacy + this.readable = true; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + Stream.call(this); +} +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + return er; +} +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + + // Iterate over current buffer to convert already stored Buffers: + var p = this._readableState.buffer.head; + var content = ''; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; + +// Don't raise the hwm > 1GB +var MAX_HWM = 0x40000000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit('data', ret); + return ret; +}; +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } + + // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var 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); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + return dest; +}; +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; + + // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; +}; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} +function resume_(stream, state) { + debug('resume', state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + this._readableState.paused = true; + return this; +}; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; +}; +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); + } + return createReadableStreamAsyncIterator(this); + }; +} +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = require('./internal/streams/from'); + } + return from(Readable, iterable, opts); + }; +} +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000000000000000000000000000000000000..1ccb7157be8b8c35df891c2c0905685a144a2e9a --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,190 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; +var _require$codes = require('../errors').codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; +var Duplex = require('./_stream_duplex'); +require('inherits')(Transform, Duplex); +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} +function prefinish() { + var _this = this; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) + // single equals check for both `null` and `undefined` + stream.push(data); + + // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000000000000000000000000000000000000..292415e23a192be6b7a7f35db37befa489117552 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,641 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; +var errorOrDestroy = destroyImpl.errorOrDestroy; +require('inherits')(Writable, Stream); +function nop() {} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + + // legacy. + this.writable = true; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + // TODO: defer error events consistently everywhere, not just the cb + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + return true; +} +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; +} +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; +} +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; +Writable.prototype._writev = null; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); + return this; +}; +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; +} +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/async_iterator.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/async_iterator.js new file mode 100644 index 0000000000000000000000000000000000000000..742c5a4674794d9e7667c02dcbeb44bf8001b4d6 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/async_iterator.js @@ -0,0 +1,180 @@ +'use strict'; + +var _Object$setPrototypeO; +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var finished = require('./end-of-stream'); +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } + + // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; + // reject if we are waiting for data in the Promise + // returned by next() and store the error + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; +module.exports = createReadableStreamAsyncIterator; \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/buffer_list.js new file mode 100644 index 0000000000000000000000000000000000000000..69bda497d35f347f1a510eef0fe2408e8d31923c --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/buffer_list.js @@ -0,0 +1,183 @@ +'use strict'; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = require('buffer'), + Buffer = _require.Buffer; +var _require2 = require('util'), + inspect = _require2.inspect; +var custom = inspect && inspect.custom || 'inspect'; +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} +module.exports = /*#__PURE__*/function () { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; +}(); \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/destroy.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 0000000000000000000000000000000000000000..31a17c4dc463880722098b62598fe21bc9672132 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,96 @@ +'use strict'; + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; +} +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} +function emitErrorNT(self, err) { + self.emit('error', err); +} +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/end-of-stream.js new file mode 100644 index 0000000000000000000000000000000000000000..59c671b5af769bc5797843837056ae419ab22e80 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/end-of-stream.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; +} +function noop() {} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} +module.exports = eos; \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/from-browser.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/from-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..a4ce56f3c90f60d3416e8e0328375c4b20213872 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/from-browser.js @@ -0,0 +1,3 @@ +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/from.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/from.js new file mode 100644 index 0000000000000000000000000000000000000000..0a34ee92e3df85fd31734c3d95a43697df8fbbb9 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/from.js @@ -0,0 +1,52 @@ +'use strict'; + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE; +function from(Readable, iterable, opts) { + var iterator; + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); + // Reading boolean to protect against _read + // being called before last iteration completion. + var reading = false; + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + function next() { + return _next2.apply(this, arguments); + } + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator.next(), + value = _yield$iterator$next.value, + done = _yield$iterator$next.done; + if (done) { + readable.push(null); + } else if (readable.push(yield value)) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + return readable; +} +module.exports = from; diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/pipeline.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/pipeline.js new file mode 100644 index 0000000000000000000000000000000000000000..e6f39241f98dd890dda9d4dbea076540ed43cabc --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/pipeline.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} +function call(fn) { + fn(); +} +function pipe(from, to) { + return from.pipe(to); +} +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} +module.exports = pipeline; \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/state.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/state.js new file mode 100644 index 0000000000000000000000000000000000000000..3fbf8927e00179deca5a8855b4b4c17da9450676 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/state.js @@ -0,0 +1,22 @@ +'use strict'; + +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + + // Default value + return state.objectMode ? 16 : 16 * 1024; +} +module.exports = { + getHighWaterMark: getHighWaterMark +}; \ No newline at end of file diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..9332a3fdae7060505c0a081614e697fa6cb56dc0 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/stream.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 0000000000000000000000000000000000000000..ce2ad5b6ee57f4778a1f4838f7970093c7941c1c --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/package.json b/node_modules/node-stdlib-browser/node_modules/readable-stream/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ade59e71aa0f170b4ec49a32cf0d04ab5f73ad86 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/package.json @@ -0,0 +1,68 @@ +{ + "name": "readable-stream", + "version": "3.6.2", + "description": "Streams3, a user-land copy of the stream library from Node.js", + "main": "readable.js", + "engines": { + "node": ">= 6" + }, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "devDependencies": { + "@babel/cli": "^7.2.0", + "@babel/core": "^7.2.0", + "@babel/polyfill": "^7.0.0", + "@babel/preset-env": "^7.2.0", + "airtap": "0.0.9", + "assert": "^1.4.0", + "bl": "^2.0.0", + "deep-strict-equal": "^0.2.0", + "events.once": "^2.0.2", + "glob": "^7.1.2", + "gunzip-maybe": "^1.4.1", + "hyperquest": "^2.1.3", + "lolex": "^2.6.0", + "nyc": "^11.0.0", + "pump": "^3.0.0", + "rimraf": "^2.6.2", + "tap": "^12.0.0", + "tape": "^4.9.0", + "tar-fs": "^1.16.2", + "util-promisify": "^2.1.0" + }, + "scripts": { + "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js", + "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap", + "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js", + "test-browser-local": "airtap --open --local -- test/browser.js", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov", + "update-browser-errors": "babel -o errors-browser.js errors.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false, + "worker_threads": false, + "./errors": "./errors-browser.js", + "./readable.js": "./readable-browser.js", + "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "license": "MIT" +} diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/readable-browser.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/readable-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..adbf60de832f9d6e066625f09d708670291e1bfd --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/readable-browser.js @@ -0,0 +1,9 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); +exports.finished = require('./lib/internal/streams/end-of-stream.js'); +exports.pipeline = require('./lib/internal/streams/pipeline.js'); diff --git a/node_modules/node-stdlib-browser/node_modules/readable-stream/readable.js b/node_modules/node-stdlib-browser/node_modules/readable-stream/readable.js new file mode 100644 index 0000000000000000000000000000000000000000..9e0ca120ded827e5ba3343f826fa7462a841e092 --- /dev/null +++ b/node_modules/node-stdlib-browser/node_modules/readable-stream/readable.js @@ -0,0 +1,16 @@ +var Stream = require('stream'); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + exports.finished = require('./lib/internal/streams/end-of-stream.js'); + exports.pipeline = require('./lib/internal/streams/pipeline.js'); +} diff --git a/node_modules/node-stdlib-browser/package.json b/node_modules/node-stdlib-browser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c7ddc5b7faa41acae926a1425dfdb171d81dc8a2 --- /dev/null +++ b/node_modules/node-stdlib-browser/package.json @@ -0,0 +1,143 @@ +{ + "name": "node-stdlib-browser", + "version": "1.3.1", + "description": "Node standard library for browser.", + "license": "MIT", + "author": "Ivan Nikolić (http://ivannikolic.com)", + "sideEffects": false, + "exports": { + ".": { + "import": "./esm/index.js", + "require": "./cjs/index.js" + }, + "./mock/*": { + "import": "./esm/mock/*.js", + "require": "./cjs/mock/*.js" + }, + "./helpers/esbuild/*": "./helpers/esbuild/*.js", + "./helpers/webpack/*": "./helpers/webpack/*.js", + "./helpers/rollup/*": "./helpers/rollup/*.js", + "./package.json": "./package.json" + }, + "main": "cjs/index.js", + "module": "esm/index.js", + "types": "esm/index.d.ts", + "directories": { + "test": "test" + }, + "files": [ + "cjs/", + "esm/", + "helpers/esbuild/{plugin,shim}.js", + "helpers/webpack/plugin.js", + "helpers/rollup/plugin.js", + "CHANGELOG.md", + "LICENSE.md", + "README.md" + ], + "scripts": { + "build": "del '{esm/,cjs/}' && rollup --config rollup.config.js && babel helpers/esbuild/shim.src.js --out-file=helpers/esbuild/shim.js", + "lint": "eslint '{index,lib/**/*,test/**/*,helpers/**/*,example/**/*}.{js,mjs}'", + "lint:types": "tsc", + "module-check": "node -e 'require(\"node-stdlib-browser\"); require(\"node-stdlib-browser/helpers/esbuild/plugin\");' && node --input-type=module -e 'import \"node-stdlib-browser\"; import \"node-stdlib-browser/helpers/esbuild/plugin\";'", + "prepublishOnly": "npm run build", + "postpublish": "GITHUB_TOKEN=$GITHUB_RELEASE_TOKEN github-release-from-changelog", + "prerelease": "npm run lint && npm run lint:types && npm run build && npm run module-check", + "release": "np --no-release-draft", + "test": "BABEL_ENV=test nyc mocha --require @babel/register --require esm 'test/**/*.js' && nyc check-coverage", + "test:watch": "nodemon --exec npm test", + "version": "if [ $(git rev-parse --abbrev-ref HEAD) == 'master' ]; then sed -i '' '/\\[unreleased\\]:/d' CHANGELOG.md && version-changelog CHANGELOG.md && changelog-verify CHANGELOG.md && git add CHANGELOG.md; else echo; fi" + }, + "dependencies": { + "assert": "^2.0.0", + "browser-resolve": "^2.0.0", + "browserify-zlib": "^0.2.0", + "buffer": "^5.7.1", + "console-browserify": "^1.1.0", + "constants-browserify": "^1.0.0", + "create-require": "^1.1.1", + "crypto-browserify": "^3.12.1", + "domain-browser": "4.22.0", + "events": "^3.0.0", + "https-browserify": "^1.0.0", + "isomorphic-timers-promises": "^1.0.1", + "os-browserify": "^0.3.0", + "path-browserify": "^1.0.1", + "pkg-dir": "^5.0.0", + "process": "^0.11.10", + "punycode": "^1.4.1", + "querystring-es3": "^0.2.1", + "readable-stream": "^3.6.0", + "stream-browserify": "^3.0.0", + "stream-http": "^3.2.0", + "string_decoder": "^1.0.0", + "timers-browserify": "^2.0.4", + "tty-browserify": "0.0.1", + "url": "^0.11.4", + "util": "^0.12.4", + "vm-browserify": "^1.0.1" + }, + "devDependencies": { + "@babel/cli": "^7.2.3", + "@babel/core": "^7.2.2", + "@babel/preset-env": "^7.12.1", + "@babel/register": "^7.0.0", + "@rollup/plugin-babel": "^5.2.1", + "@rollup/plugin-commonjs": "^20.0.0", + "@types/browser-resolve": "^2.0.1", + "@types/mocha": "^8.2.3", + "@types/node": "^16.3.0", + "@types/parse-node-version": "^1.0.0", + "babel-plugin-istanbul": "^6.0.0", + "babel-plugin-transform-globalthis": "^1.0.0", + "changelog-verify": "^1.1.2", + "core-js": "^2.6.5", + "cpy": "^8.1.2", + "del": "^6.0.0", + "del-cli": "^3.0.1", + "esbuild": "^0.13.14", + "eslint": "^7.31.0", + "eslint-config-niksy": "^10.0.0", + "eslint-config-prettier": "^8.3.0", + "eslint-plugin-import": "^2.23.4", + "eslint-plugin-jsdoc": "^33.3.0", + "eslint-plugin-mocha": "^8.0.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-prettier": "^3.4.0", + "eslint-plugin-promise": "^5.1.0", + "eslint-plugin-unicorn": "^31.0.0", + "esm": "^3.0.51", + "execa": "^5.1.1", + "github-release-from-changelog": "^2.1.1", + "husky": "^4.3.0", + "lint-staged": "^10.4.2", + "mocha": "^8.2.0", + "nodemon": "^2.0.6", + "np": "^7.6.0", + "nyc": "^15.1.0", + "parse-node-version": "^1.0.1", + "prettier": "^2.4.0", + "rollup": "^2.32.1", + "rollup-plugin-node-builtins": "^2.1.2", + "typescript": "^4.3.5", + "version-changelog": "^3.1.1", + "webpack": "^5.65.0" + }, + "engines": { + "node": ">=10" + }, + "keywords": [ + "node", + "std", + "browser", + "api" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/niksy/node-stdlib-browser.git" + }, + "bugs": { + "url": "https://github.com/niksy/node-stdlib-browser/issues" + }, + "homepage": "https://github.com/niksy/node-stdlib-browser#readme" +} diff --git a/node_modules/normalize-svg-path/Readme.md b/node_modules/normalize-svg-path/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..1a12fecbd8aafd763897e4ad1119c8ea0f768443 --- /dev/null +++ b/node_modules/normalize-svg-path/Readme.md @@ -0,0 +1,28 @@ + +# normalize-svg-path + + Convert all segments in a path to curves. Usefull if you intend to animate one shape to another. By defining all segments with curves instead of a mix of lines, arcs, and curves tweening becomes much simpler. It could also help you rewrite your SVG code according to the principles of [narcissistic design](//vimeo.com/77199361). + +## Installation + +With your favourite package manager: + +- [packin](//github.com/jkroso/packin): `packin add normalize-svg-path` +- [component](//github.com/component/component#installing-packages): `component install jkroso/normalize-svg-path` +- [npm](//npmjs.org/doc/cli/npm-install.html): `npm install normalize-svg-path` + +then in your app: + +```js +var normalize = require('normalize-svg-path') +``` + +## API + +### normalize(path) + + Translate each segment in `path` to an equivalent cubic bézier curve. The input `path` must be [absolute](//github.com/jkroso/abs-svg-path). + +```js +normalize([['L',1,2]]) // => [['C',0,0,1,2,1,2]] +``` diff --git a/node_modules/normalize-svg-path/index.js b/node_modules/normalize-svg-path/index.js new file mode 100644 index 0000000000000000000000000000000000000000..eb1d36d51246e105fdafecb05b413adfd04c47bc --- /dev/null +++ b/node_modules/normalize-svg-path/index.js @@ -0,0 +1,200 @@ + +var π = Math.PI +var _120 = radians(120) + +module.exports = normalize + +/** + * describe `path` in terms of cubic bézier + * curves and move commands + * + * @param {Array} path + * @return {Array} + */ + +function normalize(path){ + // init state + var prev + var result = [] + var bezierX = 0 + var bezierY = 0 + var startX = 0 + var startY = 0 + var quadX = null + var quadY = null + var x = 0 + var y = 0 + + for (var i = 0, len = path.length; i < len; i++) { + var seg = path[i] + var command = seg[0] + switch (command) { + case 'M': + startX = seg[1] + startY = seg[2] + break + case 'A': + seg = arc(x, y,seg[1],seg[2],radians(seg[3]),seg[4],seg[5],seg[6],seg[7]) + // split multi part + seg.unshift('C') + if (seg.length > 7) { + result.push(seg.splice(0, 7)) + seg.unshift('C') + } + break + case 'S': + // default control point + var cx = x + var cy = y + if (prev == 'C' || prev == 'S') { + cx += cx - bezierX // reflect the previous command's control + cy += cy - bezierY // point relative to the current point + } + seg = ['C', cx, cy, seg[1], seg[2], seg[3], seg[4]] + break + case 'T': + if (prev == 'Q' || prev == 'T') { + quadX = x * 2 - quadX // as with 'S' reflect previous control point + quadY = y * 2 - quadY + } else { + quadX = x + quadY = y + } + seg = quadratic(x, y, quadX, quadY, seg[1], seg[2]) + break + case 'Q': + quadX = seg[1] + quadY = seg[2] + seg = quadratic(x, y, seg[1], seg[2], seg[3], seg[4]) + break + case 'L': + seg = line(x, y, seg[1], seg[2]) + break + case 'H': + seg = line(x, y, seg[1], y) + break + case 'V': + seg = line(x, y, x, seg[1]) + break + case 'Z': + seg = line(x, y, startX, startY) + break + } + + // update state + prev = command + x = seg[seg.length - 2] + y = seg[seg.length - 1] + if (seg.length > 4) { + bezierX = seg[seg.length - 4] + bezierY = seg[seg.length - 3] + } else { + bezierX = x + bezierY = y + } + result.push(seg) + } + + return result +} + +function line(x1, y1, x2, y2){ + return ['C', x1, y1, x2, y2, x2, y2] +} + +function quadratic(x1, y1, cx, cy, x2, y2){ + return [ + 'C', + x1/3 + (2/3) * cx, + y1/3 + (2/3) * cy, + x2/3 + (2/3) * cx, + y2/3 + (2/3) * cy, + x2, + y2 + ] +} + +// This function is ripped from +// github.com/DmitryBaranovskiy/raphael/blob/4d97d4/raphael.js#L2216-L2304 +// which references w3.org/TR/SVG11/implnote.html#ArcImplementationNotes +// TODO: make it human readable + +function arc(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { + if (!recursive) { + var xy = rotate(x1, y1, -angle) + x1 = xy.x + y1 = xy.y + xy = rotate(x2, y2, -angle) + x2 = xy.x + y2 = xy.y + var x = (x1 - x2) / 2 + var y = (y1 - y2) / 2 + var h = (x * x) / (rx * rx) + (y * y) / (ry * ry) + if (h > 1) { + h = Math.sqrt(h) + rx = h * rx + ry = h * ry + } + var rx2 = rx * rx + var ry2 = ry * ry + var k = (large_arc_flag == sweep_flag ? -1 : 1) + * Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))) + if (k == Infinity) k = 1 // neutralize + var cx = k * rx * y / ry + (x1 + x2) / 2 + var cy = k * -ry * x / rx + (y1 + y2) / 2 + var f1 = Math.asin(((y1 - cy) / ry).toFixed(9)) + var f2 = Math.asin(((y2 - cy) / ry).toFixed(9)) + + f1 = x1 < cx ? π - f1 : f1 + f2 = x2 < cx ? π - f2 : f2 + if (f1 < 0) f1 = π * 2 + f1 + if (f2 < 0) f2 = π * 2 + f2 + if (sweep_flag && f1 > f2) f1 = f1 - π * 2 + if (!sweep_flag && f2 > f1) f2 = f2 - π * 2 + } else { + f1 = recursive[0] + f2 = recursive[1] + cx = recursive[2] + cy = recursive[3] + } + // greater than 120 degrees requires multiple segments + if (Math.abs(f2 - f1) > _120) { + var f2old = f2 + var x2old = x2 + var y2old = y2 + f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1) + x2 = cx + rx * Math.cos(f2) + y2 = cy + ry * Math.sin(f2) + var res = arc(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]) + } + var t = Math.tan((f2 - f1) / 4) + var hx = 4 / 3 * rx * t + var hy = 4 / 3 * ry * t + var curve = [ + 2 * x1 - (x1 + hx * Math.sin(f1)), + 2 * y1 - (y1 - hy * Math.cos(f1)), + x2 + hx * Math.sin(f2), + y2 - hy * Math.cos(f2), + x2, + y2 + ] + if (recursive) return curve + if (res) curve = curve.concat(res) + for (var i = 0; i < curve.length;) { + var rot = rotate(curve[i], curve[i+1], angle) + curve[i++] = rot.x + curve[i++] = rot.y + } + return curve +} + +function rotate(x, y, rad){ + return { + x: x * Math.cos(rad) - y * Math.sin(rad), + y: x * Math.sin(rad) + y * Math.cos(rad) + } +} + +function radians(degress){ + return degress * (π / 180) +} diff --git a/node_modules/normalize-svg-path/package.json b/node_modules/normalize-svg-path/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3cde986effc8b0f59be982541312cf1eaa9fc6da --- /dev/null +++ b/node_modules/normalize-svg-path/package.json @@ -0,0 +1,20 @@ +{ + "name": "normalize-svg-path", + "version": "0.1.0", + "description": "convert all segments in a path to curves", + "keywords": ["svg","path","normalize"], + "dependencies": {}, + "devDependencies": { + "serve": "jkroso/serve", + "dom": "component/dom", + "parse-svg-path": "*", + "equals": "*", + "mocha": "*", + "jsmd": "*" + }, + "repository": "git://github.com/jkroso/normalize-svg-path.git", + "bugs": "https://github.com/jkroso/normalize-svg-path/issues", + "author": "Jake Rosoman", + "files": ["index.js"], + "license": "MIT" +} \ No newline at end of file diff --git a/node_modules/number-is-integer/index.js b/node_modules/number-is-integer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4dd55e509668bf9917c3caa0e4df88887993eddd --- /dev/null +++ b/node_modules/number-is-integer/index.js @@ -0,0 +1,6 @@ +'use strict'; +var numberIsFinite = require('is-finite'); + +module.exports = Number.isInteger || function (x) { + return numberIsFinite(x) && Math.floor(x) === x; +}; diff --git a/node_modules/number-is-integer/license b/node_modules/number-is-integer/license new file mode 100644 index 0000000000000000000000000000000000000000..654d0bfe943437d43242325b1fbcff5f400d84ee --- /dev/null +++ b/node_modules/number-is-integer/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/number-is-integer/package.json b/node_modules/number-is-integer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4f592b0384b9a34ce8907f674472188fc4088b43 --- /dev/null +++ b/node_modules/number-is-integer/package.json @@ -0,0 +1,40 @@ +{ + "name": "number-is-integer", + "version": "1.0.1", + "description": "ES2015 Number.isInteger() ponyfill", + "license": "MIT", + "repository": "sindresorhus/number-is-integer", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "es2015", + "ecmascript", + "ponyfill", + "polyfill", + "shim", + "number", + "is-integer", + "isinteger", + "integer", + "int", + "num" + ], + "dependencies": { + "is-finite": "^1.0.1" + }, + "devDependencies": { + "ava": "*" + } +} diff --git a/node_modules/number-is-integer/readme.md b/node_modules/number-is-integer/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..53e9166f898b81a0be941d42dc560ace6f85c1c3 --- /dev/null +++ b/node_modules/number-is-integer/readme.md @@ -0,0 +1,34 @@ +# number-is-integer [![Build Status](https://travis-ci.org/sindresorhus/number-is-integer.svg?branch=master)](https://travis-ci.org/sindresorhus/number-is-integer) + +> ES2015 [`Number.isInteger()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger) [ponyfill](https://ponyfill.com) + + +## Install + +``` +$ npm install --save number-is-integer +``` + + +## Usage + +```js +var numberIsInteger = require('number-is-integer'); + +numberIsInteger(1); +//=> true + +numberIsInteger(1.5); +//=> false +``` + + +## Related + +- [is-safe-integer](https://github.com/sindresorhus/is-safe-integer) - ES2015 `Number.isSafeInteger()` ponyfill +- [number-is-float](https://github.com/sindresorhus/number-is-float) - Check if something is a float + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/object-assign/index.js b/node_modules/object-assign/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0930cf8890b9af66125c222c29d7bd75614ac6b4 --- /dev/null +++ b/node_modules/object-assign/index.js @@ -0,0 +1,90 @@ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; diff --git a/node_modules/object-assign/license b/node_modules/object-assign/license new file mode 100644 index 0000000000000000000000000000000000000000..654d0bfe943437d43242325b1fbcff5f400d84ee --- /dev/null +++ b/node_modules/object-assign/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/object-assign/package.json b/node_modules/object-assign/package.json new file mode 100644 index 0000000000000000000000000000000000000000..503eb1e6d0f5a1404c8e7f6c09fbda7e40fd29b4 --- /dev/null +++ b/node_modules/object-assign/package.json @@ -0,0 +1,42 @@ +{ + "name": "object-assign", + "version": "4.1.1", + "description": "ES2015 `Object.assign()` ponyfill", + "license": "MIT", + "repository": "sindresorhus/object-assign", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava", + "bench": "matcha bench.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "object", + "assign", + "extend", + "properties", + "es2015", + "ecmascript", + "harmony", + "ponyfill", + "prollyfill", + "polyfill", + "shim", + "browser" + ], + "devDependencies": { + "ava": "^0.16.0", + "lodash": "^4.16.4", + "matcha": "^0.7.0", + "xo": "^0.16.0" + } +} diff --git a/node_modules/object-assign/readme.md b/node_modules/object-assign/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..1be09d35c776cc0e9cc59519c2de6b9eecf8aa68 --- /dev/null +++ b/node_modules/object-assign/readme.md @@ -0,0 +1,61 @@ +# object-assign [![Build Status](https://travis-ci.org/sindresorhus/object-assign.svg?branch=master)](https://travis-ci.org/sindresorhus/object-assign) + +> ES2015 [`Object.assign()`](http://www.2ality.com/2014/01/object-assign.html) [ponyfill](https://ponyfill.com) + + +## Use the built-in + +Node.js 4 and up, as well as every evergreen browser (Chrome, Edge, Firefox, Opera, Safari), +support `Object.assign()` :tada:. If you target only those environments, then by all +means, use `Object.assign()` instead of this package. + + +## Install + +``` +$ npm install --save object-assign +``` + + +## Usage + +```js +const objectAssign = require('object-assign'); + +objectAssign({foo: 0}, {bar: 1}); +//=> {foo: 0, bar: 1} + +// multiple sources +objectAssign({foo: 0}, {bar: 1}, {baz: 2}); +//=> {foo: 0, bar: 1, baz: 2} + +// overwrites equal keys +objectAssign({foo: 0}, {foo: 1}, {foo: 2}); +//=> {foo: 2} + +// ignores null and undefined sources +objectAssign({foo: 0}, null, {bar: 1}, undefined); +//=> {foo: 0, bar: 1} +``` + + +## API + +### objectAssign(target, [source, ...]) + +Assigns enumerable own properties of `source` objects to the `target` object and returns the `target` object. Additional `source` objects will overwrite previous ones. + + +## Resources + +- [ES2015 spec - Object.assign](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign) + + +## Related + +- [deep-assign](https://github.com/sindresorhus/deep-assign) - Recursive `Object.assign()` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/object-inspect/.eslintrc b/node_modules/object-inspect/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..21f903923ef11aef5d6ca8ade40028520b82a37a --- /dev/null +++ b/node_modules/object-inspect/.eslintrc @@ -0,0 +1,53 @@ +{ + "root": true, + "extends": "@ljharb", + "rules": { + "complexity": 0, + "func-style": [2, "declaration"], + "indent": [2, 4], + "max-lines": 1, + "max-lines-per-function": 1, + "max-params": [2, 4], + "max-statements": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "no-param-reassign": 1, + "strict": 0, // TODO + }, + "overrides": [ + { + "files": ["test/**", "test-*", "example/**"], + "extends": "@ljharb/eslint-config/tests", + "rules": { + "id-length": 0, + }, + }, + { + "files": ["example/**"], + "rules": { + "no-console": 0, + }, + }, + { + "files": ["test/browser/**"], + "env": { + "browser": true, + }, + }, + { + "files": ["test/bigint*"], + "rules": { + "new-cap": [2, { "capIsNewExceptions": ["BigInt"] }], + }, + }, + { + "files": "index.js", + "globals": { + "HTMLElement": false, + }, + "rules": { + "no-use-before-define": 1, + }, + }, + ], +} diff --git a/node_modules/object-inspect/.github/FUNDING.yml b/node_modules/object-inspect/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..730276bd121df856ede4c51d6e7b63d071242487 --- /dev/null +++ b/node_modules/object-inspect/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/object-inspect +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/object-inspect/.nycrc b/node_modules/object-inspect/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..58a5db7834ad50f2f9a5814f49d98db106381316 --- /dev/null +++ b/node_modules/object-inspect/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "instrumentation": false, + "sourceMap": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "example", + "test", + "test-core-js.js" + ] +} diff --git a/node_modules/object-inspect/CHANGELOG.md b/node_modules/object-inspect/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..bdf9002747e971f342607364e8557fc8bd3e80ec --- /dev/null +++ b/node_modules/object-inspect/CHANGELOG.md @@ -0,0 +1,424 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.13.4](https://github.com/inspect-js/object-inspect/compare/v1.13.3...v1.13.4) - 2025-02-04 + +### Commits + +- [Fix] avoid being fooled by a `Symbol.toStringTag` [`fa5870d`](https://github.com/inspect-js/object-inspect/commit/fa5870da468a525d2f20193700f70752f506cbf7) +- [Tests] fix tests in node v6.0 - v6.4 [`2abfe1b`](https://github.com/inspect-js/object-inspect/commit/2abfe1bc3c69f9293c07c5cd65a9d7d87a628b84) +- [Dev Deps] update `es-value-fixtures`, `for-each`, `has-symbols` [`3edfb01`](https://github.com/inspect-js/object-inspect/commit/3edfb01cc8cce220fba0dfdfe2dc8bc955758cdd) + +## [v1.13.3](https://github.com/inspect-js/object-inspect/compare/v1.13.2...v1.13.3) - 2024-11-09 + +### Commits + +- [actions] split out node 10-20, and 20+ [`44395a8`](https://github.com/inspect-js/object-inspect/commit/44395a8fc1deda6718a5e125e86b9ffcaa1c7580) +- [Fix] `quoteStyle`: properly escape only the containing quotes [`5137f8f`](https://github.com/inspect-js/object-inspect/commit/5137f8f7bea69a7fc671bb683fd35f244f38fc52) +- [Refactor] clean up `quoteStyle` code [`450680c`](https://github.com/inspect-js/object-inspect/commit/450680cd50de4e689ee3b8e1d6db3a1bcf3fc18c) +- [Tests] add `quoteStyle` escaping tests [`e997c59`](https://github.com/inspect-js/object-inspect/commit/e997c595aeaea84fd98ca35d7e1c3b5ab3ae26e0) +- [Dev Deps] update `auto-changelog`, `es-value-fixtures`, `tape` [`d5a469c`](https://github.com/inspect-js/object-inspect/commit/d5a469c99ec07ccaeafc36ac4b36a93285086d48) +- [Tests] replace `aud` with `npm audit` [`fb7815f`](https://github.com/inspect-js/object-inspect/commit/fb7815f9b72cae277a04f65bbb0543f85b88be62) +- [Dev Deps] update `mock-property` [`11c817b`](https://github.com/inspect-js/object-inspect/commit/11c817bf10392aa017755962ba6bc89d731359ee) + +## [v1.13.2](https://github.com/inspect-js/object-inspect/compare/v1.13.1...v1.13.2) - 2024-06-21 + +### Commits + +- [readme] update badges [`8a51e6b`](https://github.com/inspect-js/object-inspect/commit/8a51e6bedaf389ec40cc4659e9df53e8543d176e) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`ef05f58`](https://github.com/inspect-js/object-inspect/commit/ef05f58c9761a41416ab907299bf0fa79517014b) +- [Dev Deps] update `error-cause`, `has-tostringtag`, `tape` [`c0c6c26`](https://github.com/inspect-js/object-inspect/commit/c0c6c26c44cee6671f7c5d43d2b91d27c5c00d90) +- [Fix] Don't throw when `global` is not defined [`d4d0965`](https://github.com/inspect-js/object-inspect/commit/d4d096570f7dbd0e03266a96de11d05eb7b63e0f) +- [meta] add missing `engines.node` [`17a352a`](https://github.com/inspect-js/object-inspect/commit/17a352af6fe1ba6b70a19081674231eb1a50c940) +- [Dev Deps] update `globalthis` [`9c08884`](https://github.com/inspect-js/object-inspect/commit/9c08884aa662a149e2f11403f413927736b97da7) +- [Dev Deps] update `error-cause` [`6af352d`](https://github.com/inspect-js/object-inspect/commit/6af352d7c3929a4cc4c55768c27bf547a5e900f4) +- [Dev Deps] update `npmignore` [`94e617d`](https://github.com/inspect-js/object-inspect/commit/94e617d38831722562fa73dff4c895746861d267) +- [Dev Deps] update `mock-property` [`2ac24d7`](https://github.com/inspect-js/object-inspect/commit/2ac24d7e58cd388ad093c33249e413e05bbfd6c3) +- [Dev Deps] update `tape` [`46125e5`](https://github.com/inspect-js/object-inspect/commit/46125e58f1d1dcfb170ed3d1ea69da550ea8d77b) + +## [v1.13.1](https://github.com/inspect-js/object-inspect/compare/v1.13.0...v1.13.1) - 2023-10-19 + +### Commits + +- [Fix] in IE 8, global can !== window despite them being prototypes of each other [`30d0859`](https://github.com/inspect-js/object-inspect/commit/30d0859dc4606cf75c2410edcd5d5c6355f8d372) + +## [v1.13.0](https://github.com/inspect-js/object-inspect/compare/v1.12.3...v1.13.0) - 2023-10-14 + +### Commits + +- [New] add special handling for the global object [`431bab2`](https://github.com/inspect-js/object-inspect/commit/431bab21a490ee51d35395966a504501e8c685da) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`fd4f619`](https://github.com/inspect-js/object-inspect/commit/fd4f6193562b4b0e95dcf5c0201b4e8cbbc4f58d) +- [Dev Deps] update `mock-property`, `tape` [`b453f6c`](https://github.com/inspect-js/object-inspect/commit/b453f6ceeebf8a1b738a1029754092e0367a4134) +- [Dev Deps] update `error-cause` [`e8ffc57`](https://github.com/inspect-js/object-inspect/commit/e8ffc577d73b92bb6a4b00c44f14e3319e374888) +- [Dev Deps] update `tape` [`054b8b9`](https://github.com/inspect-js/object-inspect/commit/054b8b9b98633284cf989e582450ebfbbe53503c) +- [Dev Deps] temporarily remove `aud` due to breaking change in transitive deps [`2476845`](https://github.com/inspect-js/object-inspect/commit/2476845e0678dd290c541c81cd3dec8420782c52) +- [Dev Deps] pin `glob`, since v10.3.8+ requires a broken `jackspeak` [`383fa5e`](https://github.com/inspect-js/object-inspect/commit/383fa5eebc0afd705cc778a4b49d8e26452e49a8) +- [Dev Deps] pin `jackspeak` since 2.1.2+ depends on npm aliases, which kill the install process in npm < 6 [`68c244c`](https://github.com/inspect-js/object-inspect/commit/68c244c5174cdd877e5dcb8ee90aa3f44b2f25be) + +## [v1.12.3](https://github.com/inspect-js/object-inspect/compare/v1.12.2...v1.12.3) - 2023-01-12 + +### Commits + +- [Fix] in eg FF 24, collections lack forEach [`75fc226`](https://github.com/inspect-js/object-inspect/commit/75fc22673c82d45f28322b1946bb0eb41b672b7f) +- [actions] update rebase action to use reusable workflow [`250a277`](https://github.com/inspect-js/object-inspect/commit/250a277a095e9dacc029ab8454dcfc15de549dcd) +- [Dev Deps] update `aud`, `es-value-fixtures`, `tape` [`66a19b3`](https://github.com/inspect-js/object-inspect/commit/66a19b3209ccc3c5ef4b34c3cb0160e65d1ce9d5) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `error-cause` [`c43d332`](https://github.com/inspect-js/object-inspect/commit/c43d3324b48384a16fd3dc444e5fc589d785bef3) +- [Tests] add `@pkgjs/support` to `postlint` [`e2618d2`](https://github.com/inspect-js/object-inspect/commit/e2618d22a7a3fa361b6629b53c1752fddc9c4d80) + +## [v1.12.2](https://github.com/inspect-js/object-inspect/compare/v1.12.1...v1.12.2) - 2022-05-26 + +### Commits + +- [Fix] use `util.inspect` for a custom inspection symbol method [`e243bf2`](https://github.com/inspect-js/object-inspect/commit/e243bf2eda6c4403ac6f1146fddb14d12e9646c1) +- [meta] add support info [`ca20ba3`](https://github.com/inspect-js/object-inspect/commit/ca20ba35713c17068ca912a86c542f5e8acb656c) +- [Fix] ignore `cause` in node v16.9 and v16.10 where it has a bug [`86aa553`](https://github.com/inspect-js/object-inspect/commit/86aa553a4a455562c2c56f1540f0bf857b9d314b) + +## [v1.12.1](https://github.com/inspect-js/object-inspect/compare/v1.12.0...v1.12.1) - 2022-05-21 + +### Commits + +- [Tests] use `mock-property` [`4ec8893`](https://github.com/inspect-js/object-inspect/commit/4ec8893ea9bfd28065ca3638cf6762424bf44352) +- [meta] use `npmignore` to autogenerate an npmignore file [`07f868c`](https://github.com/inspect-js/object-inspect/commit/07f868c10bd25a9d18686528339bb749c211fc9a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`b05244b`](https://github.com/inspect-js/object-inspect/commit/b05244b4f331e00c43b3151bc498041be77ccc91) +- [Dev Deps] update `@ljharb/eslint-config`, `error-cause`, `es-value-fixtures`, `functions-have-names`, `tape` [`d037398`](https://github.com/inspect-js/object-inspect/commit/d037398dcc5d531532e4c19c4a711ed677f579c1) +- [Fix] properly handle callable regexes in older engines [`848fe48`](https://github.com/inspect-js/object-inspect/commit/848fe48bd6dd0064ba781ee6f3c5e54a94144c37) + +## [v1.12.0](https://github.com/inspect-js/object-inspect/compare/v1.11.1...v1.12.0) - 2021-12-18 + +### Commits + +- [New] add `numericSeparator` boolean option [`2d2d537`](https://github.com/inspect-js/object-inspect/commit/2d2d537f5359a4300ce1c10241369f8024f89e11) +- [Robustness] cache more prototype methods [`191533d`](https://github.com/inspect-js/object-inspect/commit/191533da8aec98a05eadd73a5a6e979c9c8653e8) +- [New] ensure an Error’s `cause` is displayed [`53bc2ce`](https://github.com/inspect-js/object-inspect/commit/53bc2cee4e5a9cc4986f3cafa22c0685f340715e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`bc164b6`](https://github.com/inspect-js/object-inspect/commit/bc164b6e2e7d36b263970f16f54de63048b84a36) +- [Robustness] cache `RegExp.prototype.test` [`a314ab8`](https://github.com/inspect-js/object-inspect/commit/a314ab8271b905cbabc594c82914d2485a8daf12) +- [meta] fix auto-changelog settings [`5ed0983`](https://github.com/inspect-js/object-inspect/commit/5ed0983be72f73e32e2559997517a95525c7e20d) + +## [v1.11.1](https://github.com/inspect-js/object-inspect/compare/v1.11.0...v1.11.1) - 2021-12-05 + +### Commits + +- [meta] add `auto-changelog` [`7dbdd22`](https://github.com/inspect-js/object-inspect/commit/7dbdd228401d6025d8b7391476d88aee9ea9bbdf) +- [actions] reuse common workflows [`c8823bc`](https://github.com/inspect-js/object-inspect/commit/c8823bc0a8790729680709d45fb6e652432e91aa) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`7532b12`](https://github.com/inspect-js/object-inspect/commit/7532b120598307497b712890f75af8056f6d37a6) +- [Refactor] use `has-tostringtag` to behave correctly in the presence of symbol shams [`94abb5d`](https://github.com/inspect-js/object-inspect/commit/94abb5d4e745bf33253942dea86b3e538d2ff6c6) +- [actions] update codecov uploader [`5ed5102`](https://github.com/inspect-js/object-inspect/commit/5ed51025267a00e53b1341357315490ac4eb0874) +- [Dev Deps] update `eslint`, `tape` [`37b2ad2`](https://github.com/inspect-js/object-inspect/commit/37b2ad26c08d94bfd01d5d07069a0b28ef4e2ad7) +- [meta] add `sideEffects` flag [`d341f90`](https://github.com/inspect-js/object-inspect/commit/d341f905ef8bffa6a694cda6ddc5ba343532cd4f) + +## [v1.11.0](https://github.com/inspect-js/object-inspect/compare/v1.10.3...v1.11.0) - 2021-07-12 + +### Commits + +- [New] `customInspect`: add `symbol` option, to mimic modern util.inspect behavior [`e973a6e`](https://github.com/inspect-js/object-inspect/commit/e973a6e21f8140c5837cf25e9d89bdde88dc3120) +- [Dev Deps] update `eslint` [`05f1cb3`](https://github.com/inspect-js/object-inspect/commit/05f1cb3cbcfe1f238e8b51cf9bc294305b7ed793) + +## [v1.10.3](https://github.com/inspect-js/object-inspect/compare/v1.10.2...v1.10.3) - 2021-05-07 + +### Commits + +- [Fix] handle core-js Symbol shams [`4acfc2c`](https://github.com/inspect-js/object-inspect/commit/4acfc2c4b503498759120eb517abad6d51c9c5d6) +- [readme] update badges [`95c323a`](https://github.com/inspect-js/object-inspect/commit/95c323ad909d6cbabb95dd6015c190ba6db9c1f2) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud` [`cb38f48`](https://github.com/inspect-js/object-inspect/commit/cb38f485de6ec7a95109b5a9bbd0a1deba2f6611) + +## [v1.10.2](https://github.com/inspect-js/object-inspect/compare/v1.10.1...v1.10.2) - 2021-04-17 + +### Commits + +- [Fix] use a robust check for a boxed Symbol [`87f12d6`](https://github.com/inspect-js/object-inspect/commit/87f12d6e69ce530be04659c81a4cd502943acac5) + +## [v1.10.1](https://github.com/inspect-js/object-inspect/compare/v1.10.0...v1.10.1) - 2021-04-17 + +### Commits + +- [Fix] use a robust check for a boxed bigint [`d5ca829`](https://github.com/inspect-js/object-inspect/commit/d5ca8298b6d2e5c7b9334a5b21b96ed95d225c91) + +## [v1.10.0](https://github.com/inspect-js/object-inspect/compare/v1.9.0...v1.10.0) - 2021-04-17 + +### Commits + +- [Tests] increase coverage [`d8abb8a`](https://github.com/inspect-js/object-inspect/commit/d8abb8a62c2f084919df994a433b346e0d87a227) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`4bfec2e`](https://github.com/inspect-js/object-inspect/commit/4bfec2e30aaef6ddef6cbb1448306f9f8b9520b7) +- [New] respect `Symbol.toStringTag` on objects [`799b58f`](https://github.com/inspect-js/object-inspect/commit/799b58f536a45e4484633a8e9daeb0330835f175) +- [Fix] do not allow Symbol.toStringTag to masquerade as builtins [`d6c5b37`](https://github.com/inspect-js/object-inspect/commit/d6c5b37d7e94427796b82432fb0c8964f033a6ab) +- [New] add `WeakRef` support [`b6d898e`](https://github.com/inspect-js/object-inspect/commit/b6d898ee21868c780a7ee66b28532b5b34ed7f09) +- [meta] do not publish github action workflow files [`918cdfc`](https://github.com/inspect-js/object-inspect/commit/918cdfc4b6fe83f559ff6ef04fe66201e3ff5cbd) +- [meta] create `FUNDING.yml` [`0bb5fc5`](https://github.com/inspect-js/object-inspect/commit/0bb5fc516dbcd2cd728bd89cee0b580acc5ce301) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`22c8dc0`](https://github.com/inspect-js/object-inspect/commit/22c8dc0cac113d70f4781e49a950070923a671be) +- [meta] use `prepublishOnly` script for npm 7+ [`e52ee09`](https://github.com/inspect-js/object-inspect/commit/e52ee09e8050b8dbac94ef57f786675567728223) +- [Dev Deps] update `eslint` [`7c4e6fd`](https://github.com/inspect-js/object-inspect/commit/7c4e6fdedcd27cc980e13c9ad834d05a96f3d40c) + +## [v1.9.0](https://github.com/inspect-js/object-inspect/compare/v1.8.0...v1.9.0) - 2020-11-30 + +### Commits + +- [Tests] migrate tests to Github Actions [`d262251`](https://github.com/inspect-js/object-inspect/commit/d262251e13e16d3490b5473672f6b6d6ff86675d) +- [New] add enumerable own Symbols to plain object output [`ee60c03`](https://github.com/inspect-js/object-inspect/commit/ee60c033088cff9d33baa71e59a362a541b48284) +- [Tests] add passing tests [`01ac3e4`](https://github.com/inspect-js/object-inspect/commit/01ac3e4b5a30f97875a63dc9b1416b3bd626afc9) +- [actions] add "Require Allow Edits" action [`c2d7746`](https://github.com/inspect-js/object-inspect/commit/c2d774680cde4ca4af332d84d4121b26f798ba9e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `core-js` [`70058de`](https://github.com/inspect-js/object-inspect/commit/70058de1579fc54d1d15ed6c2dbe246637ce70ff) +- [Fix] hex characters in strings should be uppercased, to match node `assert` [`6ab8faa`](https://github.com/inspect-js/object-inspect/commit/6ab8faaa0abc08fe7a8e2afd8b39c6f1f0e00113) +- [Tests] run `nyc` on all tests [`4c47372`](https://github.com/inspect-js/object-inspect/commit/4c473727879ddc8e28b599202551ddaaf07b6210) +- [Tests] node 0.8 has an unpredictable property order; fix `groups` test by removing property [`f192069`](https://github.com/inspect-js/object-inspect/commit/f192069a978a3b60e6f0e0d45ac7df260ab9a778) +- [New] add enumerable properties to Function inspect result, per node’s `assert` [`fd38e1b`](https://github.com/inspect-js/object-inspect/commit/fd38e1bc3e2a1dc82091ce3e021917462eee64fc) +- [Tests] fix tests for node < 10, due to regex match `groups` [`2ac6462`](https://github.com/inspect-js/object-inspect/commit/2ac6462cc4f72eaa0b63a8cfee9aabe3008b2330) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`44b59e2`](https://github.com/inspect-js/object-inspect/commit/44b59e2676a7f825ef530dfd19dafb599e3b9456) +- [Robustness] cache `Symbol.prototype.toString` [`f3c2074`](https://github.com/inspect-js/object-inspect/commit/f3c2074d8f32faf8292587c07c9678ea931703dd) +- [Dev Deps] update `eslint` [`9411294`](https://github.com/inspect-js/object-inspect/commit/94112944b9245e3302e25453277876402d207e7f) +- [meta] `require-allow-edits` no longer requires an explicit github token [`36c0220`](https://github.com/inspect-js/object-inspect/commit/36c02205de3c2b0e84d53777c5c9fd54a36c48ab) +- [actions] update rebase checkout action to v2 [`55a39a6`](https://github.com/inspect-js/object-inspect/commit/55a39a64e944f19c6a7d8efddf3df27700f20d14) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`f59fd3c`](https://github.com/inspect-js/object-inspect/commit/f59fd3cf406c3a7c7ece140904a80bbc6bacfcca) +- [Dev Deps] update `eslint` [`a492bec`](https://github.com/inspect-js/object-inspect/commit/a492becec644b0155c9c4bc1caf6f9fac11fb2c7) + +## [v1.8.0](https://github.com/inspect-js/object-inspect/compare/v1.7.0...v1.8.0) - 2020-06-18 + +### Fixed + +- [New] add `indent` option [`#27`](https://github.com/inspect-js/object-inspect/issues/27) + +### Commits + +- [Tests] add codecov [`4324cbb`](https://github.com/inspect-js/object-inspect/commit/4324cbb1a2bd7710822a4151ff373570db22453e) +- [New] add `maxStringLength` option [`b3995cb`](https://github.com/inspect-js/object-inspect/commit/b3995cb71e15b5ee127a3094c43994df9d973502) +- [New] add `customInspect` option, to disable custom inspect methods [`28b9179`](https://github.com/inspect-js/object-inspect/commit/28b9179ee802bb3b90810100c11637db90c2fb6d) +- [Tests] add Date and RegExp tests [`3b28eca`](https://github.com/inspect-js/object-inspect/commit/3b28eca57b0367aeadffac604ea09e8bdae7d97b) +- [actions] add automatic rebasing / merge commit blocking [`0d9c6c0`](https://github.com/inspect-js/object-inspect/commit/0d9c6c044e83475ff0bfffb9d35b149834c83a2e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape`; add `aud` [`7c204f2`](https://github.com/inspect-js/object-inspect/commit/7c204f22b9e41bc97147f4d32d4cb045b17769a6) +- [readme] fix repo URLs, remove testling [`34ca9a0`](https://github.com/inspect-js/object-inspect/commit/34ca9a0dabfe75bd311f806a326fadad029909a3) +- [Fix] when truncating a deep array, note it as `[Array]` instead of just `[Object]` [`f74c82d`](https://github.com/inspect-js/object-inspect/commit/f74c82dd0b35386445510deb250f34c41be3ec0e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`1a8a5ea`](https://github.com/inspect-js/object-inspect/commit/1a8a5ea069ea2bee89d77caedad83ffa23d35711) +- [Fix] do not be fooled by a function’s own `toString` method [`7cb5c65`](https://github.com/inspect-js/object-inspect/commit/7cb5c657a976f94715c19c10556a30f15bb7d5d7) +- [patch] indicate explicitly that anon functions are anonymous, to match node [`81ebdd4`](https://github.com/inspect-js/object-inspect/commit/81ebdd4215005144074bbdff3f6bafa01407910a) +- [Dev Deps] loosen the `core-js` dep [`e7472e8`](https://github.com/inspect-js/object-inspect/commit/e7472e8e242117670560bd995830c2a4d12080f5) +- [Dev Deps] update `tape` [`699827e`](https://github.com/inspect-js/object-inspect/commit/699827e6b37258b5203c33c78c009bf4b0e6a66d) +- [meta] add `safe-publish-latest` [`c5d2868`](https://github.com/inspect-js/object-inspect/commit/c5d2868d6eb33c472f37a20f89ceef2787046088) +- [Dev Deps] update `@ljharb/eslint-config` [`9199501`](https://github.com/inspect-js/object-inspect/commit/919950195d486114ccebacbdf9d74d7f382693b0) + +## [v1.7.0](https://github.com/inspect-js/object-inspect/compare/v1.6.0...v1.7.0) - 2019-11-10 + +### Commits + +- [Tests] use shared travis-ci configs [`19899ed`](https://github.com/inspect-js/object-inspect/commit/19899edbf31f4f8809acf745ce34ad1ce1bfa63b) +- [Tests] add linting [`a00f057`](https://github.com/inspect-js/object-inspect/commit/a00f057d917f66ea26dd37769c6b810ec4af97e8) +- [Tests] lint last file [`2698047`](https://github.com/inspect-js/object-inspect/commit/2698047b58af1e2e88061598ef37a75f228dddf6) +- [Tests] up to `node` `v12.7`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`589e87a`](https://github.com/inspect-js/object-inspect/commit/589e87a99cadcff4b600e6a303418e9d922836e8) +- [New] add support for `WeakMap` and `WeakSet` [`3ddb3e4`](https://github.com/inspect-js/object-inspect/commit/3ddb3e4e0c8287130c61a12e0ed9c104b1549306) +- [meta] clean up license so github can detect it properly [`27527bb`](https://github.com/inspect-js/object-inspect/commit/27527bb801520c9610c68cc3b55d6f20a2bee56d) +- [Tests] cover `util.inspect.custom` [`36d47b9`](https://github.com/inspect-js/object-inspect/commit/36d47b9c59056a57ef2f1491602c726359561800) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape` [`b614eaa`](https://github.com/inspect-js/object-inspect/commit/b614eaac901da0e5c69151f534671f990a94cace) +- [Tests] fix coverage thresholds [`7b7b176`](https://github.com/inspect-js/object-inspect/commit/7b7b176e15f8bd6e8b2f261ff5a493c2fe78d9c2) +- [Tests] bigint tests now can run on unflagged node [`063af31`](https://github.com/inspect-js/object-inspect/commit/063af31ce9cd13c202e3b67c07ba06dc9b7c0f81) +- [Refactor] add early bailout to `isMap` and `isSet` checks [`fc51047`](https://github.com/inspect-js/object-inspect/commit/fc5104714a3671d37e225813db79470d6335683b) +- [meta] add `funding` field [`7f9953a`](https://github.com/inspect-js/object-inspect/commit/7f9953a113eec7b064a6393cf9f90ba15f1d131b) +- [Tests] Fix invalid strict-mode syntax with hexadecimal [`a8b5425`](https://github.com/inspect-js/object-inspect/commit/a8b542503b4af1599a275209a1a99f5fdedb1ead) +- [Dev Deps] update `@ljharb/eslint-config` [`98df157`](https://github.com/inspect-js/object-inspect/commit/98df1577314d9188a3fc3f17fdcf2fba697ae1bd) +- add copyright to LICENSE [`bb69fd0`](https://github.com/inspect-js/object-inspect/commit/bb69fd017a062d299e44da1f9b2c7dcd67f621e6) +- [Tests] use `npx aud` in `posttest` [`4838353`](https://github.com/inspect-js/object-inspect/commit/4838353593974cf7f905b9ef04c03c094f0cdbe2) +- [Tests] move `0.6` to allowed failures, because it won‘t build on travis [`1bff32a`](https://github.com/inspect-js/object-inspect/commit/1bff32aa52e8aea687f0856b28ba754b3e43ebf7) + +## [v1.6.0](https://github.com/inspect-js/object-inspect/compare/v1.5.0...v1.6.0) - 2018-05-02 + +### Commits + +- [New] add support for boxed BigInt primitives [`356c66a`](https://github.com/inspect-js/object-inspect/commit/356c66a410e7aece7162c8319880a5ef647beaa9) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9` [`c77b65b`](https://github.com/inspect-js/object-inspect/commit/c77b65bba593811b906b9ec57561c5cba92e2db3) +- [New] Add support for upcoming `BigInt` [`1ac548e`](https://github.com/inspect-js/object-inspect/commit/1ac548e4b27e26466c28c9a5e63e5d4e0591c31f) +- [Tests] run bigint tests in CI with --harmony-bigint flag [`d31b738`](https://github.com/inspect-js/object-inspect/commit/d31b73831880254b5c6cf5691cda9a149fbc5f04) +- [Dev Deps] update `core-js`, `tape` [`ff9eff6`](https://github.com/inspect-js/object-inspect/commit/ff9eff67113341ee1aaf80c1c22d683f43bfbccf) +- [Docs] fix example to use `safer-buffer` [`48cae12`](https://github.com/inspect-js/object-inspect/commit/48cae12a73ec6cacc955175bc56bbe6aee6a211f) + +## [v1.5.0](https://github.com/inspect-js/object-inspect/compare/v1.4.1...v1.5.0) - 2017-12-25 + +### Commits + +- [New] add `quoteStyle` option [`f5a72d2`](https://github.com/inspect-js/object-inspect/commit/f5a72d26edb3959b048f74c056ca7100a6b091e4) +- [Tests] add more test coverage [`30ebe4e`](https://github.com/inspect-js/object-inspect/commit/30ebe4e1fa943b99ecbb85be7614256d536e2759) +- [Tests] require 0.6 to pass [`99a008c`](https://github.com/inspect-js/object-inspect/commit/99a008ccace189a60fd7da18bf00e32c9572b980) + +## [v1.4.1](https://github.com/inspect-js/object-inspect/compare/v1.4.0...v1.4.1) - 2017-12-19 + +### Commits + +- [Tests] up to `node` `v9.3`, `v8.9`, `v6.12` [`6674476`](https://github.com/inspect-js/object-inspect/commit/6674476cc56acaac1bde96c84fed5ef631911906) +- [Fix] `inspect(Object(-0))` should be “Object(-0)”, not “Object(0)” [`d0a031f`](https://github.com/inspect-js/object-inspect/commit/d0a031f1cbb3024ee9982bfe364dd18a7e4d1bd3) + +## [v1.4.0](https://github.com/inspect-js/object-inspect/compare/v1.3.0...v1.4.0) - 2017-10-24 + +### Commits + +- [Tests] add `npm run coverage` [`3b48fb2`](https://github.com/inspect-js/object-inspect/commit/3b48fb25db037235eeb808f0b2830aad7aa36f70) +- [Tests] remove commented-out osx builds [`71e24db`](https://github.com/inspect-js/object-inspect/commit/71e24db8ad6ee3b9b381c5300b0475f2ba595a73) +- [New] add support for `util.inspect.custom`, in node only. [`20cca77`](https://github.com/inspect-js/object-inspect/commit/20cca7762d7e17f15b21a90793dff84acce155df) +- [Tests] up to `node` `v8.6`; use `nvm install-latest-npm` to ensure new npm doesn’t break old node [`252952d`](https://github.com/inspect-js/object-inspect/commit/252952d230d8065851dd3d4d5fe8398aae068529) +- [Tests] up to `node` `v8.8` [`4aa868d`](https://github.com/inspect-js/object-inspect/commit/4aa868d3a62914091d489dd6ec6eed194ee67cd3) +- [Dev Deps] update `core-js`, `tape` [`59483d1`](https://github.com/inspect-js/object-inspect/commit/59483d1df418f852f51fa0db7b24aa6b0209a27a) + +## [v1.3.0](https://github.com/inspect-js/object-inspect/compare/v1.2.2...v1.3.0) - 2017-07-31 + +### Fixed + +- [Fix] Map/Set: work around core-js bug < v2.5.0 [`#9`](https://github.com/inspect-js/object-inspect/issues/9) + +### Commits + +- [New] add support for arrays with additional object keys [`0d19937`](https://github.com/inspect-js/object-inspect/commit/0d199374ee37959e51539616666f420ccb29acb9) +- [Tests] up to `node` `v8.2`, `v7.10`, `v6.11`; fix new npm breaking on older nodes [`e24784a`](https://github.com/inspect-js/object-inspect/commit/e24784a90c49117787157a12a63897c49cf89bbb) +- Only apps should have lockfiles [`c6faebc`](https://github.com/inspect-js/object-inspect/commit/c6faebcb2ee486a889a4a1c4d78c0776c7576185) +- [Dev Deps] update `tape` [`7345a0a`](https://github.com/inspect-js/object-inspect/commit/7345a0aeba7e91b888a079c10004d17696a7f586) + +## [v1.2.2](https://github.com/inspect-js/object-inspect/compare/v1.2.1...v1.2.2) - 2017-03-24 + +### Commits + +- [Tests] up to `node` `v7.7`, `v6.10`, `v4.8`; improve test matrix [`a2ddc15`](https://github.com/inspect-js/object-inspect/commit/a2ddc15a1f2c65af18076eea1c0eb9cbceb478a0) +- [Tests] up to `node` `v7.0`, `v6.9`, `v5.12`, `v4.6`, `io.js` `v3.3`; improve test matrix [`a48949f`](https://github.com/inspect-js/object-inspect/commit/a48949f6b574b2d4d2298109d8e8d0eb3e7a83e7) +- [Performance] check for primitive types as early as possible. [`3b8092a`](https://github.com/inspect-js/object-inspect/commit/3b8092a2a4deffd0575f94334f00194e2d48dad3) +- [Refactor] remove unneeded `else`s. [`7255034`](https://github.com/inspect-js/object-inspect/commit/725503402e08de4f96f6bf2d8edef44ac36f26b6) +- [Refactor] avoid recreating `lowbyte` function every time. [`81edd34`](https://github.com/inspect-js/object-inspect/commit/81edd3475bd15bdd18e84de7472033dcf5004aaa) +- [Fix] differentiate -0 from 0 [`521d345`](https://github.com/inspect-js/object-inspect/commit/521d3456b009da7bf1c5785c8a9df5a9f8718264) +- [Refactor] move object key gathering into separate function [`aca6265`](https://github.com/inspect-js/object-inspect/commit/aca626536eaeef697196c6e9db3e90e7e0355b6a) +- [Refactor] consolidate wrapping logic for boxed primitives into a function. [`4e440cd`](https://github.com/inspect-js/object-inspect/commit/4e440cd9065df04802a2a1dead03f48c353ca301) +- [Robustness] use `typeof` instead of comparing to literal `undefined` [`5ca6f60`](https://github.com/inspect-js/object-inspect/commit/5ca6f601937506daff8ed2fcf686363b55807b69) +- [Refactor] consolidate Map/Set notations. [`4e576e5`](https://github.com/inspect-js/object-inspect/commit/4e576e5d7ed2f9ec3fb7f37a0d16732eb10758a9) +- [Tests] ensure that this function remains anonymous, despite ES6 name inference. [`7540ae5`](https://github.com/inspect-js/object-inspect/commit/7540ae591278756db614fa4def55ca413150e1a3) +- [Refactor] explicitly coerce Error objects to strings. [`7f4ca84`](https://github.com/inspect-js/object-inspect/commit/7f4ca8424ee8dc2c0ca5a422d94f7fac40327261) +- [Refactor] split up `var` declarations for debuggability [`6f2c11e`](https://github.com/inspect-js/object-inspect/commit/6f2c11e6a85418586a00292dcec5e97683f89bc3) +- [Robustness] cache `Object.prototype.toString` [`df44a20`](https://github.com/inspect-js/object-inspect/commit/df44a20adfccf31529d60d1df2079bfc3c836e27) +- [Dev Deps] update `tape` [`3ec714e`](https://github.com/inspect-js/object-inspect/commit/3ec714eba57bc3f58a6eb4fca1376f49e70d300a) +- [Dev Deps] update `tape` [`beb72d9`](https://github.com/inspect-js/object-inspect/commit/beb72d969653747d7cde300393c28755375329b0) + +## [v1.2.1](https://github.com/inspect-js/object-inspect/compare/v1.2.0...v1.2.1) - 2016-04-09 + +### Fixed + +- [Fix] fix Boolean `false` object inspection. [`#7`](https://github.com/substack/object-inspect/pull/7) + +## [v1.2.0](https://github.com/inspect-js/object-inspect/compare/v1.1.0...v1.2.0) - 2016-04-09 + +### Fixed + +- [New] add support for inspecting String/Number/Boolean objects. [`#6`](https://github.com/inspect-js/object-inspect/issues/6) + +### Commits + +- [Dev Deps] update `tape` [`742caa2`](https://github.com/inspect-js/object-inspect/commit/742caa262cf7af4c815d4821c8bd0129c1446432) + +## [v1.1.0](https://github.com/inspect-js/object-inspect/compare/1.0.2...v1.1.0) - 2015-12-14 + +### Merged + +- [New] add ES6 Map/Set support. [`#4`](https://github.com/inspect-js/object-inspect/pull/4) + +### Fixed + +- [New] add ES6 Map/Set support. [`#3`](https://github.com/inspect-js/object-inspect/issues/3) + +### Commits + +- Update `travis.yml` to test on bunches of `iojs` and `node` versions. [`4c1fd65`](https://github.com/inspect-js/object-inspect/commit/4c1fd65cc3bd95307e854d114b90478324287fd2) +- [Dev Deps] update `tape` [`88a907e`](https://github.com/inspect-js/object-inspect/commit/88a907e33afbe408e4b5d6e4e42a33143f88848c) + +## [1.0.2](https://github.com/inspect-js/object-inspect/compare/1.0.1...1.0.2) - 2015-08-07 + +### Commits + +- [Fix] Cache `Object.prototype.hasOwnProperty` in case it's deleted later. [`1d0075d`](https://github.com/inspect-js/object-inspect/commit/1d0075d3091dc82246feeb1f9871cb2b8ed227b3) +- [Dev Deps] Update `tape` [`ca8d5d7`](https://github.com/inspect-js/object-inspect/commit/ca8d5d75635ddbf76f944e628267581e04958457) +- gitignore node_modules since this is a reusable modules. [`ed41407`](https://github.com/inspect-js/object-inspect/commit/ed41407811743ca530cdeb28f982beb96026af82) + +## [1.0.1](https://github.com/inspect-js/object-inspect/compare/1.0.0...1.0.1) - 2015-07-19 + +### Commits + +- Make `inspect` work with symbol primitives and objects, including in node 0.11 and 0.12. [`ddf1b94`](https://github.com/inspect-js/object-inspect/commit/ddf1b94475ab951f1e3bccdc0a48e9073cfbfef4) +- bump tape [`103d674`](https://github.com/inspect-js/object-inspect/commit/103d67496b504bdcfdd765d303a773f87ec106e2) +- use newer travis config [`d497276`](https://github.com/inspect-js/object-inspect/commit/d497276c1da14234bb5098a59cf20de75fbc316a) + +## [1.0.0](https://github.com/inspect-js/object-inspect/compare/0.4.0...1.0.0) - 2014-08-05 + +### Commits + +- error inspect works properly [`260a22d`](https://github.com/inspect-js/object-inspect/commit/260a22d134d3a8a482c67d52091c6040c34f4299) +- seen coverage [`57269e8`](https://github.com/inspect-js/object-inspect/commit/57269e8baa992a7439047f47325111fdcbcb8417) +- htmlelement instance coverage [`397ffe1`](https://github.com/inspect-js/object-inspect/commit/397ffe10a1980350868043ef9de65686d438979f) +- more element coverage [`6905cc2`](https://github.com/inspect-js/object-inspect/commit/6905cc2f7df35600177e613b0642b4df5efd3eca) +- failing test for type errors [`385b615`](https://github.com/inspect-js/object-inspect/commit/385b6152e49b51b68449a662f410b084ed7c601a) +- fn name coverage [`edc906d`](https://github.com/inspect-js/object-inspect/commit/edc906d40fca6b9194d304062c037ee8e398c4c2) +- server-side element test [`362d1d3`](https://github.com/inspect-js/object-inspect/commit/362d1d3e86f187651c29feeb8478110afada385b) +- custom inspect fn [`e89b0f6`](https://github.com/inspect-js/object-inspect/commit/e89b0f6fe6d5e03681282af83732a509160435a6) +- fixed browser test [`b530882`](https://github.com/inspect-js/object-inspect/commit/b5308824a1c8471c5617e394766a03a6977102a9) +- depth test, matches node [`1cfd9e0`](https://github.com/inspect-js/object-inspect/commit/1cfd9e0285a4ae1dff44101ad482915d9bf47e48) +- exercise hasOwnProperty path [`8d753fb`](https://github.com/inspect-js/object-inspect/commit/8d753fb362a534fa1106e4d80f2ee9bea06a66d9) +- more cases covered for errors [`c5c46a5`](https://github.com/inspect-js/object-inspect/commit/c5c46a569ec4606583497e8550f0d8c7ad39a4a4) +- \W obj key test case [`b0eceee`](https://github.com/inspect-js/object-inspect/commit/b0eceeea6e0eb94d686c1046e99b9e25e5005f75) +- coverage for explicit depth param [`e12b91c`](https://github.com/inspect-js/object-inspect/commit/e12b91cd59683362f3a0e80f46481a0211e26c15) + +## [0.4.0](https://github.com/inspect-js/object-inspect/compare/0.3.1...0.4.0) - 2014-03-21 + +### Commits + +- passing lowbyte interpolation test [`b847511`](https://github.com/inspect-js/object-inspect/commit/b8475114f5def7e7961c5353d48d3d8d9a520985) +- lowbyte test [`4a2b0e1`](https://github.com/inspect-js/object-inspect/commit/4a2b0e142667fc933f195472759385ac08f3946c) + +## [0.3.1](https://github.com/inspect-js/object-inspect/compare/0.3.0...0.3.1) - 2014-03-04 + +### Commits + +- sort keys [`a07b19c`](https://github.com/inspect-js/object-inspect/commit/a07b19cc3b1521a82d4fafb6368b7a9775428a05) + +## [0.3.0](https://github.com/inspect-js/object-inspect/compare/0.2.0...0.3.0) - 2014-03-04 + +### Commits + +- [] and {} instead of [ ] and { } [`654c44b`](https://github.com/inspect-js/object-inspect/commit/654c44b2865811f3519e57bb8526e0821caf5c6b) + +## [0.2.0](https://github.com/inspect-js/object-inspect/compare/0.1.3...0.2.0) - 2014-03-04 + +### Commits + +- failing holes test [`99cdfad`](https://github.com/inspect-js/object-inspect/commit/99cdfad03c6474740275a75636fe6ca86c77737a) +- regex already work [`e324033`](https://github.com/inspect-js/object-inspect/commit/e324033267025995ec97d32ed0a65737c99477a6) +- failing undef/null test [`1f88a00`](https://github.com/inspect-js/object-inspect/commit/1f88a00265d3209719dda8117b7e6360b4c20943) +- holes in the all example [`7d345f3`](https://github.com/inspect-js/object-inspect/commit/7d345f3676dcbe980cff89a4f6c243269ebbb709) +- check for .inspect(), fixes Buffer use-case [`c3f7546`](https://github.com/inspect-js/object-inspect/commit/c3f75466dbca125347d49847c05262c292f12b79) +- fixes for holes [`ce25f73`](https://github.com/inspect-js/object-inspect/commit/ce25f736683de4b92ff27dc5471218415e2d78d8) +- weird null behavior [`405c1ea`](https://github.com/inspect-js/object-inspect/commit/405c1ea72cd5a8cf3b498c3eaa903d01b9fbcab5) +- tape is actually a devDependency, upgrade [`703b0ce`](https://github.com/inspect-js/object-inspect/commit/703b0ce6c5817b4245a082564bccd877e0bb6990) +- put date in the example [`a342219`](https://github.com/inspect-js/object-inspect/commit/a3422190eeaa013215f46df2d0d37b48595ac058) +- passing the null test [`4ab737e`](https://github.com/inspect-js/object-inspect/commit/4ab737ebf862a75d247ebe51e79307a34d6380d4) + +## [0.1.3](https://github.com/inspect-js/object-inspect/compare/0.1.1...0.1.3) - 2013-07-26 + +### Commits + +- special isElement() check [`882768a`](https://github.com/inspect-js/object-inspect/commit/882768a54035d30747be9de1baf14e5aa0daa128) +- oh right old IEs don't have indexOf either [`36d1275`](https://github.com/inspect-js/object-inspect/commit/36d12756c38b08a74370b0bb696c809e529913a5) + +## [0.1.1](https://github.com/inspect-js/object-inspect/compare/0.1.0...0.1.1) - 2013-07-26 + +### Commits + +- tests! [`4422fd9`](https://github.com/inspect-js/object-inspect/commit/4422fd95532c2745aa6c4f786f35f1090be29998) +- fix for ie<9, doesn't have hasOwnProperty [`6b7d611`](https://github.com/inspect-js/object-inspect/commit/6b7d61183050f6da801ea04473211da226482613) +- fix for all IEs: no f.name [`4e0c2f6`](https://github.com/inspect-js/object-inspect/commit/4e0c2f6dfd01c306d067d7163319acc97c94ee50) +- badges [`5ed0d88`](https://github.com/inspect-js/object-inspect/commit/5ed0d88e4e407f9cb327fa4a146c17921f9680f3) + +## [0.1.0](https://github.com/inspect-js/object-inspect/compare/0.0.0...0.1.0) - 2013-07-26 + +### Commits + +- [Function] for functions [`ad5c485`](https://github.com/inspect-js/object-inspect/commit/ad5c485098fc83352cb540a60b2548ca56820e0b) + +## 0.0.0 - 2013-07-26 + +### Commits + +- working browser example [`34be6b6`](https://github.com/inspect-js/object-inspect/commit/34be6b6548f9ce92bdc3c27572857ba0c4a1218d) +- package.json etc [`cad51f2`](https://github.com/inspect-js/object-inspect/commit/cad51f23fc6bcf1a456ed6abe16088256c2f632f) +- docs complete [`b80cce2`](https://github.com/inspect-js/object-inspect/commit/b80cce2490c4e7183a9ee11ea89071f0abec4446) +- circular example [`4b4a7b9`](https://github.com/inspect-js/object-inspect/commit/4b4a7b92209e4e6b4630976cb6bcd17d14165a59) +- string rep [`7afb479`](https://github.com/inspect-js/object-inspect/commit/7afb479baa798d27f09e0a178b72ea327f60f5c8) diff --git a/node_modules/object-inspect/LICENSE b/node_modules/object-inspect/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ca64cc1e605205438cc1b04b215f6fc12ab3f039 --- /dev/null +++ b/node_modules/object-inspect/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 James Halliday + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/object-inspect/example/all.js b/node_modules/object-inspect/example/all.js new file mode 100644 index 0000000000000000000000000000000000000000..2f3355c509acd1a0e9d409f9e655939d6d18c2ec --- /dev/null +++ b/node_modules/object-inspect/example/all.js @@ -0,0 +1,23 @@ +'use strict'; + +var inspect = require('../'); +var Buffer = require('safer-buffer').Buffer; + +var holes = ['a', 'b']; +holes[4] = 'e'; +holes[6] = 'g'; + +var obj = { + a: 1, + b: [3, 4, undefined, null], + c: undefined, + d: null, + e: { + regex: /^x/i, + buf: Buffer.from('abc'), + holes: holes + }, + now: new Date() +}; +obj.self = obj; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/circular.js b/node_modules/object-inspect/example/circular.js new file mode 100644 index 0000000000000000000000000000000000000000..487a7c169d0df8c4acb6ad02b26ce76175ecfc0f --- /dev/null +++ b/node_modules/object-inspect/example/circular.js @@ -0,0 +1,6 @@ +'use strict'; + +var inspect = require('../'); +var obj = { a: 1, b: [3, 4] }; +obj.c = obj; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/fn.js b/node_modules/object-inspect/example/fn.js new file mode 100644 index 0000000000000000000000000000000000000000..9b5db8de036ffc6718969bee9193de36409235aa --- /dev/null +++ b/node_modules/object-inspect/example/fn.js @@ -0,0 +1,5 @@ +'use strict'; + +var inspect = require('../'); +var obj = [1, 2, function f(n) { return n + 5; }, 4]; +console.log(inspect(obj)); diff --git a/node_modules/object-inspect/example/inspect.js b/node_modules/object-inspect/example/inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..e2df7c9f471356c48f14e7af2813119ffb6854bb --- /dev/null +++ b/node_modules/object-inspect/example/inspect.js @@ -0,0 +1,10 @@ +'use strict'; + +/* eslint-env browser */ +var inspect = require('../'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }])); diff --git a/node_modules/object-inspect/index.js b/node_modules/object-inspect/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a4b2d4cd850adb5cda64eb9e5692457a73c0947e --- /dev/null +++ b/node_modules/object-inspect/index.js @@ -0,0 +1,544 @@ +var hasMap = typeof Map === 'function' && Map.prototype; +var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; +var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; +var mapForEach = hasMap && Map.prototype.forEach; +var hasSet = typeof Set === 'function' && Set.prototype; +var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; +var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; +var setForEach = hasSet && Set.prototype.forEach; +var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; +var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; +var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; +var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; +var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; +var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; +var booleanValueOf = Boolean.prototype.valueOf; +var objectToString = Object.prototype.toString; +var functionToString = Function.prototype.toString; +var $match = String.prototype.match; +var $slice = String.prototype.slice; +var $replace = String.prototype.replace; +var $toUpperCase = String.prototype.toUpperCase; +var $toLowerCase = String.prototype.toLowerCase; +var $test = RegExp.prototype.test; +var $concat = Array.prototype.concat; +var $join = Array.prototype.join; +var $arrSlice = Array.prototype.slice; +var $floor = Math.floor; +var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; +var gOPS = Object.getOwnPropertySymbols; +var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; +var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; +// ie, `has-tostringtag/shams +var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') + ? Symbol.toStringTag + : null; +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( + [].__proto__ === Array.prototype // eslint-disable-line no-proto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null +); + +function addNumericSeparator(num, str) { + if ( + num === Infinity + || num === -Infinity + || num !== num + || (num && num > -1000 && num < 1000) + || $test.call(/e/, str) + ) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); +} + +var utilInspect = require('./util.inspect'); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + +var quotes = { + __proto__: null, + 'double': '"', + single: "'" +}; +var quoteREs = { + __proto__: null, + 'double': /(["\\])/g, + single: /(['\\])/g +}; + +module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + + if (has(opts, 'quoteStyle') && !has(quotes, opts.quoteStyle)) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if ( + has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' + ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity + : opts.maxStringLength !== null + ) + ) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } + + if ( + has(opts, 'indent') + && opts.indent !== null + && opts.indent !== '\t' + && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) + ) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { depth = 0; } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray(obj) ? '[Array]' : '[Object]'; + } + + var indent = getIndent(opts, depth); + + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { s += '...'; } + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { return '[]'; } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { return '[' + String(obj) + ']'; } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + } + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + // note: in IE 8, sometimes `global !== window` but both are the prototypes of each other + /* eslint-env browser */ + if (typeof window !== 'undefined' && obj === window) { + return '{ [object Window] }'; + } + if ( + (typeof globalThis !== 'undefined' && obj === globalThis) + || (typeof global !== 'undefined' && obj === global) + ) { + return '{ [object globalThis] }'; + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { return tag + '{}'; } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); +}; + +function wrapQuotes(s, defaultStyle, opts) { + var style = opts.quoteStyle || defaultStyle; + var quoteChar = quotes[style]; + return quoteChar + s + quoteChar; +} + +function quote(s) { + return $replace.call(String(s), /"/g, '"'); +} + +function canTrustToString(obj) { + return !toStringTag || !(typeof obj === 'object' && (toStringTag in obj || typeof obj[toStringTag] !== 'undefined')); +} +function isArray(obj) { return toStr(obj) === '[object Array]' && canTrustToString(obj); } +function isDate(obj) { return toStr(obj) === '[object Date]' && canTrustToString(obj); } +function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && canTrustToString(obj); } +function isError(obj) { return toStr(obj) === '[object Error]' && canTrustToString(obj); } +function isString(obj) { return toStr(obj) === '[object String]' && canTrustToString(obj); } +function isNumber(obj) { return toStr(obj) === '[object Number]' && canTrustToString(obj); } +function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && canTrustToString(obj); } + +// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives +function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; +} + +function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; +} + +var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; +function has(obj, key) { + return hasOwn.call(obj, key); +} + +function toStr(obj) { + return objectToString.call(obj); +} + +function nameOf(f) { + if (f.name) { return f.name; } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { return m[1]; } + return null; +} + +function indexOf(xs, x) { + if (xs.indexOf) { return xs.indexOf(x); } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { return i; } + } + return -1; +} + +function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; +} + +function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isElement(x) { + if (!x || typeof x !== 'object') { return false; } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; +} + +function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + var quoteRE = quoteREs[opts.quoteStyle || 'single']; + quoteRE.lastIndex = 0; + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, quoteRE, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} + +function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { return '\\' + x; } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); +} + +function markBoxed(str) { + return 'Object(' + str + ')'; +} + +function weakCollectionOf(type) { + return type + ' { ? }'; +} + +function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; +} + +function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; +} + +function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; +} + +function indentedJoin(xs, indent) { + if (xs.length === 0) { return ''; } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; +} + +function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; +} diff --git a/node_modules/object-inspect/package-support.json b/node_modules/object-inspect/package-support.json new file mode 100644 index 0000000000000000000000000000000000000000..5cc12d0585a386018d3c486be5a841d8377d15db --- /dev/null +++ b/node_modules/object-inspect/package-support.json @@ -0,0 +1,20 @@ +{ + "versions": [ + { + "version": "*", + "target": { + "node": "all" + }, + "response": { + "type": "time-permitting" + }, + "backing": { + "npm-funding": true, + "donations": [ + "https://github.com/ljharb", + "https://tidelift.com/funding/github/npm/object-inspect" + ] + } + } + ] +} diff --git a/node_modules/object-inspect/package.json b/node_modules/object-inspect/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9fd97ff7523f106de04c47adf74aa3a36db8dbbd --- /dev/null +++ b/node_modules/object-inspect/package.json @@ -0,0 +1,105 @@ +{ + "name": "object-inspect", + "version": "1.13.4", + "description": "string representations of objects in node and the browser", + "main": "index.js", + "sideEffects": false, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.1", + "@pkgjs/support": "^0.0.6", + "auto-changelog": "^2.5.0", + "core-js": "^2.6.12", + "error-cause": "^1.0.8", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "for-each": "^0.3.4", + "functions-have-names": "^1.2.3", + "glob": "=10.3.7", + "globalthis": "^1.0.4", + "has-symbols": "^1.1.0", + "has-tostringtag": "^1.0.2", + "in-publish": "^2.0.1", + "jackspeak": "=2.1.1", + "make-arrow-function": "^1.2.0", + "mock-property": "^1.1.0", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "safer-buffer": "^2.1.2", + "semver": "^6.3.1", + "string.prototype.repeat": "^1.0.0", + "tape": "^5.9.0" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "lint": "eslint --ext=js,mjs .", + "postlint": "npx @pkgjs/support validate", + "test": "npm run tests-only && npm run test:corejs", + "tests-only": "nyc tape 'test/*.js'", + "test:corejs": "nyc tape test-core-js.js 'test/*.js'", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "testling": { + "files": [ + "test/*.js", + "test/browser/*.js" + ], + "browsers": [ + "ie/6..latest", + "chrome/latest", + "firefox/latest", + "safari/latest", + "opera/latest", + "iphone/latest", + "ipad/latest", + "android/latest" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/object-inspect.git" + }, + "homepage": "https://github.com/inspect-js/object-inspect", + "keywords": [ + "inspect", + "util.inspect", + "object", + "stringify", + "pretty" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "browser": { + "./util.inspect.js": false + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "./test-core-js.js" + ] + }, + "support": true, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/object-inspect/readme.markdown b/node_modules/object-inspect/readme.markdown new file mode 100644 index 0000000000000000000000000000000000000000..f91617df32a3c8b9ffa23300ad26ca918bca13aa --- /dev/null +++ b/node_modules/object-inspect/readme.markdown @@ -0,0 +1,84 @@ +# object-inspect [![Version Badge][npm-version-svg]][package-url] + +string representations of objects in node and the browser + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +# example + +## circular + +``` js +var inspect = require('object-inspect'); +var obj = { a: 1, b: [3,4] }; +obj.c = obj; +console.log(inspect(obj)); +``` + +## dom element + +``` js +var inspect = require('object-inspect'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ])); +``` + +output: + +``` +[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [ ... ] ] ] ] } ] +``` + +# methods + +``` js +var inspect = require('object-inspect') +``` + +## var s = inspect(obj, opts={}) + +Return a string `s` with the string representation of `obj` up to a depth of `opts.depth`. + +Additional options: + - `quoteStyle`: must be "single" or "double", if present. Default `'single'` for strings, `'double'` for HTML elements. + - `maxStringLength`: must be `0`, a positive integer, `Infinity`, or `null`, if present. Default `Infinity`. + - `customInspect`: When `true`, a custom inspect method function will be invoked (either undere the `util.inspect.custom` symbol, or the `inspect` property). When the string `'symbol'`, only the symbol method will be invoked. Default `true`. + - `indent`: must be "\t", `null`, or a positive integer. Default `null`. + - `numericSeparator`: must be a boolean, if present. Default `false`. If `true`, all numbers will be printed with numeric separators (eg, `1234.5678` will be printed as `'1_234.567_8'`) + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install object-inspect +``` + +# license + +MIT + +[package-url]: https://npmjs.org/package/object-inspect +[npm-version-svg]: https://versionbadg.es/inspect-js/object-inspect.svg +[deps-svg]: https://david-dm.org/inspect-js/object-inspect.svg +[deps-url]: https://david-dm.org/inspect-js/object-inspect +[dev-deps-svg]: https://david-dm.org/inspect-js/object-inspect/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/object-inspect#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/object-inspect.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/object-inspect.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/object-inspect.svg +[downloads-url]: https://npm-stat.com/charts.html?package=object-inspect +[codecov-image]: https://codecov.io/gh/inspect-js/object-inspect/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/object-inspect/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/object-inspect +[actions-url]: https://github.com/inspect-js/object-inspect/actions diff --git a/node_modules/object-inspect/test-core-js.js b/node_modules/object-inspect/test-core-js.js new file mode 100644 index 0000000000000000000000000000000000000000..e53c40022533f691fd17d623cd24a8ecb5a82669 --- /dev/null +++ b/node_modules/object-inspect/test-core-js.js @@ -0,0 +1,26 @@ +'use strict'; + +require('core-js'); + +var inspect = require('./'); +var test = require('tape'); + +test('Maps', function (t) { + t.equal(inspect(new Map([[1, 2]])), 'Map (1) {1 => 2}'); + t.end(); +}); + +test('WeakMaps', function (t) { + t.equal(inspect(new WeakMap([[{}, 2]])), 'WeakMap { ? }'); + t.end(); +}); + +test('Sets', function (t) { + t.equal(inspect(new Set([[1, 2]])), 'Set (1) {[ 1, 2 ]}'); + t.end(); +}); + +test('WeakSets', function (t) { + t.equal(inspect(new WeakSet([[1, 2]])), 'WeakSet { ? }'); + t.end(); +}); diff --git a/node_modules/object-inspect/test/bigint.js b/node_modules/object-inspect/test/bigint.js new file mode 100644 index 0000000000000000000000000000000000000000..4ecc31df8ab3fd311570d866b418514d159abfde --- /dev/null +++ b/node_modules/object-inspect/test/bigint.js @@ -0,0 +1,58 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); + +test('bigint', { skip: typeof BigInt === 'undefined' }, function (t) { + t.test('primitives', function (st) { + st.plan(3); + + st.equal(inspect(BigInt(-256)), '-256n'); + st.equal(inspect(BigInt(0)), '0n'); + st.equal(inspect(BigInt(256)), '256n'); + }); + + t.test('objects', function (st) { + st.plan(3); + + st.equal(inspect(Object(BigInt(-256))), 'Object(-256n)'); + st.equal(inspect(Object(BigInt(0))), 'Object(0n)'); + st.equal(inspect(Object(BigInt(256))), 'Object(256n)'); + }); + + t.test('syntactic primitives', function (st) { + st.plan(3); + + /* eslint-disable no-new-func */ + st.equal(inspect(Function('return -256n')()), '-256n'); + st.equal(inspect(Function('return 0n')()), '0n'); + st.equal(inspect(Function('return 256n')()), '256n'); + }); + + t.test('toStringTag', { skip: !hasToStringTag }, function (st) { + st.plan(1); + + var faker = {}; + faker[Symbol.toStringTag] = 'BigInt'; + st.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'BigInt\' }', + 'object lying about being a BigInt inspects as an object' + ); + }); + + t.test('numericSeparator', function (st) { + st.equal(inspect(BigInt(0), { numericSeparator: false }), '0n', '0n, numericSeparator false'); + st.equal(inspect(BigInt(0), { numericSeparator: true }), '0n', '0n, numericSeparator true'); + + st.equal(inspect(BigInt(1234), { numericSeparator: false }), '1234n', '1234n, numericSeparator false'); + st.equal(inspect(BigInt(1234), { numericSeparator: true }), '1_234n', '1234n, numericSeparator true'); + st.equal(inspect(BigInt(-1234), { numericSeparator: false }), '-1234n', '1234n, numericSeparator false'); + st.equal(inspect(BigInt(-1234), { numericSeparator: true }), '-1_234n', '1234n, numericSeparator true'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/browser/dom.js b/node_modules/object-inspect/test/browser/dom.js new file mode 100644 index 0000000000000000000000000000000000000000..210c0b233e9f72c5733ef80fa38a3e8a315e5c29 --- /dev/null +++ b/node_modules/object-inspect/test/browser/dom.js @@ -0,0 +1,15 @@ +var inspect = require('../../'); +var test = require('tape'); + +test('dom element', function (t) { + t.plan(1); + + var d = document.createElement('div'); + d.setAttribute('id', 'beep'); + d.innerHTML = 'woooiiiii'; + + t.equal( + inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }]), + '[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [Object] ] ] ] } ]' + ); +}); diff --git a/node_modules/object-inspect/test/circular.js b/node_modules/object-inspect/test/circular.js new file mode 100644 index 0000000000000000000000000000000000000000..5df4233cb202efc92a8e874ef74f0c69d6ac29d1 --- /dev/null +++ b/node_modules/object-inspect/test/circular.js @@ -0,0 +1,16 @@ +var inspect = require('../'); +var test = require('tape'); + +test('circular', function (t) { + t.plan(2); + var obj = { a: 1, b: [3, 4] }; + obj.c = obj; + t.equal(inspect(obj), '{ a: 1, b: [ 3, 4 ], c: [Circular] }'); + + var double = {}; + double.a = [double]; + double.b = {}; + double.b.inner = double.b; + double.b.obj = double; + t.equal(inspect(double), '{ a: [ [Circular] ], b: { inner: [Circular], obj: [Circular] } }'); +}); diff --git a/node_modules/object-inspect/test/deep.js b/node_modules/object-inspect/test/deep.js new file mode 100644 index 0000000000000000000000000000000000000000..99ce32a088f90f217c1e4b001f4e41d3ddd4f3ec --- /dev/null +++ b/node_modules/object-inspect/test/deep.js @@ -0,0 +1,12 @@ +var inspect = require('../'); +var test = require('tape'); + +test('deep', function (t) { + t.plan(4); + var obj = [[[[[[500]]]]]]; + t.equal(inspect(obj), '[ [ [ [ [ [Array] ] ] ] ] ]'); + t.equal(inspect(obj, { depth: 4 }), '[ [ [ [ [Array] ] ] ] ]'); + t.equal(inspect(obj, { depth: 2 }), '[ [ [Array] ] ]'); + + t.equal(inspect([[[{ a: 1 }]]], { depth: 3 }), '[ [ [ [Object] ] ] ]'); +}); diff --git a/node_modules/object-inspect/test/element.js b/node_modules/object-inspect/test/element.js new file mode 100644 index 0000000000000000000000000000000000000000..47fa9e240029eb6fa2906727e20ec843fc3b6308 --- /dev/null +++ b/node_modules/object-inspect/test/element.js @@ -0,0 +1,53 @@ +var inspect = require('../'); +var test = require('tape'); + +test('element', function (t) { + t.plan(3); + var elem = { + nodeName: 'div', + attributes: [{ name: 'class', value: 'row' }], + getAttribute: function (key) { return key; }, + childNodes: [] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + t.deepEqual(inspect(obj, { quoteStyle: 'single' }), "[ 1,
, 3 ]"); + t.deepEqual(inspect(obj, { quoteStyle: 'double' }), '[ 1,
, 3 ]'); +}); + +test('element no attr', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) { return key; }, + childNodes: [] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); +}); + +test('element with contents', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) { return key; }, + childNodes: [{ nodeName: 'b' }] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
...
, 3 ]'); +}); + +test('element instance', function (t) { + t.plan(1); + var h = global.HTMLElement; + global.HTMLElement = function (name, attr) { + this.nodeName = name; + this.attributes = attr; + }; + global.HTMLElement.prototype.getAttribute = function () {}; + + var elem = new global.HTMLElement('div', []); + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + global.HTMLElement = h; +}); diff --git a/node_modules/object-inspect/test/err.js b/node_modules/object-inspect/test/err.js new file mode 100644 index 0000000000000000000000000000000000000000..cc1d884abdc52c8b5443b6212ab1d0d886ce9c33 --- /dev/null +++ b/node_modules/object-inspect/test/err.js @@ -0,0 +1,48 @@ +var test = require('tape'); +var ErrorWithCause = require('error-cause/Error'); + +var inspect = require('../'); + +test('type error', function (t) { + t.plan(1); + var aerr = new TypeError(); + aerr.foo = 555; + aerr.bar = [1, 2, 3]; + + var berr = new TypeError('tuv'); + berr.baz = 555; + + var cerr = new SyntaxError(); + cerr.message = 'whoa'; + cerr['a-b'] = 5; + + var withCause = new ErrorWithCause('foo', { cause: 'bar' }); + var withCausePlus = new ErrorWithCause('foo', { cause: 'bar' }); + withCausePlus.foo = 'bar'; + var withUndefinedCause = new ErrorWithCause('foo', { cause: undefined }); + var withEnumerableCause = new Error('foo'); + withEnumerableCause.cause = 'bar'; + + var obj = [ + new TypeError(), + new TypeError('xxx'), + aerr, + berr, + cerr, + withCause, + withCausePlus, + withUndefinedCause, + withEnumerableCause + ]; + t.equal(inspect(obj), '[ ' + [ + '[TypeError]', + '[TypeError: xxx]', + '{ [TypeError] foo: 555, bar: [ 1, 2, 3 ] }', + '{ [TypeError: tuv] baz: 555 }', + '{ [SyntaxError: whoa] message: \'whoa\', \'a-b\': 5 }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: \'bar\' }', + '{ [Error: foo] ' + ('cause' in Error.prototype ? '' : '[cause]: \'bar\', ') + 'foo: \'bar\' }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: undefined }', + '{ [Error: foo] cause: \'bar\' }' + ].join(', ') + ' ]'); +}); diff --git a/node_modules/object-inspect/test/fakes.js b/node_modules/object-inspect/test/fakes.js new file mode 100644 index 0000000000000000000000000000000000000000..a65c08c15a6e4c9c5500cbbb7a2b01327a5a8c4b --- /dev/null +++ b/node_modules/object-inspect/test/fakes.js @@ -0,0 +1,29 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); +var forEach = require('for-each'); + +test('fakes', { skip: !hasToStringTag }, function (t) { + forEach([ + 'Array', + 'Boolean', + 'Date', + 'Error', + 'Number', + 'RegExp', + 'String' + ], function (expected) { + var faker = {}; + faker[Symbol.toStringTag] = expected; + + t.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'' + expected + '\' }', + 'faker masquerading as ' + expected + ' is not shown as one' + ); + }); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/fn.js b/node_modules/object-inspect/test/fn.js new file mode 100644 index 0000000000000000000000000000000000000000..de3ca625e73adcabc8570a11318504d8d6aa6806 --- /dev/null +++ b/node_modules/object-inspect/test/fn.js @@ -0,0 +1,76 @@ +var inspect = require('../'); +var test = require('tape'); +var arrow = require('make-arrow-function')(); +var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames(); + +test('function', function (t) { + t.plan(1); + var obj = [1, 2, function f(n) { return n; }, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function: f], 4 ]'); +}); + +test('function name', function (t) { + t.plan(1); + var f = (function () { + return function () {}; + }()); + f.toString = function toStr() { return 'function xxx () {}'; }; + var obj = [1, 2, f, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)] { toString: [Function: toStr] }, 4 ]'); +}); + +test('anon function', function (t) { + var f = (function () { + return function () {}; + }()); + var obj = [1, 2, f, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)], 4 ]'); + + t.end(); +}); + +test('arrow function', { skip: !arrow }, function (t) { + t.equal(inspect(arrow), '[Function (anonymous)]'); + + t.end(); +}); + +test('truly nameless function', { skip: !arrow || !functionsHaveConfigurableNames }, function (t) { + function f() {} + Object.defineProperty(f, 'name', { value: false }); + t.equal(f.name, false); + t.equal( + inspect(f), + '[Function: f]', + 'named function with falsy `.name` does not hide its original name' + ); + + function g() {} + Object.defineProperty(g, 'name', { value: true }); + t.equal(g.name, true); + t.equal( + inspect(g), + '[Function: true]', + 'named function with truthy `.name` hides its original name' + ); + + var anon = function () {}; // eslint-disable-line func-style + Object.defineProperty(anon, 'name', { value: null }); + t.equal(anon.name, null); + t.equal( + inspect(anon), + '[Function (anonymous)]', + 'anon function with falsy `.name` does not hide its anonymity' + ); + + var anon2 = function () {}; // eslint-disable-line func-style + Object.defineProperty(anon2, 'name', { value: 1 }); + t.equal(anon2.name, 1); + t.equal( + inspect(anon2), + '[Function: 1]', + 'anon function with truthy `.name` hides its anonymity' + ); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/global.js b/node_modules/object-inspect/test/global.js new file mode 100644 index 0000000000000000000000000000000000000000..c57216aebd518555d0ba6e6677238b6cf4aee59d --- /dev/null +++ b/node_modules/object-inspect/test/global.js @@ -0,0 +1,17 @@ +'use strict'; + +var inspect = require('../'); + +var test = require('tape'); +var globalThis = require('globalthis')(); + +test('global object', function (t) { + /* eslint-env browser */ + var expected = typeof window === 'undefined' ? 'globalThis' : 'Window'; + t.equal( + inspect([globalThis]), + '[ { [object ' + expected + '] } ]' + ); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/has.js b/node_modules/object-inspect/test/has.js new file mode 100644 index 0000000000000000000000000000000000000000..01800dee6b07894536485e9a23ca6cda472984a2 --- /dev/null +++ b/node_modules/object-inspect/test/has.js @@ -0,0 +1,15 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var mockProperty = require('mock-property'); + +test('when Object#hasOwnProperty is deleted', function (t) { + t.plan(1); + var arr = [1, , 3]; // eslint-disable-line no-sparse-arrays + + t.teardown(mockProperty(Array.prototype, 1, { value: 2 })); // this is needed to account for "in" vs "hasOwnProperty" + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + + t.equal(inspect(arr), '[ 1, , 3 ]'); +}); diff --git a/node_modules/object-inspect/test/holes.js b/node_modules/object-inspect/test/holes.js new file mode 100644 index 0000000000000000000000000000000000000000..87fc8c84aedf765a2c908f451564e54ac27dcb85 --- /dev/null +++ b/node_modules/object-inspect/test/holes.js @@ -0,0 +1,15 @@ +var test = require('tape'); +var inspect = require('../'); + +var xs = ['a', 'b']; +xs[5] = 'f'; +xs[7] = 'j'; +xs[8] = 'k'; + +test('holes', function (t) { + t.plan(1); + t.equal( + inspect(xs), + "[ 'a', 'b', , , , 'f', , 'j', 'k' ]" + ); +}); diff --git a/node_modules/object-inspect/test/indent-option.js b/node_modules/object-inspect/test/indent-option.js new file mode 100644 index 0000000000000000000000000000000000000000..89d8fcedfa318ca67c9ba8fe694ba06fd2b47044 --- /dev/null +++ b/node_modules/object-inspect/test/indent-option.js @@ -0,0 +1,271 @@ +var test = require('tape'); +var forEach = require('for-each'); + +var inspect = require('../'); + +test('bad indent options', function (t) { + forEach([ + undefined, + true, + false, + -1, + 1.2, + Infinity, + -Infinity, + NaN + ], function (indent) { + t['throws']( + function () { inspect('', { indent: indent }); }, + TypeError, + inspect(indent) + ' is invalid' + ); + }); + + t.end(); +}); + +test('simple object with indent', function (t) { + t.plan(2); + + var obj = { a: 1, b: 2 }; + + var expectedSpaces = [ + '{', + ' a: 1,', + ' b: 2', + '}' + ].join('\n'); + var expectedTabs = [ + '{', + ' a: 1,', + ' b: 2', + '}' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('two deep object with indent', function (t) { + t.plan(2); + + var obj = { a: 1, b: { c: 3, d: 4 } }; + + var expectedSpaces = [ + '{', + ' a: 1,', + ' b: {', + ' c: 3,', + ' d: 4', + ' }', + '}' + ].join('\n'); + var expectedTabs = [ + '{', + ' a: 1,', + ' b: {', + ' c: 3,', + ' d: 4', + ' }', + '}' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('simple array with all single line elements', function (t) { + t.plan(2); + + var obj = [1, 2, 3, 'asdf\nsdf']; + + var expected = '[ 1, 2, 3, \'asdf\\nsdf\' ]'; + + t.equal(inspect(obj, { indent: 2 }), expected, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expected, 'tabs'); +}); + +test('array with complex elements', function (t) { + t.plan(2); + + var obj = [1, { a: 1, b: { c: 1 } }, 'asdf\nsdf']; + + var expectedSpaces = [ + '[', + ' 1,', + ' {', + ' a: 1,', + ' b: {', + ' c: 1', + ' }', + ' },', + ' \'asdf\\nsdf\'', + ']' + ].join('\n'); + var expectedTabs = [ + '[', + ' 1,', + ' {', + ' a: 1,', + ' b: {', + ' c: 1', + ' }', + ' },', + ' \'asdf\\nsdf\'', + ']' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('values', function (t) { + t.plan(2); + var obj = [{}, [], { 'a-b': 5 }]; + + var expectedSpaces = [ + '[', + ' {},', + ' [],', + ' {', + ' \'a-b\': 5', + ' }', + ']' + ].join('\n'); + var expectedTabs = [ + '[', + ' {},', + ' [],', + ' {', + ' \'a-b\': 5', + ' }', + ']' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + + var expectedStringSpaces = [ + 'Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + '}' + ].join('\n'); + var expectedStringTabs = [ + 'Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + '}' + ].join('\n'); + var expectedStringTabsDoubleQuotes = [ + 'Map (2) {', + ' { a: 1 } => [ "b" ],', + ' 3 => NaN', + '}' + ].join('\n'); + + t.equal( + inspect(map, { indent: 2 }), + expectedStringSpaces, + 'Map keys are not indented (two)' + ); + t.equal( + inspect(map, { indent: '\t' }), + expectedStringTabs, + 'Map keys are not indented (tabs)' + ); + t.equal( + inspect(map, { indent: '\t', quoteStyle: 'double' }), + expectedStringTabsDoubleQuotes, + 'Map keys are not indented (tabs + double quotes)' + ); + + t.equal(inspect(new Map(), { indent: 2 }), 'Map (0) {}', 'empty Map should show as empty (two)'); + t.equal(inspect(new Map(), { indent: '\t' }), 'Map (0) {}', 'empty Map should show as empty (tabs)'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + var expectedNestedSpaces = [ + 'Map (1) {', + ' [Circular] => Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + ' }', + '}' + ].join('\n'); + var expectedNestedTabs = [ + 'Map (1) {', + ' [Circular] => Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + ' }', + '}' + ].join('\n'); + t.equal(inspect(nestedMap, { indent: 2 }), expectedNestedSpaces, 'Map containing a Map should work (two)'); + t.equal(inspect(nestedMap, { indent: '\t' }), expectedNestedTabs, 'Map containing a Map should work (tabs)'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedStringSpaces = [ + 'Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + '}' + ].join('\n'); + var expectedStringTabs = [ + 'Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + '}' + ].join('\n'); + t.equal(inspect(set, { indent: 2 }), expectedStringSpaces, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (two)'); + t.equal(inspect(set, { indent: '\t' }), expectedStringTabs, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (tabs)'); + + t.equal(inspect(new Set(), { indent: 2 }), 'Set (0) {}', 'empty Set should show as empty (two)'); + t.equal(inspect(new Set(), { indent: '\t' }), 'Set (0) {}', 'empty Set should show as empty (tabs)'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + var expectedNestedSpaces = [ + 'Set (2) {', + ' Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + ' },', + ' [Circular]', + '}' + ].join('\n'); + var expectedNestedTabs = [ + 'Set (2) {', + ' Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + ' },', + ' [Circular]', + '}' + ].join('\n'); + t.equal(inspect(nestedSet, { indent: 2 }), expectedNestedSpaces, 'Set containing a Set should work (two)'); + t.equal(inspect(nestedSet, { indent: '\t' }), expectedNestedTabs, 'Set containing a Set should work (tabs)'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/inspect.js b/node_modules/object-inspect/test/inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..1abf81b1f00b305519e52fe74477b2c5b71803c7 --- /dev/null +++ b/node_modules/object-inspect/test/inspect.js @@ -0,0 +1,139 @@ +var test = require('tape'); +var hasSymbols = require('has-symbols/shams')(); +var utilInspect = require('../util.inspect'); +var repeat = require('string.prototype.repeat'); + +var inspect = require('..'); + +test('inspect', function (t) { + t.plan(5); + + var obj = [{ inspect: function xyzInspect() { return '!XYZ¡'; } }, []]; + var stringResult = '[ !XYZ¡, [] ]'; + var falseResult = '[ { inspect: [Function: xyzInspect] }, [] ]'; + + t.equal(inspect(obj), stringResult); + t.equal(inspect(obj, { customInspect: true }), stringResult); + t.equal(inspect(obj, { customInspect: 'symbol' }), falseResult); + t.equal(inspect(obj, { customInspect: false }), falseResult); + t['throws']( + function () { inspect(obj, { customInspect: 'not a boolean or "symbol"' }); }, + TypeError, + '`customInspect` must be a boolean or the string "symbol"' + ); +}); + +test('inspect custom symbol', { skip: !hasSymbols || !utilInspect || !utilInspect.custom }, function (t) { + t.plan(4); + + var obj = { inspect: function stringInspect() { return 'string'; } }; + obj[utilInspect.custom] = function custom() { return 'symbol'; }; + + var symbolResult = '[ symbol, [] ]'; + var stringResult = '[ string, [] ]'; + var falseResult = '[ { inspect: [Function: stringInspect]' + (utilInspect.custom ? ', [' + inspect(utilInspect.custom) + ']: [Function: custom]' : '') + ' }, [] ]'; + + var symbolStringFallback = utilInspect.custom ? symbolResult : stringResult; + var symbolFalseFallback = utilInspect.custom ? symbolResult : falseResult; + + t.equal(inspect([obj, []]), symbolStringFallback); + t.equal(inspect([obj, []], { customInspect: true }), symbolStringFallback); + t.equal(inspect([obj, []], { customInspect: 'symbol' }), symbolFalseFallback); + t.equal(inspect([obj, []], { customInspect: false }), falseResult); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + t.plan(2); + + var obj = { a: 1 }; + obj[Symbol('test')] = 2; + obj[Symbol.iterator] = 3; + Object.defineProperty(obj, Symbol('non-enum'), { + enumerable: false, + value: 4 + }); + + if (typeof Symbol.iterator === 'symbol') { + t.equal(inspect(obj), '{ a: 1, [Symbol(test)]: 2, [Symbol(Symbol.iterator)]: 3 }', 'object with symbols'); + t.equal(inspect([obj, []]), '[ { a: 1, [Symbol(test)]: 2, [Symbol(Symbol.iterator)]: 3 }, [] ]', 'object with symbols in array'); + } else { + // symbol sham key ordering is unreliable + t.match( + inspect(obj), + /^(?:{ a: 1, \[Symbol\(test\)\]: 2, \[Symbol\(Symbol.iterator\)\]: 3 }|{ a: 1, \[Symbol\(Symbol.iterator\)\]: 3, \[Symbol\(test\)\]: 2 })$/, + 'object with symbols (nondeterministic symbol sham key ordering)' + ); + t.match( + inspect([obj, []]), + /^\[ (?:{ a: 1, \[Symbol\(test\)\]: 2, \[Symbol\(Symbol.iterator\)\]: 3 }|{ a: 1, \[Symbol\(Symbol.iterator\)\]: 3, \[Symbol\(test\)\]: 2 }), \[\] \]$/, + 'object with symbols in array (nondeterministic symbol sham key ordering)' + ); + } +}); + +test('maxStringLength', function (t) { + t['throws']( + function () { inspect('', { maxStringLength: -1 }); }, + TypeError, + 'maxStringLength must be >= 0, or Infinity, not negative' + ); + + var str = repeat('a', 1e8); + + t.equal( + inspect([str], { maxStringLength: 10 }), + '[ \'aaaaaaaaaa\'... 99999990 more characters ]', + 'maxStringLength option limits output' + ); + + t.equal( + inspect(['f'], { maxStringLength: null }), + '[ \'\'... 1 more character ]', + 'maxStringLength option accepts `null`' + ); + + t.equal( + inspect([str], { maxStringLength: Infinity }), + '[ \'' + str + '\' ]', + 'maxStringLength option accepts ∞' + ); + + t.end(); +}); + +test('inspect options', { skip: !utilInspect.custom }, function (t) { + var obj = {}; + obj[utilInspect.custom] = function () { + return JSON.stringify(arguments); + }; + t.equal( + inspect(obj), + utilInspect(obj, { depth: 5 }), + 'custom symbols will use node\'s inspect' + ); + t.equal( + inspect(obj, { depth: 2 }), + utilInspect(obj, { depth: 2 }), + 'a reduced depth will be passed to node\'s inspect' + ); + t.equal( + inspect({ d1: obj }, { depth: 3 }), + '{ d1: ' + utilInspect(obj, { depth: 2 }) + ' }', + 'deep objects will receive a reduced depth' + ); + t.equal( + inspect({ d1: obj }, { depth: 1 }), + '{ d1: [Object] }', + 'unlike nodejs inspect, customInspect will not be used once the depth is exceeded.' + ); + t.end(); +}); + +test('inspect URL', { skip: typeof URL === 'undefined' }, function (t) { + t.match( + inspect(new URL('https://nodejs.org')), + /nodejs\.org/, // Different environments stringify it differently + 'url can be inspected' + ); + t.end(); +}); diff --git a/node_modules/object-inspect/test/lowbyte.js b/node_modules/object-inspect/test/lowbyte.js new file mode 100644 index 0000000000000000000000000000000000000000..68a345d8578004506a45296d6de9e091b7811272 --- /dev/null +++ b/node_modules/object-inspect/test/lowbyte.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { x: 'a\r\nb', y: '\x05! \x1f \x12' }; + +test('interpolate low bytes', function (t) { + t.plan(1); + t.equal( + inspect(obj), + "{ x: 'a\\r\\nb', y: '\\x05! \\x1F \\x12' }" + ); +}); diff --git a/node_modules/object-inspect/test/number.js b/node_modules/object-inspect/test/number.js new file mode 100644 index 0000000000000000000000000000000000000000..8f287e8e2ab93785108de2e82e5b359ffb524f02 --- /dev/null +++ b/node_modules/object-inspect/test/number.js @@ -0,0 +1,58 @@ +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); + +var inspect = require('../'); + +test('negative zero', function (t) { + t.equal(inspect(0), '0', 'inspect(0) === "0"'); + t.equal(inspect(Object(0)), 'Object(0)', 'inspect(Object(0)) === "Object(0)"'); + + t.equal(inspect(-0), '-0', 'inspect(-0) === "-0"'); + t.equal(inspect(Object(-0)), 'Object(-0)', 'inspect(Object(-0)) === "Object(-0)"'); + + t.end(); +}); + +test('numericSeparator', function (t) { + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { inspect(true, { numericSeparator: nonBoolean }); }, + TypeError, + inspect(nonBoolean) + ' is not a boolean' + ); + }); + + t.test('3 digit numbers', function (st) { + var failed = false; + for (var i = -999; i < 1000; i += 1) { + var actual = inspect(i); + var actualSepNo = inspect(i, { numericSeparator: false }); + var actualSepYes = inspect(i, { numericSeparator: true }); + var expected = String(i); + if (actual !== expected || actualSepNo !== expected || actualSepYes !== expected) { + failed = true; + t.equal(actual, expected); + t.equal(actualSepNo, expected); + t.equal(actualSepYes, expected); + } + } + + st.notOk(failed, 'all 3 digit numbers passed'); + + st.end(); + }); + + t.equal(inspect(1e3), '1000', '1000'); + t.equal(inspect(1e3, { numericSeparator: false }), '1000', '1000, numericSeparator false'); + t.equal(inspect(1e3, { numericSeparator: true }), '1_000', '1000, numericSeparator true'); + t.equal(inspect(-1e3), '-1000', '-1000'); + t.equal(inspect(-1e3, { numericSeparator: false }), '-1000', '-1000, numericSeparator false'); + t.equal(inspect(-1e3, { numericSeparator: true }), '-1_000', '-1000, numericSeparator true'); + + t.equal(inspect(1234.5678, { numericSeparator: true }), '1_234.567_8', 'fractional numbers get separators'); + t.equal(inspect(1234.56789, { numericSeparator: true }), '1_234.567_89', 'fractional numbers get separators'); + t.equal(inspect(1234.567891, { numericSeparator: true }), '1_234.567_891', 'fractional numbers get separators'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/quoteStyle.js b/node_modules/object-inspect/test/quoteStyle.js new file mode 100644 index 0000000000000000000000000000000000000000..da23e630cfcf0b2bcd6d5e90becc09d714f46d7b --- /dev/null +++ b/node_modules/object-inspect/test/quoteStyle.js @@ -0,0 +1,26 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); + +test('quoteStyle option', function (t) { + t['throws'](function () { inspect(null, { quoteStyle: false }); }, 'false is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: true }); }, 'true is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: '' }); }, '"" is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: {} }); }, '{} is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: [] }); }, '[] is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: 42 }); }, '42 is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: NaN }); }, 'NaN is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: function () {} }); }, 'a function is not a valid value'); + + t.equal(inspect('"', { quoteStyle: 'single' }), '\'"\'', 'double quote, quoteStyle: "single"'); + t.equal(inspect('"', { quoteStyle: 'double' }), '"\\""', 'double quote, quoteStyle: "double"'); + + t.equal(inspect('\'', { quoteStyle: 'single' }), '\'\\\'\'', 'single quote, quoteStyle: "single"'); + t.equal(inspect('\'', { quoteStyle: 'double' }), '"\'"', 'single quote, quoteStyle: "double"'); + + t.equal(inspect('`', { quoteStyle: 'single' }), '\'`\'', 'backtick, quoteStyle: "single"'); + t.equal(inspect('`', { quoteStyle: 'double' }), '"`"', 'backtick, quoteStyle: "double"'); + + t.end(); +}); diff --git a/node_modules/object-inspect/test/toStringTag.js b/node_modules/object-inspect/test/toStringTag.js new file mode 100644 index 0000000000000000000000000000000000000000..95f82703d08f358b00f180c7b479b9f33dff3dac --- /dev/null +++ b/node_modules/object-inspect/test/toStringTag.js @@ -0,0 +1,40 @@ +'use strict'; + +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); + +var inspect = require('../'); + +test('Symbol.toStringTag', { skip: !hasToStringTag }, function (t) { + t.plan(4); + + var obj = { a: 1 }; + t.equal(inspect(obj), '{ a: 1 }', 'object, no Symbol.toStringTag'); + + obj[Symbol.toStringTag] = 'foo'; + t.equal(inspect(obj), '{ a: 1, [Symbol(Symbol.toStringTag)]: \'foo\' }', 'object with Symbol.toStringTag'); + + t.test('null objects', { skip: 'toString' in { __proto__: null } }, function (st) { + st.plan(2); + + var dict = { __proto__: null, a: 1 }; + st.equal(inspect(dict), '[Object: null prototype] { a: 1 }', 'null object with Symbol.toStringTag'); + + dict[Symbol.toStringTag] = 'Dict'; + st.equal(inspect(dict), '[Dict: null prototype] { a: 1, [Symbol(Symbol.toStringTag)]: \'Dict\' }', 'null object with Symbol.toStringTag'); + }); + + t.test('instances', function (st) { + st.plan(4); + + function C() { + this.a = 1; + } + st.equal(Object.prototype.toString.call(new C()), '[object Object]', 'instance, no toStringTag, Object.prototype.toString'); + st.equal(inspect(new C()), 'C { a: 1 }', 'instance, no toStringTag'); + + C.prototype[Symbol.toStringTag] = 'Class!'; + st.equal(Object.prototype.toString.call(new C()), '[object Class!]', 'instance, with toStringTag, Object.prototype.toString'); + st.equal(inspect(new C()), 'C [Class!] { a: 1 }', 'instance, with toStringTag'); + }); +}); diff --git a/node_modules/object-inspect/test/undef.js b/node_modules/object-inspect/test/undef.js new file mode 100644 index 0000000000000000000000000000000000000000..e3f4961229c249a1d4f242d415b5193fc0ad5056 --- /dev/null +++ b/node_modules/object-inspect/test/undef.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { a: 1, b: [3, 4, undefined, null], c: undefined, d: null }; + +test('undef and null', function (t) { + t.plan(1); + t.equal( + inspect(obj), + '{ a: 1, b: [ 3, 4, undefined, null ], c: undefined, d: null }' + ); +}); diff --git a/node_modules/object-inspect/test/values.js b/node_modules/object-inspect/test/values.js new file mode 100644 index 0000000000000000000000000000000000000000..15986cd0edbb8218fdd4fe8f414b4e27b5767b1e --- /dev/null +++ b/node_modules/object-inspect/test/values.js @@ -0,0 +1,261 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var mockProperty = require('mock-property'); +var hasSymbols = require('has-symbols/shams')(); +var hasToStringTag = require('has-tostringtag/shams')(); +var forEach = require('for-each'); +var semver = require('semver'); + +test('values', function (t) { + t.plan(1); + var obj = [{}, [], { 'a-b': 5 }]; + t.equal(inspect(obj), '[ {}, [], { \'a-b\': 5 } ]'); +}); + +test('arrays with properties', function (t) { + t.plan(1); + var arr = [3]; + arr.foo = 'bar'; + var obj = [1, 2, arr]; + obj.baz = 'quux'; + obj.index = -1; + t.equal(inspect(obj), '[ 1, 2, [ 3, foo: \'bar\' ], baz: \'quux\', index: -1 ]'); +}); + +test('has', function (t) { + t.plan(1); + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + + t.equal(inspect({ a: 1, b: 2 }), '{ a: 1, b: 2 }'); +}); + +test('indexOf seen', function (t) { + t.plan(1); + var xs = [1, 2, 3, {}]; + xs.push(xs); + + var seen = []; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[ 1, 2, 3, {}, [Circular] ]' + ); +}); + +test('seen seen', function (t) { + t.plan(1); + var xs = [1, 2, 3]; + + var seen = [xs]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('seen seen seen', function (t) { + t.plan(1); + var xs = [1, 2, 3]; + + var seen = [5, xs]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + var sym = Symbol('foo'); + t.equal(inspect(sym), 'Symbol(foo)', 'Symbol("foo") should be "Symbol(foo)"'); + if (typeof sym === 'symbol') { + // Symbol shams are incapable of differentiating boxed from unboxed symbols + t.equal(inspect(Object(sym)), 'Object(Symbol(foo))', 'Object(Symbol("foo")) should be "Object(Symbol(foo))"'); + } + + t.test('toStringTag', { skip: !hasToStringTag }, function (st) { + st.plan(1); + + var faker = {}; + faker[Symbol.toStringTag] = 'Symbol'; + st.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'Symbol\' }', + 'object lying about being a Symbol inspects as an object' + ); + }); + + t.end(); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + var expectedString = 'Map (2) {' + inspect({ a: 1 }) + ' => ' + inspect(['b']) + ', 3 => NaN}'; + t.equal(inspect(map), expectedString, 'new Map([[{ a: 1 }, ["b"]], [3, NaN]]) should show size and contents'); + t.equal(inspect(new Map()), 'Map (0) {}', 'empty Map should show as empty'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + t.equal(inspect(nestedMap), 'Map (1) {[Circular] => ' + expectedString + '}', 'Map containing a Map should work'); + + t.end(); +}); + +test('WeakMap', { skip: typeof WeakMap !== 'function' }, function (t) { + var map = new WeakMap(); + map.set({ a: 1 }, ['b']); + var expectedString = 'WeakMap { ? }'; + t.equal(inspect(map), expectedString, 'new WeakMap([[{ a: 1 }, ["b"]]]) should not show size or contents'); + t.equal(inspect(new WeakMap()), 'WeakMap { ? }', 'empty WeakMap should not show as empty'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedString = 'Set (2) {' + inspect({ a: 1 }) + ', ' + inspect(['b']) + '}'; + t.equal(inspect(set), expectedString, 'new Set([{ a: 1 }, ["b"]]) should show size and contents'); + t.equal(inspect(new Set()), 'Set (0) {}', 'empty Set should show as empty'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + t.equal(inspect(nestedSet), 'Set (2) {' + expectedString + ', [Circular]}', 'Set containing a Set should work'); + + t.end(); +}); + +test('WeakSet', { skip: typeof WeakSet !== 'function' }, function (t) { + var map = new WeakSet(); + map.add({ a: 1 }); + var expectedString = 'WeakSet { ? }'; + t.equal(inspect(map), expectedString, 'new WeakSet([{ a: 1 }]) should not show size or contents'); + t.equal(inspect(new WeakSet()), 'WeakSet { ? }', 'empty WeakSet should not show as empty'); + + t.end(); +}); + +test('WeakRef', { skip: typeof WeakRef !== 'function' }, function (t) { + var ref = new WeakRef({ a: 1 }); + var expectedString = 'WeakRef { ? }'; + t.equal(inspect(ref), expectedString, 'new WeakRef({ a: 1 }) should not show contents'); + + t.end(); +}); + +test('FinalizationRegistry', { skip: typeof FinalizationRegistry !== 'function' }, function (t) { + var registry = new FinalizationRegistry(function () {}); + var expectedString = 'FinalizationRegistry [FinalizationRegistry] {}'; + t.equal(inspect(registry), expectedString, 'new FinalizationRegistry(function () {}) should work normallys'); + + t.end(); +}); + +test('Strings', function (t) { + var str = 'abc'; + + t.equal(inspect(str), "'" + str + "'", 'primitive string shows as such'); + t.equal(inspect(str, { quoteStyle: 'single' }), "'" + str + "'", 'primitive string shows as such, single quoted'); + t.equal(inspect(str, { quoteStyle: 'double' }), '"' + str + '"', 'primitive string shows as such, double quoted'); + t.equal(inspect(Object(str)), 'Object(' + inspect(str) + ')', 'String object shows as such'); + t.equal(inspect(Object(str), { quoteStyle: 'single' }), 'Object(' + inspect(str, { quoteStyle: 'single' }) + ')', 'String object shows as such, single quoted'); + t.equal(inspect(Object(str), { quoteStyle: 'double' }), 'Object(' + inspect(str, { quoteStyle: 'double' }) + ')', 'String object shows as such, double quoted'); + + t.end(); +}); + +test('Numbers', function (t) { + var num = 42; + + t.equal(inspect(num), String(num), 'primitive number shows as such'); + t.equal(inspect(Object(num)), 'Object(' + inspect(num) + ')', 'Number object shows as such'); + + t.end(); +}); + +test('Booleans', function (t) { + t.equal(inspect(true), String(true), 'primitive true shows as such'); + t.equal(inspect(Object(true)), 'Object(' + inspect(true) + ')', 'Boolean object true shows as such'); + + t.equal(inspect(false), String(false), 'primitive false shows as such'); + t.equal(inspect(Object(false)), 'Object(' + inspect(false) + ')', 'Boolean false object shows as such'); + + t.end(); +}); + +test('Date', function (t) { + var now = new Date(); + t.equal(inspect(now), String(now), 'Date shows properly'); + t.equal(inspect(new Date(NaN)), 'Invalid Date', 'Invalid Date shows properly'); + + t.end(); +}); + +test('RegExps', function (t) { + t.equal(inspect(/a/g), '/a/g', 'regex shows properly'); + t.equal(inspect(new RegExp('abc', 'i')), '/abc/i', 'new RegExp shows properly'); + + var match = 'abc abc'.match(/[ab]+/); + delete match.groups; // for node < 10 + t.equal(inspect(match), '[ \'ab\', index: 0, input: \'abc abc\' ]', 'RegExp match object shows properly'); + + t.end(); +}); + +test('Proxies', { skip: typeof Proxy !== 'function' || !hasToStringTag }, function (t) { + var target = { proxy: true }; + var fake = new Proxy(target, { has: function () { return false; } }); + + // needed to work around a weird difference in node v6.0 - v6.4 where non-present properties are not logged + var isNode60 = semver.satisfies(process.version, '6.0 - 6.4'); + + forEach([ + 'Boolean', + 'Number', + 'String', + 'Symbol', + 'Date' + ], function (tag) { + target[Symbol.toStringTag] = tag; + + t.equal( + inspect(fake), + '{ ' + (isNode60 ? '' : 'proxy: true, ') + '[Symbol(Symbol.toStringTag)]: \'' + tag + '\' }', + 'Proxy for + ' + tag + ' shows as the target, which has no slots' + ); + }); + + t.end(); +}); + +test('fakers', { skip: !hasToStringTag }, function (t) { + var target = { proxy: false }; + + forEach([ + 'Boolean', + 'Number', + 'String', + 'Symbol', + 'Date' + ], function (tag) { + target[Symbol.toStringTag] = tag; + + t.equal( + inspect(target), + '{ proxy: false, [Symbol(Symbol.toStringTag)]: \'' + tag + '\' }', + 'Object pretending to be ' + tag + ' does not trick us' + ); + }); + + t.end(); +}); diff --git a/node_modules/object-inspect/util.inspect.js b/node_modules/object-inspect/util.inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..7784fab55d08875a01b24636f3a541c3d0bd39b2 --- /dev/null +++ b/node_modules/object-inspect/util.inspect.js @@ -0,0 +1 @@ +module.exports = require('util').inspect; diff --git a/node_modules/object-is/.eslintrc b/node_modules/object-is/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..3b5d9e90ec405f85dd7f9066656efccc51193697 --- /dev/null +++ b/node_modules/object-is/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/object-is/.nycrc b/node_modules/object-is/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/node_modules/object-is/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/object-is/CHANGELOG.md b/node_modules/object-is/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..1de939e608b10b797f1563f6dcd6205ceea63f95 --- /dev/null +++ b/node_modules/object-is/CHANGELOG.md @@ -0,0 +1,175 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.6](https://github.com/es-shims/object-is/compare/v1.1.5...v1.1.6) - 2024-02-27 + +### Commits + +- [actions] reuse common workflows [`f8d0c06`](https://github.com/es-shims/object-is/commit/f8d0c0617901b4b220f2bbbaff8c9ec7f22891c6) +- [actions] use `node/install` instead of `node/run` [`90fc019`](https://github.com/es-shims/object-is/commit/90fc01955dc677fef745f0dc4164e2144b047997) +- [actions] update workflows [`37339d8`](https://github.com/es-shims/object-is/commit/37339d870aacad9f524cb685c0075aed78e9bd6e) +- [meta] use `npmignore` to autogenerate an npmignore file [`a257c19`](https://github.com/es-shims/object-is/commit/a257c19d55c275ac44892b1d2d98a5d06e976943) +- [readme] fix badges [`50af053`](https://github.com/es-shims/object-is/commit/50af053d4d8ee02657d71f784c31b372905187a7) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `safe-publish-latest`, `tape` [`86058c6`](https://github.com/es-shims/object-is/commit/86058c65153dea90d18ff969244bdc610f382046) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `functions-have-names`, `has-symbols`, `tape` [`d5484eb`](https://github.com/es-shims/object-is/commit/d5484eb02a44482de29ce95ccfd01e885d0ff83b) +- [actions] update rebase action to use reusable workflow [`68075c5`](https://github.com/es-shims/object-is/commit/68075c5bd0e35b51e815e7fd95bb90cc54deb699) +- [actions] update codecov uploader [`f12fbb2`](https://github.com/es-shims/object-is/commit/f12fbb2f23b43c2d982fd00c95ff98b01e8747a1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `has-symbols`, `tape` [`43eb235`](https://github.com/es-shims/object-is/commit/43eb235ffa1dd258ff5ef990fd2f0ce78ce40ccc) +- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `aud`, `npmignore`, `tape` [`f306966`](https://github.com/es-shims/object-is/commit/f306966e53fac2e24dd11dfe6cf31a8ae20a08da) +- [readme] add actions and codecov badges [`e443b4a`](https://github.com/es-shims/object-is/commit/e443b4a3d0b01683cb6fec59916ad4ec463e9de7) +- [readme] remove travis badge [`5165adc`](https://github.com/es-shims/object-is/commit/5165adccf9e8373f38a01e7a5887b42a4229ca2b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`e7ccf56`](https://github.com/es-shims/object-is/commit/e7ccf56f84434f6671fae1d1fe4945f5b3a84120) +- [Deps] update `call-bind`, `define-properties` [`a3052db`](https://github.com/es-shims/object-is/commit/a3052db9e272c5d544553a7f43c916689e8cca9a) +- [readme] fix URLs [`ac37ea6`](https://github.com/es-shims/object-is/commit/ac37ea68b2a11ef7ebff694e6c4f308c735240ea) +- [readme] assert.notOk -> assert.equal [`7fe769f`](https://github.com/es-shims/object-is/commit/7fe769fc8293d8756ed2d31c4d12afc0581498b7) +- [Deps] update `call-bind` [`b965cd3`](https://github.com/es-shims/object-is/commit/b965cd319e1c397a5ef7dc6dffc9a5bd4329d408) +- [Dev Deps] update `tape` [`a737830`](https://github.com/es-shims/object-is/commit/a737830a051cdc650c3bfb78b085586c9fd7cd13) +- [Deps] update `define-properties`, `es-abstract` [`441eafb`](https://github.com/es-shims/object-is/commit/441eafbca4e32d76dc16bea6b73ee794296e2c0c) + +## [v1.1.5](https://github.com/es-shims/object-is/compare/v1.1.4...v1.1.5) - 2021-02-20 + +### Commits + +- [meta] do not publish github action workflow files [`ec00b0f`](https://github.com/es-shims/object-is/commit/ec00b0f3a5096a7d57884e201c76ded3052a1b9c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`279645e`](https://github.com/es-shims/object-is/commit/279645e330da410da9776455274aa6b3c89b585b) +- [actions] update workflows [`6b4ef5a`](https://github.com/es-shims/object-is/commit/6b4ef5a219fc3982433fc3df2ad9d57994be0761) +- [Dev Deps] update `eslint`, `functions-have-names`, `tape` [`f5fd32a`](https://github.com/es-shims/object-is/commit/f5fd32ace61d4643fe0bf67ca83a6674a65906be) +- [Deps] update `call-bind` [`0fafc13`](https://github.com/es-shims/object-is/commit/0fafc13ec1a20d3075512ae9d2c0b0ee252169a9) +- [Deps] update `call-bind` [`e28a929`](https://github.com/es-shims/object-is/commit/e28a929b71fc1939a4c4d5c92ca0c04a0b27ff81) +- [readme] Add note about es-shim API [`f903cc1`](https://github.com/es-shims/object-is/commit/f903cc11186e0d5c6c4173821d6b7bf2a49f6c01) + +## [v1.1.4](https://github.com/es-shims/object-is/compare/v1.1.3...v1.1.4) - 2020-11-26 + +### Commits + +- [Tests] migrate tests to Github Actions [`958ab26`](https://github.com/es-shims/object-is/commit/958ab266fd68396781c076d8a5ee4ba292561362) +- [Tests] add `shimmed` and `implementation` and `index` tests; run `es-shim-api` in postlint; use `tape` runner [`b918fb8`](https://github.com/es-shims/object-is/commit/b918fb849023032d2da61ead95f31b0a03371131) +- [Tests] run `nyc` on all tests [`8f62816`](https://github.com/es-shims/object-is/commit/8f6281683ad58ffe9b5809c2a9e7bb65db344c9c) +- [actions] add "Allow Edits" workflow [`aa419f0`](https://github.com/es-shims/object-is/commit/aa419f0ea2b497844365f9f51a746fa2a57bb6ee) +- [Deps] use `call-bind` instead of `es-abstract` [`4991728`](https://github.com/es-shims/object-is/commit/49917288eddfce31949f5a3351f0e0bb67929a2b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud` [`3ce2ef5`](https://github.com/es-shims/object-is/commit/3ce2ef5e834bf22566ea5741178cd76bb35f8a89) +- [meta] ignore coverage output [`d778383`](https://github.com/es-shims/object-is/commit/d778383fde9222bc5349dd4adcaab9f5ef10254e) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`e0d9b41`](https://github.com/es-shims/object-is/commit/e0d9b41a73f51f1c8b9d9b402da5f754926bc280) + +## [v1.1.3](https://github.com/es-shims/object-is/compare/v1.1.2...v1.1.3) - 2020-09-30 + +### Commits + +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`6f1217f`](https://github.com/es-shims/object-is/commit/6f1217fc82cbe25d3911cad2d3298a8f3f51bd7f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog` [`68d8ab0`](https://github.com/es-shims/object-is/commit/68d8ab07275949aa78f20f0e6270c0a26aba2647) +- [Deps] update `es-abstract` [`d665d57`](https://github.com/es-shims/object-is/commit/d665d570e416f039bbbc577f0c2c77104302d227) +- [Deps] update `es-abstract` [`61b4d08`](https://github.com/es-shims/object-is/commit/61b4d0893212b08ec89ba8c388948fa4377f7a43) + +## [v1.1.2](https://github.com/es-shims/object-is/compare/v1.1.1...v1.1.2) - 2020-04-14 + +### Commits + +- [Fix] avoid mutating the builtin `Object.is` in the main entry point [`5988702`](https://github.com/es-shims/object-is/commit/59887020544021d7cf8e72cd84c4d67abcf558c5) + +## [v1.1.1](https://github.com/es-shims/object-is/compare/v1.1.0...v1.1.1) - 2020-04-14 + +### Fixed + +- [Deps] add missing `define-properties` [`#10`](https://github.com/es-shims/object-is/issues/10) + +## [v1.1.0](https://github.com/es-shims/object-is/compare/v1.0.2...v1.1.0) - 2020-04-14 + +### Commits + +- [New] convert to `es-shim-api` interface [`c8b6e9f`](https://github.com/es-shims/object-is/commit/c8b6e9f249438bfd9dfa315415eddd3a1d436d15) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`; add `safe-publish-latest` [`222a2a9`](https://github.com/es-shims/object-is/commit/222a2a9a2eb08be844bf4c619d1eb711d743c6f3) +- [Dev Deps] update `auto-changelog`, `tape` [`1ea6a92`](https://github.com/es-shims/object-is/commit/1ea6a92153695074c4e3f2e2e0ec26b83f6b091a) +- [Dev Deps] update `auto-changelog`; add `aud` [`1d129e0`](https://github.com/es-shims/object-is/commit/1d129e0dfe386a1e39fa4f3ff991198e885299b1) +- [Tests] only audit prod deps [`ad12386`](https://github.com/es-shims/object-is/commit/ad1238688dcfe9170217b6b9a02122369979d221) + +## [v1.0.2](https://github.com/es-shims/object-is/compare/v1.0.1...v1.0.2) - 2019-12-15 + +### Commits + +- [Tests] use shared travis-ci configs [`eb56ddf`](https://github.com/es-shims/object-is/commit/eb56ddf82bd08f56bd50db7333f2a7b6cef2452a) +- [Tests] up to `node` `v12.6`, `v11.15`, `v10.16`, `v9.11`, `v8.16`, `v7.10`, `v6.17`, `v5.12`, `4.9`; use `nvm install-latest-npm` [`a5bb4e3`](https://github.com/es-shims/object-is/commit/a5bb4e3663902dda4eb9c748aecd04532428594a) +- [Tests] remove `jscs` [`1929690`](https://github.com/es-shims/object-is/commit/19296907bbb9864518ccb2364a44f9adda9c910c) +- Using my standard jscs.json file. [`a7621dc`](https://github.com/es-shims/object-is/commit/a7621dcafbdf4befa4bb97c4e132f30fd486addf) +- [meta] run `auto-changelog` [`5c551c4`](https://github.com/es-shims/object-is/commit/5c551c406f8a72d53f8f4bbabc89f0c1892bf262) +- Update `tape`, `covert`, `jscs` [`bd84112`](https://github.com/es-shims/object-is/commit/bd8411263e754f5a464b6d55c01ecd3b1f4c7437) +- [meta] move repo to es-shims org [`15d3cdc`](https://github.com/es-shims/object-is/commit/15d3cdcbd4b78c8dee80507ac8a5f4cff7ab42d4) +- Test up to `io.js` `v2.2` [`d1d2de4`](https://github.com/es-shims/object-is/commit/d1d2de48f72853552e3d3a751b3f178c5dc10ef5) +- Update `tape`, `jscs` [`b40e85f`](https://github.com/es-shims/object-is/commit/b40e85f77cc906fc54246cf672a78b902bd65aab) +- Add `npm run eslint` [`a80ee81`](https://github.com/es-shims/object-is/commit/a80ee81d12d8fb4120bf590c4d4622fb5dc3f67b) +- Only apps should have lockfiles [`f70677a`](https://github.com/es-shims/object-is/commit/f70677adbe0a765ee26e214a95a97d0ddf88f31e) +- [actions] add automatic rebasing / merge commit blocking [`27780d3`](https://github.com/es-shims/object-is/commit/27780d330cbaf3ef96479b5a0a3fe55f71b54bb6) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`cf886ce`](https://github.com/es-shims/object-is/commit/cf886ced70afff6c5a66be6f9ddba2d330034c70) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `has-symbols` [`b70e146`](https://github.com/es-shims/object-is/commit/b70e146496488ac5e1a48651cb94292e67051e48) +- [meta] add version scripts [`25a5308`](https://github.com/es-shims/object-is/commit/25a5308bfcc41733a86ce0461ef69a2459215b5b) +- [Tests] up to `node` `v12.10` [`b6e934c`](https://github.com/es-shims/object-is/commit/b6e934ca8f0e65dac7ed3c30b2b7907d39e36f6b) +- [Dev Deps] update `tape`, `jscs` [`df38b5a`](https://github.com/es-shims/object-is/commit/df38b5a856071aaa4d6b8e089a48d80775cb1ed9) +- Adding license and downloads badges [`c743f09`](https://github.com/es-shims/object-is/commit/c743f0907b0bab73a0821541190a865a5c3e5da9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`41d1c5b`](https://github.com/es-shims/object-is/commit/41d1c5b8173f6543e01940b18daee93c586058d0) +- Add tests for Symbols. [`8189ca7`](https://github.com/es-shims/object-is/commit/8189ca73b647a13f63162bc8ed14040386972530) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`698c449`](https://github.com/es-shims/object-is/commit/698c449a8fdc6634747765333cdd8071119932b8) +- Add `npm run security` [`1fe530a`](https://github.com/es-shims/object-is/commit/1fe530abd3164eb70dedd959a25f3b1ad0d02c01) +- Test up to `io.js` `v3.0` [`cd6ac03`](https://github.com/es-shims/object-is/commit/cd6ac034cda66916319c68aeea190e5817de106c) +- [Refactor] no-else-return [`a590382`](https://github.com/es-shims/object-is/commit/a590382d69134915f37039ae6841c9fffbdd5b81) +- [docs] clean up some links [`422df90`](https://github.com/es-shims/object-is/commit/422df90523f4d7f2463e404d394f656232f0fc7c) +- All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. [`8684418`](https://github.com/es-shims/object-is/commit/8684418131004859fe18443d4f57f28510b72e13) +- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`6b618ac`](https://github.com/es-shims/object-is/commit/6b618acfa5bcab8d1684d926728000afb4f1ee52) +- [readme] prefer ES2015 over ES6 [`9aae9f9`](https://github.com/es-shims/object-is/commit/9aae9f9d1b4e699364f4822534b89887abb9089f) +- [meta] use keepachangelog with auto-changelog [`3abdcd9`](https://github.com/es-shims/object-is/commit/3abdcd915bc647a5f01af2422fa4a37b2980f946) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`65da8bb`](https://github.com/es-shims/object-is/commit/65da8bba76d4b0e95f95d2a6b98d7bfe5b294ff0) +- [Tests] use `has-symbols` [`9c88ec7`](https://github.com/es-shims/object-is/commit/9c88ec729227f35dc18fe52131c11afd296a042e) +- Update `tape`, `jscs` [`abc6021`](https://github.com/es-shims/object-is/commit/abc6021a0be38921688182e0f95376597056f6cd) +- Update `jscs` [`f85f0ba`](https://github.com/es-shims/object-is/commit/f85f0ba49809030c09dfda4af0022c4122438f90) +- Update `tape`, `jscs` [`9c8b28b`](https://github.com/es-shims/object-is/commit/9c8b28bf52521b70fdacdaba1035e101aa0a1240) +- Using single quotes. [`46a566e`](https://github.com/es-shims/object-is/commit/46a566efbc6366aa44ef9ac8b47668ede5830d50) +- [meta] add `funding` field [`f71e665`](https://github.com/es-shims/object-is/commit/f71e66510676f9bfeb6e81a05821161953879270) +- [Dev Deps] update `tape` [`694a94e`](https://github.com/es-shims/object-is/commit/694a94e83b4d415b1e43adb8011ad33351945105) +- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`4b29a71`](https://github.com/es-shims/object-is/commit/4b29a718b459ecde3512c4dd6577a2a5e95b7cc6) +- Update `jscs` [`204e6fe`](https://github.com/es-shims/object-is/commit/204e6febc368ca94091ac0b5ec0254c33b0ee462) +- Lock covert to v1.0.0. [`efc5a21`](https://github.com/es-shims/object-is/commit/efc5a21e1d0cc463ec7c7ef2f75a317085093d5e) +- Updating tape [`d1ff721`](https://github.com/es-shims/object-is/commit/d1ff721d2bdec538112cdbbfedcf06d578093831) +- Updating jscs [`35b4df9`](https://github.com/es-shims/object-is/commit/35b4df90d0c97a4f004f0188940b2e602b645c16) +- Updating jscs [`46c3b9d`](https://github.com/es-shims/object-is/commit/46c3b9d31a7f8ce43c496e0304b22ce142311917) +- Updating jscs [`75c9b8b`](https://github.com/es-shims/object-is/commit/75c9b8b45022d5e9b44b0c9a055974185b550a57) + +## [v1.0.1](https://github.com/es-shims/object-is/compare/v1.0.0...v1.0.1) - 2014-08-27 + +### Merged + +- Use svg instead of png to get better image quality [`#2`](https://github.com/es-shims/object-is/pull/2) + +### Commits + +- Adding `npm run lint` [`af5dedd`](https://github.com/es-shims/object-is/commit/af5dedd2f40df7584c856576123a2d2852dd9694) +- Using an easier isNaN check [`89474ae`](https://github.com/es-shims/object-is/commit/89474ae3e26eb857d89b01c1f3b20f859bd0f161) +- Oops, run quiet coverage as part of tests [`5149e18`](https://github.com/es-shims/object-is/commit/5149e1876808e67a016fd913f6d99481bf7091f2) +- Run linter as part of tests [`d5eee8a`](https://github.com/es-shims/object-is/commit/d5eee8a43b95c619cf3b06ef3d64cefc865f33f3) +- Updating covert [`0b862da`](https://github.com/es-shims/object-is/commit/0b862dad7873b9aab74d2f4262b5b587120c169b) +- Updating tape [`484e6ca`](https://github.com/es-shims/object-is/commit/484e6cab0d5734b8c9f23ceada58e93b09dc15ee) + +## [v1.0.0](https://github.com/es-shims/object-is/compare/v0.0.0...v1.0.0) - 2014-08-01 + +### Commits + +- Make sure old and unstable nodes don't break Travis [`c8d3dfe`](https://github.com/es-shims/object-is/commit/c8d3dfe4c0f6dc76a5b0cc22a6a6401fa1105cea) +- Bumping to v1.0.0. [`8811835`](https://github.com/es-shims/object-is/commit/8811835bff203cf0dc0dee1342beeb749ea63e10) +- Updating tape [`0767579`](https://github.com/es-shims/object-is/commit/0767579b3cbf59e49c73c131186bfcbad4448020) +- Updating covert [`6b67a0b`](https://github.com/es-shims/object-is/commit/6b67a0b4b6933ea23c74c24037f3f515942a005a) +- Run code coverage in tests [`8b5d70d`](https://github.com/es-shims/object-is/commit/8b5d70d9cbf6194d69ee22b8433fe4e0a3d7507e) +- Updating tape [`57b019c`](https://github.com/es-shims/object-is/commit/57b019c8b74030601dc71dc38cd2c41cf5b735d4) +- Updating tape [`91d94f9`](https://github.com/es-shims/object-is/commit/91d94f9b06c4a86942b077979536a8c2994ab374) + +## v0.0.0 - 2014-02-17 + +### Commits + +- package.json [`b724e50`](https://github.com/es-shims/object-is/commit/b724e50ea4a151f46ff5344f9dc3f00d48e60695) +- read me [`62470f5`](https://github.com/es-shims/object-is/commit/62470f58dbef4ba0b96c6c000b2802e328c54be6) +- Tests. [`639e212`](https://github.com/es-shims/object-is/commit/639e212c478afcb8c9a24753aa8fc2b2fdcfb925) +- Initial commit [`8e95b37`](https://github.com/es-shims/object-is/commit/8e95b3744c07594c49372c5732d96235f0b7d9d6) +- Implementation. [`47780bc`](https://github.com/es-shims/object-is/commit/47780bc0f483eeabd853877fa33295976cf201ae) +- Travis CI [`baaf8c7`](https://github.com/es-shims/object-is/commit/baaf8c70bc7fd88cf149af9b0c992febb5e89514) +- Covert is broken in node 0.6 [`ee040b2`](https://github.com/es-shims/object-is/commit/ee040b2f3a917da9a33a287daf8470e95db271e1) diff --git a/node_modules/object-is/LICENSE b/node_modules/object-is/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..47b7b5078fce38783c58381828d9a7f762db7866 --- /dev/null +++ b/node_modules/object-is/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/object-is/README.md b/node_modules/object-is/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a2854fd7370b77fb3b5ba32478abcc6b1c5f736e --- /dev/null +++ b/node_modules/object-is/README.md @@ -0,0 +1,60 @@ +# object-is [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +ES2015-compliant shim for Object.is - differentiates between -0 and +0, and can compare to NaN. + +Essentially, Object.is returns the same value as === - but true for NaN, and false for -0 and +0. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](https://tc39.es/ecma262). + +## Example + +```js +Object.is = require('object-is'); +var assert = require('assert'); + +assert.ok(Object.is()); +assert.ok(Object.is(undefined)); +assert.ok(Object.is(undefined, undefined)); +assert.ok(Object.is(null, null)); +assert.ok(Object.is(true, true)); +assert.ok(Object.is(false, false)); +assert.ok(Object.is('foo', 'foo')); + +var arr = [1, 2]; +assert.ok(Object.is(arr, arr)); +assert.equal(Object.is(arr, [1, 2]), false); + +assert.ok(Object.is(0, 0)); +assert.ok(Object.is(-0, -0)); +assert.equal(Object.is(0, -0), false); + +assert.ok(Object.is(NaN, NaN)); +assert.ok(Object.is(Infinity, Infinity)); +assert.ok(Object.is(-Infinity, -Infinity)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.com/package/object-is +[npm-version-svg]: https://versionbadg.es/es-shims/object-is.svg +[deps-svg]: https://david-dm.org/es-shims/object-is.svg +[deps-url]: https://david-dm.org/es-shims/object-is +[dev-deps-svg]: https://david-dm.org/es-shims/object-is/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/object-is#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/object-is.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/object-is.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/object-is.svg +[downloads-url]: https://npm-stat.com/charts.html?package=object-is +[codecov-image]: https://codecov.io/gh/es-shims/object-is/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/es-shims/object-is/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/es-shims/object-is +[actions-url]: https://github.com/es-shims/object-is/actions diff --git a/node_modules/object-is/auto.js b/node_modules/object-is/auto.js new file mode 100644 index 0000000000000000000000000000000000000000..8ebf606cb02ff3a8c6ef786afa37d21a19254f46 --- /dev/null +++ b/node_modules/object-is/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/node_modules/object-is/implementation.js b/node_modules/object-is/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..7b3a5652ef6aa43de8082229d05fc7ccfb571ced --- /dev/null +++ b/node_modules/object-is/implementation.js @@ -0,0 +1,19 @@ +'use strict'; + +var numberIsNaN = function (value) { + return value !== value; +}; + +module.exports = function is(a, b) { + if (a === 0 && b === 0) { + return 1 / a === 1 / b; + } + if (a === b) { + return true; + } + if (numberIsNaN(a) && numberIsNaN(b)) { + return true; + } + return false; +}; + diff --git a/node_modules/object-is/index.js b/node_modules/object-is/index.js new file mode 100644 index 0000000000000000000000000000000000000000..abf0449c9546665ebc4fbe2601e75ad937d98c17 --- /dev/null +++ b/node_modules/object-is/index.js @@ -0,0 +1,18 @@ +'use strict'; + +var define = require('define-properties'); +var callBind = require('call-bind'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var polyfill = callBind(getPolyfill(), Object); + +define(polyfill, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = polyfill; diff --git a/node_modules/object-is/package.json b/node_modules/object-is/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b5e50d4b7a4f4b6f48baa5632a658dff4dd4177b --- /dev/null +++ b/node_modules/object-is/package.json @@ -0,0 +1,96 @@ +{ + "name": "object-is", + "version": "1.1.6", + "description": "ES2015-compliant shim for Object.is - differentiates between -0 and +0", + "author": "Jordan Harband", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "lint": "eslint --ext=js,mjs .", + "postlint": "es-shim-api --bound", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/es-shims/object-is.git" + }, + "bugs": { + "url": "https://github.com/es-shims/object-is/issues" + }, + "homepage": "https://github.com/es-shims/object-is", + "keywords": [ + "is", + "Object.is", + "equality", + "sameValueZero", + "ES6", + "ES2015", + "shim", + "polyfill", + "es-shim API" + ], + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1" + }, + "devDependencies": { + "@es-shims/api": "^2.4.2", + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "functions-have-names": "^1.2.3", + "has-symbols": "^1.0.3", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5" + }, + "testling": { + "files": "test.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..12.0", + "opera/15.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/object-is/polyfill.js b/node_modules/object-is/polyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..96cd58a48e46ed1e0ee7a1cb1ac3834ff808e846 --- /dev/null +++ b/node_modules/object-is/polyfill.js @@ -0,0 +1,7 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = function getPolyfill() { + return typeof Object.is === 'function' ? Object.is : implementation; +}; diff --git a/node_modules/object-is/shim.js b/node_modules/object-is/shim.js new file mode 100644 index 0000000000000000000000000000000000000000..e6650d3850232c97eaddf8ba31a88f68dd6300b6 --- /dev/null +++ b/node_modules/object-is/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var getPolyfill = require('./polyfill'); +var define = require('define-properties'); + +module.exports = function shimObjectIs() { + var polyfill = getPolyfill(); + define(Object, { is: polyfill }, { + is: function testObjectIs() { + return Object.is !== polyfill; + } + }); + return polyfill; +}; diff --git a/node_modules/object-is/test/implementation.js b/node_modules/object-is/test/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..76de8be564660703a11fd2340eb15ff5c1c5ecfd --- /dev/null +++ b/node_modules/object-is/test/implementation.js @@ -0,0 +1,12 @@ +'use strict'; + +var implementation = require('../implementation'); +var callBind = require('call-bind'); +var test = require('tape'); +var runTests = require('./tests'); + +test('as a function', function (t) { + runTests(callBind(implementation, Object), t); + + t.end(); +}); diff --git a/node_modules/object-is/test/index.js b/node_modules/object-is/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..39f34b30717329dc0231b22da8080bf5141c1fcb --- /dev/null +++ b/node_modules/object-is/test/index.js @@ -0,0 +1,12 @@ +'use strict'; + +var index = require('../'); +var test = require('tape'); + +var runTests = require('./tests'); + +test('as a function', function (t) { + runTests(index, t); + + t.end(); +}); diff --git a/node_modules/object-is/test/shimmed.js b/node_modules/object-is/test/shimmed.js new file mode 100644 index 0000000000000000000000000000000000000000..eb8de97149166728970b2032ce5730d53b0a5c04 --- /dev/null +++ b/node_modules/object-is/test/shimmed.js @@ -0,0 +1,28 @@ +'use strict'; + +require('../auto'); + +var runTests = require('./tests'); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var callBind = require('call-bind'); +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); + +test('shimmed', function (t) { + t.equal(Object.is.length, 2, 'Object.is has a length of 2'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal(Object.is.name, 'is', 'Object.is has name "is"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(Object, 'is'), 'Object.is is not enumerable'); + et.end(); + }); + + runTests(callBind(Object.is, Object), t); + + t.end(); +}); diff --git a/node_modules/object-is/test/tests.js b/node_modules/object-is/test/tests.js new file mode 100644 index 0000000000000000000000000000000000000000..c9af9f27ff166534175067ad17e71d30e1d61c21 --- /dev/null +++ b/node_modules/object-is/test/tests.js @@ -0,0 +1,57 @@ +'use strict'; + +var hasSymbols = require('has-symbols')(); + +module.exports = function runTests(is, t) { + t.test('works with primitives', function (st) { + st.ok(is(), 'two absent args are the same'); + st.ok(is(undefined), 'undefined & one absent arg are the same'); + st.ok(is(undefined, undefined), 'undefined is undefined'); + st.ok(is(null, null), 'null is null'); + st.ok(is(true, true), 'true is true'); + st.ok(is(false, false), 'false is false'); + st.notOk(is(true, false), 'true is not false'); + st.end(); + }); + + t.test('works with NaN', function (st) { + st.ok(is(NaN, NaN), 'NaN is NaN'); + st.end(); + }); + + t.test('differentiates zeroes', function (st) { + st.ok(is(0, 0), '+0 is +0'); + st.ok(is(-0, -0), '-0 is -0'); + st.notOk(is(0, -0), '+0 is not -0'); + st.end(); + }); + + t.test('nonzero numbers', function (st) { + st.ok(is(Infinity, Infinity), 'infinity is infinity'); + st.ok(is(-Infinity, -Infinity), 'infinity is infinity'); + st.ok(is(42, 42), '42 is 42'); + st.notOk(is(42, -42), '42 is not -42'); + st.end(); + }); + + t.test('strings', function (st) { + st.ok(is('', ''), 'empty string is empty string'); + st.ok(is('foo', 'foo'), 'string is string'); + st.notOk(is('foo', 'bar'), 'string is not different string'); + st.end(); + }); + + t.test('objects', function (st) { + var obj = {}; + st.ok(is(obj, obj), 'object is same object'); + st.notOk(is(obj, {}), 'object is not different object'); + st.end(); + }); + + t.test('Symbols', { skip: !hasSymbols }, function (st) { + st.ok(is(Symbol.iterator, Symbol.iterator), 'Symbol.iterator is itself'); + st.notOk(is(Symbol(), Symbol()), 'different Symbols are not equal'); + st.notOk(is(Symbol.iterator, Object(Symbol.iterator)), 'Symbol.iterator is not boxed form of itself'); + st.end(); + }); +}; diff --git a/node_modules/object-keys/.editorconfig b/node_modules/object-keys/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..eaa214161f5cdb409c32465fd822624c633a6bd8 --- /dev/null +++ b/node_modules/object-keys/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*] +indent_style = tab; +insert_final_newline = true; +quote_type = auto; +space_after_anonymous_functions = true; +space_after_control_statements = true; +spaces_around_operators = true; +trim_trailing_whitespace = true; +spaces_in_brackets = false; +end_of_line = lf; + diff --git a/node_modules/object-keys/.eslintrc b/node_modules/object-keys/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..9a8d5b0e95e3615753a24220256ddc671ac2cedc --- /dev/null +++ b/node_modules/object-keys/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": [2, 23], + "id-length": [2, { "min": 1, "max": 40 }], + "max-params": [2, 3], + "max-statements": [2, 23], + "max-statements-per-line": [2, { "max": 2 }], + "no-extra-parens": [1], + "no-invalid-this": [1], + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "LabeledStatement", "WithStatement"], + "operator-linebreak": [2, "after"] + } +} diff --git a/node_modules/object-keys/.travis.yml b/node_modules/object-keys/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..94a6ce42df6f7716665798fab033108ab07f97b1 --- /dev/null +++ b/node_modules/object-keys/.travis.yml @@ -0,0 +1,277 @@ +language: node_js +os: + - linux +node_js: + - "11.8" + - "10.15" + - "9.11" + - "8.15" + - "7.10" + - "6.16" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "11.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.15" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true + - env: COVERAGE=true + - env: POSTTEST=true diff --git a/node_modules/object-keys/CHANGELOG.md b/node_modules/object-keys/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..b7d92df248e7c9c53413397b4e4dd50780f7cde8 --- /dev/null +++ b/node_modules/object-keys/CHANGELOG.md @@ -0,0 +1,232 @@ +1.1.1 / 2019-04-06 +================= + * [Fix] exclude deprecated Firefox keys (#53) + +1.1.0 / 2019-02-10 +================= + * [New] [Refactor] move full implementation to `implementation` entry point + * [Refactor] only evaluate the implementation if `Object.keys` is not present + * [Tests] up to `node` `v11.8`, `v10.15`, `v8.15`, `v6.16` + * [Tests] remove jscs + * [Tests] switch to `npm audit` from `nsp` + +1.0.12 / 2018-06-18 +================= + * [Fix] avoid accessing `window.applicationCache`, to avoid issues with latest Chrome on HTTP (#46) + +1.0.11 / 2016-07-05 +================= + * [Fix] exclude keys regarding the style (eg. `pageYOffset`) on `window` to avoid reflow (#32) + +1.0.10 / 2016-07-04 +================= + * [Fix] exclude `height` and `width` keys on `window` to avoid reflow (#31) + * [Fix] In IE 6, `window.external` makes `Object.keys` throw + * [Tests] up to `node` `v6.2`, `v5.10`, `v4.4` + * [Tests] use pretest/posttest for linting/security + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` + * [Dev Deps] remove unused eccheck script + dep + +1.0.9 / 2015-10-19 +================= + * [Fix] Blacklist 'frame' property on window (#16, #17) + * [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` + +1.0.8 / 2015-10-14 +================= + * [Fix] wrap automation equality bug checking in try/catch, per [es5-shim#327](https://github.com/es-shims/es5-shim/issues/327) + * [Fix] Blacklist 'window.frameElement' per [es5-shim#322](https://github.com/es-shims/es5-shim/issues/322) + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + * [Tests] up to `io.js` `v3.3`, `node` `v4.2` + * [Dev Deps] update `eslint`, `tape`, `@ljharb/eslint-config`, `jscs` + +1.0.7 / 2015-07-18 +================= + * [Fix] A proper fix for 176f03335e90d5c8d0d8125a99f27819c9b9cdad / https://github.com/es-shims/es5-shim/issues/275 that doesn't break dontEnum/constructor fixes in IE 8. + * [Fix] Remove deprecation message in Chrome by touching deprecated window properties (#15) + * [Tests] Improve test output for automation equality bugfix + * [Tests] Test on `io.js` `v2.4` + +1.0.6 / 2015-07-09 +================= + * [Fix] Use an object lookup rather than ES5's `indexOf` (#14) + * [Tests] ES3 browsers don't have `Array.isArray` + * [Tests] Fix `no-shadow` rule, as well as an IE 8 bug caused by engine NFE shadowing bugs. + +1.0.5 / 2015-07-03 +================= + * [Fix] Fix a flabbergasting IE 8 bug where `localStorage.constructor.prototype === localStorage` throws + * [Tests] Test up to `io.js` `v2.3` + * [Dev Deps] Update `nsp`, `eslint` + +1.0.4 / 2015-05-23 +================= + * Fix a Safari 5.0 bug with `Object.keys` not working with `arguments` + * Test on latest `node` and `io.js` + * Update `jscs`, `tape`, `eslint`, `nsp`, `is`, `editorconfig-tools`, `covert` + +1.0.3 / 2015-01-06 +================= + * Revert "Make `object-keys` more robust against later environment tampering" to maintain ES3 compliance + +1.0.2 / 2014-12-28 +================= + * Update lots of dev dependencies + * Tweaks to README + * Make `object-keys` more robust against later environment tampering + +1.0.1 / 2014-09-03 +================= + * Update URLs and badges in README + +1.0.0 / 2014-08-26 +================= + * v1.0.0 + +0.6.1 / 2014-08-25 +================= + * v0.6.1 + * Updating dependencies (tape, covert, is) + * Update badges in readme + * Use separate var statements + +0.6.0 / 2014-04-23 +================= + * v0.6.0 + * Updating dependencies (tape, covert) + * Make sure boxed primitives, and arguments objects, work properly in ES3 browsers + * Improve test matrix: test all node versions, but only latest two stables are a failure + * Remove internal foreach shim. + +0.5.1 / 2014-03-09 +================= + * 0.5.1 + * Updating dependencies (tape, covert, is) + * Removing forEach from the module (but keeping it in tests) + +0.5.0 / 2014-01-30 +================= + * 0.5.0 + * Explicitly returning the shim, instead of returning native Object.keys when present + * Adding a changelog. + * Cleaning up IIFE wrapping + * Testing on node 0.4 through 0.11 + +0.4.0 / 2013-08-14 +================== + + * v0.4.0 + * In Chrome 4-10 and Safari 4, typeof (new RegExp) === 'function' + * If it's a string, make sure to use charAt instead of brackets. + * Only use Function#call if necessary. + * Making sure the context tests actually run. + * Better function detection + * Adding the android browser + * Fixing testling files + * Updating tape + * Removing the "is" dependency. + * Making an isArguments shim. + * Adding a local forEach shim and tests. + * Updating paths. + * Moving the shim test. + * v0.3.0 + +0.3.0 / 2013-05-18 +================== + + * README tweak. + * Fixing constructor enum issue. Fixes [#5](https://github.com/ljharb/object-keys/issues/5). + * Adding a test for [#5](https://github.com/ljharb/object-keys/issues/5) + * Updating readme. + * Updating dependencies. + * Giving credit to lodash. + * Make sure that a prototype's constructor property is not enumerable. Fixes [#3](https://github.com/ljharb/object-keys/issues/3). + * Adding additional tests to handle arguments objects, and to skip "prototype" in functions. Fixes [#2](https://github.com/ljharb/object-keys/issues/2). + * Fixing a typo on this test for [#3](https://github.com/ljharb/object-keys/issues/3). + * Adding node 0.10 to travis. + * Adding an IE < 9 test per [#3](https://github.com/ljharb/object-keys/issues/3) + * Adding an iOS 5 mobile Safari test per [#2](https://github.com/ljharb/object-keys/issues/2) + * Moving "indexof" and "is" to be dev dependencies. + * Making sure the shim works with functions. + * Flattening the tests. + +0.2.0 / 2013-05-10 +================== + + * v0.2.0 + * Object.keys should work with arrays. + +0.1.8 / 2013-05-10 +================== + + * v0.1.8 + * Upgrading dependencies. + * Using a simpler check. + * Fixing a bug in hasDontEnumBug browsers. + * Using the newest tape! + * Fixing this error test. + * "undefined" is probably a reserved word in ES3. + * Better test message. + +0.1.7 / 2013-04-17 +================== + + * Upgrading "is" once more. + * The key "null" is breaking some browsers. + +0.1.6 / 2013-04-17 +================== + + * v0.1.6 + * Upgrading "is" + +0.1.5 / 2013-04-14 +================== + + * Bumping version. + * Adding more testling browsers. + * Updating "is" + +0.1.4 / 2013-04-08 +================== + + * Using "is" instead of "is-extended". + +0.1.3 / 2013-04-07 +================== + + * Using "foreach" instead of my own shim. + * Removing "tap"; I'll just wait for "tape" to fix its node 0.10 bug. + +0.1.2 / 2013-04-03 +================== + + * Adding dependency status; moving links to an index at the bottom. + * Upgrading is-extended; version 0.1.2 + * Adding an npm version badge. + +0.1.1 / 2013-04-01 +================== + + * Adding Travis CI. + * Bumping the version. + * Adding indexOf since IE sucks. + * Adding a forEach shim since older browsers don't have Array#forEach. + * Upgrading tape - 0.3.2 uses Array#map + * Using explicit end instead of plan. + * Can't test with Array.isArray in older browsers. + * Using is-extended. + * Fixing testling files. + * JSHint/JSLint-ing. + * Removing an unused object. + * Using strict mode. + +0.1.0 / 2013-03-30 +================== + + * Changing the exports should have meant a higher version bump. + * Oops, fixing the repo URL. + * Adding more tests. + * 0.0.2 + * Merge branch 'export_one_thing'; closes [#1](https://github.com/ljharb/object-keys/issues/1) + * Move shim export to a separate file. diff --git a/node_modules/object-keys/LICENSE b/node_modules/object-keys/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..28553fdd06841b14fea43a5093bea3a5773fe1e0 --- /dev/null +++ b/node_modules/object-keys/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (C) 2013 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/object-keys/README.md b/node_modules/object-keys/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ed4c277023a8a48522ec922f35ed27dda62a0ea8 --- /dev/null +++ b/node_modules/object-keys/README.md @@ -0,0 +1,76 @@ +#object-keys [![Version Badge][npm-version-svg]][package-url] + +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +[![browser support][testling-svg]][testling-url] + +An Object.keys shim. Invoke its "shim" method to shim Object.keys if it is unavailable. + +Most common usage: +```js +var keys = Object.keys || require('object-keys'); +``` + +## Example + +```js +var keys = require('object-keys'); +var assert = require('assert'); +var obj = { + a: true, + b: true, + c: true +}; + +assert.deepEqual(keys(obj), ['a', 'b', 'c']); +``` + +```js +var keys = require('object-keys'); +var assert = require('assert'); +/* when Object.keys is not present */ +delete Object.keys; +var shimmedKeys = keys.shim(); +assert.equal(shimmedKeys, keys); +assert.deepEqual(Object.keys(obj), keys(obj)); +``` + +```js +var keys = require('object-keys'); +var assert = require('assert'); +/* when Object.keys is present */ +var shimmedKeys = keys.shim(); +assert.equal(shimmedKeys, Object.keys); +assert.deepEqual(Object.keys(obj), keys(obj)); +``` + +## Source +Implementation taken directly from [es5-shim][es5-shim-url], with modifications, including from [lodash][lodash-url]. + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/object-keys +[npm-version-svg]: http://versionbadg.es/ljharb/object-keys.svg +[travis-svg]: https://travis-ci.org/ljharb/object-keys.svg +[travis-url]: https://travis-ci.org/ljharb/object-keys +[deps-svg]: https://david-dm.org/ljharb/object-keys.svg +[deps-url]: https://david-dm.org/ljharb/object-keys +[dev-deps-svg]: https://david-dm.org/ljharb/object-keys/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/object-keys#info=devDependencies +[testling-svg]: https://ci.testling.com/ljharb/object-keys.png +[testling-url]: https://ci.testling.com/ljharb/object-keys +[es5-shim-url]: https://github.com/es-shims/es5-shim/blob/master/es5-shim.js#L542-589 +[lodash-url]: https://github.com/lodash/lodash +[npm-badge-png]: https://nodei.co/npm/object-keys.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/object-keys.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/object-keys.svg +[downloads-url]: http://npm-stat.com/charts.html?package=object-keys + diff --git a/node_modules/object-keys/implementation.js b/node_modules/object-keys/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..5b329861954977f86c06e1efaf4d30a3f9629a0d --- /dev/null +++ b/node_modules/object-keys/implementation.js @@ -0,0 +1,122 @@ +'use strict'; + +var keysShim; +if (!Object.keys) { + // modified from https://github.com/es-shims/es5-shim + var has = Object.prototype.hasOwnProperty; + var toStr = Object.prototype.toString; + var isArgs = require('./isArguments'); // eslint-disable-line global-require + var isEnumerable = Object.prototype.propertyIsEnumerable; + var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); + var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); + var dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ]; + var equalsConstructorPrototype = function (o) { + var ctor = o.constructor; + return ctor && ctor.prototype === o; + }; + var excludedKeys = { + $applicationCache: true, + $console: true, + $external: true, + $frame: true, + $frameElement: true, + $frames: true, + $innerHeight: true, + $innerWidth: true, + $onmozfullscreenchange: true, + $onmozfullscreenerror: true, + $outerHeight: true, + $outerWidth: true, + $pageXOffset: true, + $pageYOffset: true, + $parent: true, + $scrollLeft: true, + $scrollTop: true, + $scrollX: true, + $scrollY: true, + $self: true, + $webkitIndexedDB: true, + $webkitStorageInfo: true, + $window: true + }; + var hasAutomationEqualityBug = (function () { + /* global window */ + if (typeof window === 'undefined') { return false; } + for (var k in window) { + try { + if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { + try { + equalsConstructorPrototype(window[k]); + } catch (e) { + return true; + } + } + } catch (e) { + return true; + } + } + return false; + }()); + var equalsConstructorPrototypeIfNotBuggy = function (o) { + /* global window */ + if (typeof window === 'undefined' || !hasAutomationEqualityBug) { + return equalsConstructorPrototype(o); + } + try { + return equalsConstructorPrototype(o); + } catch (e) { + return false; + } + }; + + keysShim = function keys(object) { + var isObject = object !== null && typeof object === 'object'; + var isFunction = toStr.call(object) === '[object Function]'; + var isArguments = isArgs(object); + var isString = isObject && toStr.call(object) === '[object String]'; + var theKeys = []; + + if (!isObject && !isFunction && !isArguments) { + throw new TypeError('Object.keys called on a non-object'); + } + + var skipProto = hasProtoEnumBug && isFunction; + if (isString && object.length > 0 && !has.call(object, 0)) { + for (var i = 0; i < object.length; ++i) { + theKeys.push(String(i)); + } + } + + if (isArguments && object.length > 0) { + for (var j = 0; j < object.length; ++j) { + theKeys.push(String(j)); + } + } else { + for (var name in object) { + if (!(skipProto && name === 'prototype') && has.call(object, name)) { + theKeys.push(String(name)); + } + } + } + + if (hasDontEnumBug) { + var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); + + for (var k = 0; k < dontEnums.length; ++k) { + if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { + theKeys.push(dontEnums[k]); + } + } + } + return theKeys; + }; +} +module.exports = keysShim; diff --git a/node_modules/object-keys/index.js b/node_modules/object-keys/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a43807d2f695c7b101bf95a24620227ab00947de --- /dev/null +++ b/node_modules/object-keys/index.js @@ -0,0 +1,32 @@ +'use strict'; + +var slice = Array.prototype.slice; +var isArgs = require('./isArguments'); + +var origKeys = Object.keys; +var keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./implementation'); + +var originalKeys = Object.keys; + +keysShim.shim = function shimObjectKeys() { + if (Object.keys) { + var keysWorksWithArguments = (function () { + // Safari 5.0 bug + var args = Object.keys(arguments); + return args && args.length === arguments.length; + }(1, 2)); + if (!keysWorksWithArguments) { + Object.keys = function keys(object) { // eslint-disable-line func-name-matching + if (isArgs(object)) { + return originalKeys(slice.call(object)); + } + return originalKeys(object); + }; + } + } else { + Object.keys = keysShim; + } + return Object.keys || keysShim; +}; + +module.exports = keysShim; diff --git a/node_modules/object-keys/isArguments.js b/node_modules/object-keys/isArguments.js new file mode 100644 index 0000000000000000000000000000000000000000..f2a2a9014d925e99b46c9f776525b02442fb6005 --- /dev/null +++ b/node_modules/object-keys/isArguments.js @@ -0,0 +1,17 @@ +'use strict'; + +var toStr = Object.prototype.toString; + +module.exports = function isArguments(value) { + var str = toStr.call(value); + var isArgs = str === '[object Arguments]'; + if (!isArgs) { + isArgs = str !== '[object Array]' && + value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + toStr.call(value.callee) === '[object Function]'; + } + return isArgs; +}; diff --git a/node_modules/object-keys/package.json b/node_modules/object-keys/package.json new file mode 100644 index 0000000000000000000000000000000000000000..99ea923870ceb9e896828018d22a083dc4e70545 --- /dev/null +++ b/node_modules/object-keys/package.json @@ -0,0 +1,88 @@ +{ + "name": "object-keys", + "version": "1.1.1", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + { + "name": "Raynos", + "email": "raynos2@gmail.com" + }, + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net" + }, + { + "name": "Ivan Starkov", + "email": "istarkov@gmail.com" + }, + { + "name": "Gary Katsevman", + "email": "git@gkatsev.com" + } + ], + "description": "An Object.keys replacement, in case Object.keys is not available. From https://github.com/es-shims/es5-shim", + "license": "MIT", + "main": "index.js", + "scripts": { + "pretest": "npm run --silent lint", + "test": "npm run --silent tests-only", + "posttest": "npm run --silent audit", + "tests-only": "node test/index.js", + "coverage": "covert test/*.js", + "coverage-quiet": "covert test/*.js --quiet", + "lint": "eslint .", + "preaudit": "npm install --package-lock --package-lock-only", + "audit": "npm audit", + "postaudit": "rm package-lock.json" + }, + "repository": { + "type": "git", + "url": "git://github.com/ljharb/object-keys.git" + }, + "keywords": [ + "Object.keys", + "keys", + "ES5", + "shim" + ], + "dependencies": {}, + "devDependencies": { + "@ljharb/eslint-config": "^13.1.1", + "covert": "^1.1.1", + "eslint": "^5.13.0", + "foreach": "^2.0.5", + "indexof": "^0.0.1", + "is": "^3.3.0", + "tape": "^4.9.2" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/object-keys/test/index.js b/node_modules/object-keys/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5402465a19b5b697128197df09d014c791542c51 --- /dev/null +++ b/node_modules/object-keys/test/index.js @@ -0,0 +1,5 @@ +'use strict'; + +require('./isArguments'); + +require('./shim'); diff --git a/node_modules/object.assign/.editorconfig b/node_modules/object.assign/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..bc228f8269443bf772b437890dde7756a3e8a894 --- /dev/null +++ b/node_modules/object.assign/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/object.assign/.eslintrc b/node_modules/object.assign/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..131851698feacc552ca62b379186430f0257b2b0 --- /dev/null +++ b/node_modules/object.assign/.eslintrc @@ -0,0 +1,28 @@ +{ + "root": true, + + "extends": "@ljharb", + + "ignorePatterns": ["dist/"], + + "rules": { + "eqeqeq": [2, "allow-null"], + "id-length": [2, { "min": 1, "max": 30 }], + "max-statements": [2, 33], + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": [1, { "ignore": [0] }], + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "no-invalid-this": 1, + "max-lines-per-function": 0, + "max-statements-per-line": [2, { "max": 3 }], + "no-magic-numbers": 0, + }, + }, + ], +} diff --git a/node_modules/object.assign/.github/FUNDING.yml b/node_modules/object.assign/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..ef7fdbfa08a090928219b6ae36796c5d73b4a952 --- /dev/null +++ b/node_modules/object.assign/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/object.assign +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/object.assign/.nycrc b/node_modules/object.assign/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/node_modules/object.assign/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/object.assign/CHANGELOG.md b/node_modules/object.assign/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..509f766dc90e71776ab3af19b422915f887b4c0f --- /dev/null +++ b/node_modules/object.assign/CHANGELOG.md @@ -0,0 +1,246 @@ +4.1.7 / 2024-12-18 +================== + * [Deps] add missing `es-object-atoms` (#86) + +4.1.6 / 2024-12-18 +================== + * [Refactor] use `call-bound` directly; use `es-object-atoms` + * [Deps] update `call-bind`, `has-symbols` + * [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `hasown`, `mock-property`, `ses`, `tape` + * [actions] split out node 10-20, and 20+ + * [actions] remove redundant finisher + * [Tests] replace `aud` with `npm audit` + +4.1.5 / 2023-11-30 +================== + * [meta] republish without testing HTML file (#85) + * [Deps] update `call-bind`, `define-properties` + * [Dev Deps] use `hasown` instead of `has` + * [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `aud`, `npmignore`, `mock-property`, `tape` + * [actions] update rebase action + +4.1.4 / 2022-08-16 +================== + * [meta] fix `npmignore` integration (#83) + +4.1.3 / 2022-08-05 +================== + * [Refactor] make steps closer to actual spec + * [Refactor] simplify object coercible check + * [readme] remove defunct badges, add coverage and actions badges + * [eslint] ignore coverage output + * [meta] use `npmignore` to autogenerate an npmignore file + * [meta] remove audit-level + * [Deps] update `call-bind`, `define-properties`, `has-symbols` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `aud`, `functions-have-names`, `safe-publish-latest`, `ses`, `tape` + * [actions] use `node/install` instead of `node/run`; use `codecov` action + * [actions] reuse common workflows + * [actions] update codecov uploader + * [Tests] add implementation tests + * [Tests] use `mock-property` + * [Tests] disable posttest pending `aud` handling `file:` deps + * [Tests] migrate remaining tests to Github Actions (#81) + * [Tests] gitignore coverage output + * [Tests] test node v1-v9 on Github Actions instead of travis; resume testing all minors (#80) + +4.1.2 / 2020-10-30 +================== + * [Refactor] use extracted `call-bind` instead of full `es-abstract` + * [Dev Deps] update `eslint`, `ses`, `browserify` + * [Tests] run tests in SES + * [Tests] ses-compat: show error stacks + +4.1.1 / 2020-09-11 +================== + * [Fix] avoid mutating `Object.assign` in modern engines + * [Refactor] use `callBind` from `es-abstract` instead of `function-bind` + * [Deps] update `has-symbols`, `object-keys`, `define-properties` + * [meta] add `funding` field, FUNDING.yml + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `browserify`, `covert`, `for-each`, `is`, `tape`, `functions-have-names`; add `aud`, `safe-publish-latest`; remove `jscs` + * [actions] add Require Allow Edits workflow + * [actions] add automatic rebasing / merge commit blocking + * [Tests] ses-compat - add test to ensure package initializes correctly after ses lockdown (#77) + * [Tests] Add passing test for a source of `window.location` (#68) + * [Tests] use shared travis-ci config + * [Tests] use `npx aud` instead of `npm audit` with hoops or `nsp` + * [Tests] use `functions-have-names` + +4.1.0 / 2017-12-21 +================== + * [New] add `auto` entry point (#52) + * [Refactor] Use `has-symbols` module + * [Deps] update `function-bind`, `object-keys` + * [Dev Deps] update `@es-shims/api`, `browserify`, `nsp`, `eslint`, `@ljharb/eslint-config`, `is` + * [Tests] up to `node` `v9.3`, `v8.9`, `v6.12`; use `nvm install-latest-npm`; pin included builds to LTS + +4.0.4 / 2016-07-04 +================== + * [Fix] Cache original `getOwnPropertySymbols`, and use that when `Object.getOwnPropertySymbols` is unavailable + * [Deps] update `object-keys` + * [Dev Deps] update `eslint`, `get-own-property-symbols`, `core-js`, `jscs`, `nsp`, `browserify`, `@ljharb/eslint-config`, `tape`, `@es-shims/api` + * [Tests] up to `node` `v6.2`, `v5.10`, `v4.4` + * [Tests] run sham tests on node 0.10 + * [Tests] use pretest/posttest for linting/security + +4.0.3 / 2015-10-21 +================== + * [Fix] Support core-js's Symbol sham (#17) + * [Fix] Ensure that properties removed or made non-enumerable during enumeration are not assigned (#16) + * [Fix] Avoid looking up keys and values more than once + * [Tests] Avoid using `reduce` so `npm run test:shams:corejs` passes in `node` `v0.8` ([core-js#122](https://github.com/zloirock/core-js/issues/122)) + * [Tests] Refactor to use my conventional structure that separates shimmed, implementation, and common tests + * [Tests] Create `npm run test:shams` and better organize tests for symbol shams + * [Tests] Remove `nsp` in favor of `requiresafe` + +4.0.2 / 2015-10-20 +================== + * [Fix] Ensure correct property enumeration order, particularly in v8 (#15) + * [Deps] update `object-keys`, `define-properties` + * [Dev Deps] update `browserify`, `is`, `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` + * [Tests] up to `io.js` `v3.3`, `node` `v4.2` + +4.0.1 / 2015-08-16 +================== + * [Docs] Add `Symbol` note to readme + +4.0.0 / 2015-08-15 +================== + * [Breaking] Implement the [es-shim API](es-shims/api). + * [Robustness] Make implementation robust against later modification of environment methods. + * [Refactor] Move implementation to `implementation.js` + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + * [Deps] update `object-keys`, `define-properties` + * [Dev Deps] update `browserify`, `tape`, `eslint`, `jscs`, `browserify` + * [Tests] Add `npm run tests-only` + * [Tests] use my personal shared `eslint` config. + * [Tests] up to `io.js` `v3.0` + +3.0.1 / 2015-06-28 +================== + * Cache `Object` and `Array#push` to make the shim more robust. + * [Fix] Remove use of `Array#filter`, which isn't in ES3. + * [Deps] Update `object-keys`, `define-properties` + * [Dev Deps] Update `get-own-property-symbols`, `browserify`, `eslint`, `nsp` + * [Tests] Test up to `io.js` `v2.3` + * [Tests] Adding `Object.assign` tests for non-object targets, per https://github.com/paulmillr/es6-shim/issues/348 + +3.0.0 / 2015-05-20 +================== + * Attempt to feature-detect Symbols, even if `typeof Symbol() !== 'symbol'` (#12) + * Make a separate `hasSymbols` internal module + * Update `browserify`, `eslint` + +2.0.3 / 2015-06-28 +================== + * Cache `Object` and `Array#push` to make the shim more robust. + * [Fix] Remove use of `Array#filter`, which isn't in ES3 + * [Deps] Update `object-keys`, `define-properties` + * [Dev Deps] Update `browserify`, `nsp`, `eslint` + * [Tests] Test up to `io.js` `v2.3` + +2.0.2 / 2015-05-20 +================== + * Make sure `.shim` is non-enumerable. + * Refactor `.shim` implementation to use `define-properties` predicates, rather than `delete`ing the original. + * Update docs to match spec/implementation. (#11) + * Add `npm run eslint` + * Test up to `io.js` `v2.0` + * Update `jscs`, `browserify`, `covert` + +2.0.1 / 2015-04-12 +================== + * Make sure non-enumerable Symbols are excluded. + +2.0.0 / 2015-04-12 +================== + * Make sure the shim function overwrites a broken implementation with pending exceptions. + * Ensure shim is not enumerable using `define-properties` + * Ensure `Object.assign` includes symbols. + * All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. + * Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. + * Add `npm run security` via `nsp` + * Update `browserify`, `jscs`, `tape`, `object-keys`, `is` + +1.1.1 / 2014-12-14 +================== + * Actually include the browser build in `npm` + +1.1.0 / 2014-12-14 +================== + * Add `npm run build`, and build an automatic-shimming browser distribution as part of the npm publish process. + * Update `is`, `jscs` + +1.0.3 / 2014-11-29 +================== + * Revert "optimize --production installs" + +1.0.2 / 2014-11-27 +================== + * Update `jscs`, `is`, `object-keys`, `tape` + * Add badges to README + * Name URLs in README + * Lock `covert` to `v1.0.0` + * Optimize --production installs + +1.0.1 / 2014-08-26 +================== + * Update `is`, `covert` + +1.0.0 / 2014-08-07 +================== + * Update `object-keys`, `tape` + +0.5.0 / 2014-07-31 +================== + * Object.assign no longer throws on null or undefined sources, per https://bugs.ecmascript.org/show_bug.cgi?id=3096 + +0.4.3 / 2014-07-30 +================== + * Don’t modify vars in the function signature, since it deoptimizes v8 + +0.4.2 / 2014-07-30 +================== + * Fixing the version number: v0.4.2 + +0.4.1 / 2014-07-19 +================== + * Revert "Use the native Object.keys if it’s available." + +0.4.0 / 2014-07-19 +================== + * Use the native Object.keys if it’s available. + * Fixes [#2](https://github.com/ljharb/object.assign/issues/2). + * Adding failing tests for [#2](https://github.com/ljharb/object.assign/issues/2). + * Fix indentation. + * Adding `npm run lint` + * Update `tape`, `covert` + * README: Use SVG badge for Travis [#1](https://github.com/ljharb/object.assign/issues/1) from mathiasbynens/patch-1 + +0.3.1 / 2014-04-10 +================== + * Object.assign does partially modify objects if it throws, per https://twitter.com/awbjs/status/454320863093862400 + +0.3.0 / 2014-04-10 +================== + * Update with newest ES6 behavior - Object.assign now takes a variable number of source objects. + * Update `tape` + * Make sure old and unstable nodes don’t fail Travis + +0.2.1 / 2014-03-16 +================== + * Let object-keys handle the fallback + * Update dependency badges + * Adding bower.json + +0.2.0 / 2014-03-16 +================== + * Use a for loop, because ES3 browsers don’t have "reduce" + +0.1.1 / 2014-03-14 +================== + * Updating readme + +0.1.0 / 2014-03-14 +================== + * Initial release. + diff --git a/node_modules/object.assign/LICENSE b/node_modules/object.assign/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ab29cbd63b72d5d30b0cc92162db190f2e4b9a36 --- /dev/null +++ b/node_modules/object.assign/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/node_modules/object.assign/README.md b/node_modules/object.assign/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8e933fee6260157922ea8ebd8f46795e030d6df4 --- /dev/null +++ b/node_modules/object.assign/README.md @@ -0,0 +1,136 @@ +# object.assign [![Version Badge][npm-version-svg]][npm-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][npm-url] + +An Object.assign shim. Invoke its "shim" method to shim Object.assign if it is unavailable. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-object.assign). In an ES6 environment, it will also work properly with `Symbol`s. + +Takes a minimum of 2 arguments: `target` and `source`. +Takes a variable sized list of source arguments - at least 1, as many as you want. +Throws a TypeError if the `target` argument is `null` or `undefined`. + +Most common usage: +```js +var assign = require('object.assign').getPolyfill(); // returns native method if compliant + /* or */ +var assign = require('object.assign/polyfill')(); // returns native method if compliant +``` + +## Example + +```js +var assert = require('assert'); + +// Multiple sources! +var target = { a: true }; +var source1 = { b: true }; +var source2 = { c: true }; +var sourceN = { n: true }; + +var expected = { + a: true, + b: true, + c: true, + n: true +}; + +assign(target, source1, source2, sourceN); +assert.deepEqual(target, expected); // AWESOME! +``` + +```js +var target = { + a: true, + b: true, + c: true +}; +var source1 = { + c: false, + d: false +}; +var sourceN = { + e: false +}; + +var assigned = assign(target, source1, sourceN); +assert.equal(target, assigned); // returns the target object +assert.deepEqual(assigned, { + a: true, + b: true, + c: false, + d: false, + e: false +}); +``` + +```js +/* when Object.assign is not present */ +delete Object.assign; +var shimmedAssign = require('object.assign').shim(); + /* or */ +var shimmedAssign = require('object.assign/shim')(); + +assert.equal(shimmedAssign, assign); + +var target = { + a: true, + b: true, + c: true +}; +var source = { + c: false, + d: false, + e: false +}; + +var assigned = assign(target, source); +assert.deepEqual(Object.assign(target, source), assign(target, source)); +``` + +```js +/* when Object.assign is present */ +var shimmedAssign = require('object.assign').shim(); +assert.equal(shimmedAssign, Object.assign); + +var target = { + a: true, + b: true, + c: true +}; +var source = { + c: false, + d: false, + e: false +}; + +assert.deepEqual(Object.assign(target, source), assign(target, source)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[npm-url]: https://npmjs.org/package/object.assign +[npm-version-svg]: http://versionbadg.es/ljharb/object.assign.svg +[travis-svg]: https://travis-ci.org/ljharb/object.assign.svg +[travis-url]: https://travis-ci.org/ljharb/object.assign +[deps-svg]: https://david-dm.org/ljharb/object.assign.svg?theme=shields.io +[deps-url]: https://david-dm.org/ljharb/object.assign +[dev-deps-svg]: https://david-dm.org/ljharb/object.assign/dev-status.svg?theme=shields.io +[dev-deps-url]: https://david-dm.org/ljharb/object.assign#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/object.assign.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/object.assign.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/object.assign.svg +[downloads-url]: http://npm-stat.com/charts.html?package=object.assign +[codecov-image]: https://codecov.io/gh/ljharb/object.assign/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/object.assign/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/object.assign +[actions-url]: https://github.com/ljharb/object.assign/actions diff --git a/node_modules/object.assign/auto.js b/node_modules/object.assign/auto.js new file mode 100644 index 0000000000000000000000000000000000000000..8ebf606cb02ff3a8c6ef786afa37d21a19254f46 --- /dev/null +++ b/node_modules/object.assign/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/node_modules/object.assign/dist/browser.js b/node_modules/object.assign/dist/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..a644f9bc91dd9f247921e199e1e9ff39f9700197 --- /dev/null +++ b/node_modules/object.assign/dist/browser.js @@ -0,0 +1,1304 @@ +(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;i 0 ? adjustedLength : 0), + true + ); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} + +},{"call-bind-apply-helpers":8,"call-bind-apply-helpers/applyBind":5,"es-define-property":15,"set-function-length":41}],11:[function(require,module,exports){ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBindBasic = require('call-bind-apply-helpers'); + +/** @type {(thisArg: string, searchString: string, position?: number) => number} */ +var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]); + +/** @type {import('.')} */ +module.exports = function callBoundIntrinsic(name, allowMissing) { + // eslint-disable-next-line no-extra-parens + var intrinsic = /** @type {Parameters[0][0]} */ (GetIntrinsic(name, !!allowMissing)); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBindBasic([intrinsic]); + } + return intrinsic; +}; + +},{"call-bind-apply-helpers":8,"get-intrinsic":26}],12:[function(require,module,exports){ +'use strict'; + +var $defineProperty = require('es-define-property'); + +var $SyntaxError = require('es-errors/syntax'); +var $TypeError = require('es-errors/type'); + +var gopd = require('gopd'); + +/** @type {import('.')} */ +module.exports = function defineDataProperty( + obj, + property, + value +) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new $TypeError('`obj` must be an object or a function`'); + } + if (typeof property !== 'string' && typeof property !== 'symbol') { + throw new $TypeError('`property` must be a string or a symbol`'); + } + if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { + throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null'); + } + if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { + throw new $TypeError('`nonWritable`, if provided, must be a boolean or null'); + } + if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { + throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null'); + } + if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { + throw new $TypeError('`loose`, if provided, must be a boolean'); + } + + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + + /* @type {false | TypedPropertyDescriptor} */ + var desc = !!gopd && gopd(obj, property); + + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value: value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { + // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable + obj[property] = value; // eslint-disable-line no-param-reassign + } else { + throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); + } +}; + +},{"es-define-property":15,"es-errors/syntax":20,"es-errors/type":21,"gopd":28}],13:[function(require,module,exports){ +'use strict'; + +var keys = require('object-keys'); +var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; + +var toStr = Object.prototype.toString; +var concat = Array.prototype.concat; +var defineDataProperty = require('define-data-property'); + +var isFunction = function (fn) { + return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; +}; + +var supportsDescriptors = require('has-property-descriptors')(); + +var defineProperty = function (object, name, value, predicate) { + if (name in object) { + if (predicate === true) { + if (object[name] === value) { + return; + } + } else if (!isFunction(predicate) || !predicate()) { + return; + } + } + + if (supportsDescriptors) { + defineDataProperty(object, name, value, true); + } else { + defineDataProperty(object, name, value); + } +}; + +var defineProperties = function (object, map) { + var predicates = arguments.length > 2 ? arguments[2] : {}; + var props = keys(map); + if (hasSymbols) { + props = concat.call(props, Object.getOwnPropertySymbols(map)); + } + for (var i = 0; i < props.length; i += 1) { + defineProperty(object, props[i], map[props[i]], predicates[props[i]]); + } +}; + +defineProperties.supportsDescriptors = !!supportsDescriptors; + +module.exports = defineProperties; + +},{"define-data-property":12,"has-property-descriptors":29,"object-keys":39}],14:[function(require,module,exports){ +'use strict'; + +var callBind = require('call-bind-apply-helpers'); +var gOPD = require('gopd'); + +var hasProtoAccessor; +try { + // eslint-disable-next-line no-extra-parens, no-proto + hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; +} catch (e) { + if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { + throw e; + } +} + +// eslint-disable-next-line no-extra-parens +var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); + +var $Object = Object; +var $getPrototypeOf = $Object.getPrototypeOf; + +/** @type {import('./get')} */ +module.exports = desc && typeof desc.get === 'function' + ? callBind([desc.get]) + : typeof $getPrototypeOf === 'function' + ? /** @type {import('./get')} */ function getDunder(value) { + // eslint-disable-next-line eqeqeq + return $getPrototypeOf(value == null ? value : $Object(value)); + } + : false; + +},{"call-bind-apply-helpers":8,"gopd":28}],15:[function(require,module,exports){ +'use strict'; + +/** @type {import('.')} */ +var $defineProperty = Object.defineProperty || false; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} + +module.exports = $defineProperty; + +},{}],16:[function(require,module,exports){ +'use strict'; + +/** @type {import('./eval')} */ +module.exports = EvalError; + +},{}],17:[function(require,module,exports){ +'use strict'; + +/** @type {import('.')} */ +module.exports = Error; + +},{}],18:[function(require,module,exports){ +'use strict'; + +/** @type {import('./range')} */ +module.exports = RangeError; + +},{}],19:[function(require,module,exports){ +'use strict'; + +/** @type {import('./ref')} */ +module.exports = ReferenceError; + +},{}],20:[function(require,module,exports){ +'use strict'; + +/** @type {import('./syntax')} */ +module.exports = SyntaxError; + +},{}],21:[function(require,module,exports){ +'use strict'; + +/** @type {import('./type')} */ +module.exports = TypeError; + +},{}],22:[function(require,module,exports){ +'use strict'; + +/** @type {import('./uri')} */ +module.exports = URIError; + +},{}],23:[function(require,module,exports){ +'use strict'; + +/** @type {import('.')} */ +module.exports = Object; + +},{}],24:[function(require,module,exports){ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + +},{}],25:[function(require,module,exports){ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; + +},{"./implementation":24}],26:[function(require,module,exports){ +'use strict'; + +var undefined; + +var $Object = require('es-object-atoms'); + +var $Error = require('es-errors'); +var $EvalError = require('es-errors/eval'); +var $RangeError = require('es-errors/range'); +var $ReferenceError = require('es-errors/ref'); +var $SyntaxError = require('es-errors/syntax'); +var $TypeError = require('es-errors/type'); +var $URIError = require('es-errors/uri'); + +var abs = require('math-intrinsics/abs'); +var floor = require('math-intrinsics/floor'); +var max = require('math-intrinsics/max'); +var min = require('math-intrinsics/min'); +var pow = require('math-intrinsics/pow'); + +var $Function = Function; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = require('gopd'); +var $defineProperty = require('es-define-property'); + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = require('has-symbols')(); +var getDunderProto = require('dunder-proto/get'); + +var getProto = (typeof Reflect === 'function' && Reflect.getPrototypeOf) + || $Object.getPrototypeOf + || getDunderProto; + +var $apply = require('call-bind-apply-helpers/functionApply'); +var $call = require('call-bind-apply-helpers/functionCall'); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': $Object, + '%Object.getOwnPropertyDescriptor%': $gOPD, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, + + '%Function.prototype.call%': $call, + '%Function.prototype.apply%': $apply, + '%Object.defineProperty%': $defineProperty, + '%Math.abs%': abs, + '%Math.floor%': floor, + '%Math.max%': max, + '%Math.min%': min, + '%Math.pow%': pow +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = require('function-bind'); +var hasOwn = require('hasown'); +var $concat = bind.call($call, Array.prototype.concat); +var $spliceApply = bind.call($apply, Array.prototype.splice); +var $replace = bind.call($call, String.prototype.replace); +var $strSlice = bind.call($call, String.prototype.slice); +var $exec = bind.call($call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; + +},{"call-bind-apply-helpers/functionApply":6,"call-bind-apply-helpers/functionCall":7,"dunder-proto/get":14,"es-define-property":15,"es-errors":17,"es-errors/eval":16,"es-errors/range":18,"es-errors/ref":19,"es-errors/syntax":20,"es-errors/type":21,"es-errors/uri":22,"es-object-atoms":23,"function-bind":25,"gopd":28,"has-symbols":30,"hasown":32,"math-intrinsics/abs":33,"math-intrinsics/floor":34,"math-intrinsics/max":35,"math-intrinsics/min":36,"math-intrinsics/pow":37}],27:[function(require,module,exports){ +'use strict'; + +/** @type {import('./gOPD')} */ +module.exports = Object.getOwnPropertyDescriptor; + +},{}],28:[function(require,module,exports){ +'use strict'; + +/** @type {import('.')} */ +var $gOPD = require('./gOPD'); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; + +},{"./gOPD":27}],29:[function(require,module,exports){ +'use strict'; + +var $defineProperty = require('es-define-property'); + +var hasPropertyDescriptors = function hasPropertyDescriptors() { + return !!$defineProperty; +}; + +hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + // node v0.6 has a bug where array lengths can be Set but not Defined + if (!$defineProperty) { + return null; + } + try { + return $defineProperty([], 'length', { value: 1 }).length !== 1; + } catch (e) { + // In Firefox 4-22, defining length on an array throws an exception. + return true; + } +}; + +module.exports = hasPropertyDescriptors; + +},{"es-define-property":15}],30:[function(require,module,exports){ +'use strict'; + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = require('./shams'); + +/** @type {import('.')} */ +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; + +},{"./shams":31}],31:[function(require,module,exports){ +'use strict'; + +/** @type {import('./shams')} */ +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + /** @type {{ [k in symbol]?: unknown }} */ + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + // eslint-disable-next-line no-extra-parens + var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; + +},{}],32:[function(require,module,exports){ +'use strict'; + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = require('function-bind'); + +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); + +},{"function-bind":25}],33:[function(require,module,exports){ +'use strict'; + +/** @type {import('./abs')} */ +module.exports = Math.abs; + +},{}],34:[function(require,module,exports){ +'use strict'; + +/** @type {import('./abs')} */ +module.exports = Math.floor; + +},{}],35:[function(require,module,exports){ +'use strict'; + +/** @type {import('./max')} */ +module.exports = Math.max; + +},{}],36:[function(require,module,exports){ +'use strict'; + +/** @type {import('./min')} */ +module.exports = Math.min; + +},{}],37:[function(require,module,exports){ +'use strict'; + +/** @type {import('./pow')} */ +module.exports = Math.pow; + +},{}],38:[function(require,module,exports){ +'use strict'; + +var keysShim; +if (!Object.keys) { + // modified from https://github.com/es-shims/es5-shim + var has = Object.prototype.hasOwnProperty; + var toStr = Object.prototype.toString; + var isArgs = require('./isArguments'); // eslint-disable-line global-require + var isEnumerable = Object.prototype.propertyIsEnumerable; + var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); + var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); + var dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ]; + var equalsConstructorPrototype = function (o) { + var ctor = o.constructor; + return ctor && ctor.prototype === o; + }; + var excludedKeys = { + $applicationCache: true, + $console: true, + $external: true, + $frame: true, + $frameElement: true, + $frames: true, + $innerHeight: true, + $innerWidth: true, + $onmozfullscreenchange: true, + $onmozfullscreenerror: true, + $outerHeight: true, + $outerWidth: true, + $pageXOffset: true, + $pageYOffset: true, + $parent: true, + $scrollLeft: true, + $scrollTop: true, + $scrollX: true, + $scrollY: true, + $self: true, + $webkitIndexedDB: true, + $webkitStorageInfo: true, + $window: true + }; + var hasAutomationEqualityBug = (function () { + /* global window */ + if (typeof window === 'undefined') { return false; } + for (var k in window) { + try { + if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { + try { + equalsConstructorPrototype(window[k]); + } catch (e) { + return true; + } + } + } catch (e) { + return true; + } + } + return false; + }()); + var equalsConstructorPrototypeIfNotBuggy = function (o) { + /* global window */ + if (typeof window === 'undefined' || !hasAutomationEqualityBug) { + return equalsConstructorPrototype(o); + } + try { + return equalsConstructorPrototype(o); + } catch (e) { + return false; + } + }; + + keysShim = function keys(object) { + var isObject = object !== null && typeof object === 'object'; + var isFunction = toStr.call(object) === '[object Function]'; + var isArguments = isArgs(object); + var isString = isObject && toStr.call(object) === '[object String]'; + var theKeys = []; + + if (!isObject && !isFunction && !isArguments) { + throw new TypeError('Object.keys called on a non-object'); + } + + var skipProto = hasProtoEnumBug && isFunction; + if (isString && object.length > 0 && !has.call(object, 0)) { + for (var i = 0; i < object.length; ++i) { + theKeys.push(String(i)); + } + } + + if (isArguments && object.length > 0) { + for (var j = 0; j < object.length; ++j) { + theKeys.push(String(j)); + } + } else { + for (var name in object) { + if (!(skipProto && name === 'prototype') && has.call(object, name)) { + theKeys.push(String(name)); + } + } + } + + if (hasDontEnumBug) { + var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); + + for (var k = 0; k < dontEnums.length; ++k) { + if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { + theKeys.push(dontEnums[k]); + } + } + } + return theKeys; + }; +} +module.exports = keysShim; + +},{"./isArguments":40}],39:[function(require,module,exports){ +'use strict'; + +var slice = Array.prototype.slice; +var isArgs = require('./isArguments'); + +var origKeys = Object.keys; +var keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./implementation'); + +var originalKeys = Object.keys; + +keysShim.shim = function shimObjectKeys() { + if (Object.keys) { + var keysWorksWithArguments = (function () { + // Safari 5.0 bug + var args = Object.keys(arguments); + return args && args.length === arguments.length; + }(1, 2)); + if (!keysWorksWithArguments) { + Object.keys = function keys(object) { // eslint-disable-line func-name-matching + if (isArgs(object)) { + return originalKeys(slice.call(object)); + } + return originalKeys(object); + }; + } + } else { + Object.keys = keysShim; + } + return Object.keys || keysShim; +}; + +module.exports = keysShim; + +},{"./implementation":38,"./isArguments":40}],40:[function(require,module,exports){ +'use strict'; + +var toStr = Object.prototype.toString; + +module.exports = function isArguments(value) { + var str = toStr.call(value); + var isArgs = str === '[object Arguments]'; + if (!isArgs) { + isArgs = str !== '[object Array]' && + value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + toStr.call(value.callee) === '[object Function]'; + } + return isArgs; +}; + +},{}],41:[function(require,module,exports){ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var define = require('define-data-property'); +var hasDescriptors = require('has-property-descriptors')(); +var gOPD = require('gopd'); + +var $TypeError = require('es-errors/type'); +var $floor = GetIntrinsic('%Math.floor%'); + +/** @type {import('.')} */ +module.exports = function setFunctionLength(fn, length) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { + throw new $TypeError('`length` must be a positive 32-bit integer'); + } + + var loose = arguments.length > 2 && !!arguments[2]; + + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ('length' in fn && gOPD) { + var desc = gOPD(fn, 'length'); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define(/** @type {Parameters[0]} */ (fn), 'length', length, true, true); + } else { + define(/** @type {Parameters[0]} */ (fn), 'length', length); + } + } + return fn; +}; + +},{"define-data-property":12,"es-errors/type":21,"get-intrinsic":26,"gopd":28,"has-property-descriptors":29}],42:[function(require,module,exports){ +'use strict'; + +var implementation = require('./implementation'); + +var lacksProperEnumerationOrder = function () { + if (!Object.assign) { + return false; + } + /* + * v8, specifically in node 4.x, has a bug with incorrect property enumeration order + * note: this does not detect the bug unless there's 20 characters + */ + var str = 'abcdefghijklmnopqrst'; + var letters = str.split(''); + var map = {}; + for (var i = 0; i < letters.length; ++i) { + map[letters[i]] = letters[i]; + } + var obj = Object.assign({}, map); + var actual = ''; + for (var k in obj) { + actual += k; + } + return str !== actual; +}; + +var assignHasPendingExceptions = function () { + if (!Object.assign || !Object.preventExtensions) { + return false; + } + /* + * Firefox 37 still has "pending exception" logic in its Object.assign implementation, + * which is 72% slower than our shim, and Firefox 40's native implementation. + */ + var thrower = Object.preventExtensions({ 1: 2 }); + try { + Object.assign(thrower, 'xy'); + } catch (e) { + return thrower[1] === 'y'; + } + return false; +}; + +module.exports = function getPolyfill() { + if (!Object.assign) { + return implementation; + } + if (lacksProperEnumerationOrder()) { + return implementation; + } + if (assignHasPendingExceptions()) { + return implementation; + } + return Object.assign; +}; + +},{"./implementation":2}],43:[function(require,module,exports){ +'use strict'; + +var define = require('define-properties'); +var getPolyfill = require('./polyfill'); + +module.exports = function shimAssign() { + var polyfill = getPolyfill(); + define( + Object, + { assign: polyfill }, + { assign: function () { return Object.assign !== polyfill; } } + ); + return polyfill; +}; + +},{"./polyfill":42,"define-properties":13}]},{},[1]); diff --git a/node_modules/object.assign/hasSymbols.js b/node_modules/object.assign/hasSymbols.js new file mode 100644 index 0000000000000000000000000000000000000000..34841e01199eb2cc5e607665b22679da2eeb6a43 --- /dev/null +++ b/node_modules/object.assign/hasSymbols.js @@ -0,0 +1,43 @@ +'use strict'; + +var keys = require('object-keys'); + +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + /* + * temp disabled per https://github.com/ljharb/object.assign/issues/17 + * if (sym instanceof Symbol) { return false; } + * temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + * if (!(symObj instanceof Symbol)) { return false; } + */ + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-unreachable-loop + if (keys(obj).length !== 0) { return false; } + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; diff --git a/node_modules/object.assign/implementation.js b/node_modules/object.assign/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..4f4b4256f57ecb9478548853ad4cb61ec98cbbe8 --- /dev/null +++ b/node_modules/object.assign/implementation.js @@ -0,0 +1,46 @@ +'use strict'; + +// modified from https://github.com/es-shims/es6-shim +var objectKeys = require('object-keys'); +var hasSymbols = require('has-symbols/shams')(); +var callBound = require('call-bound'); +var $Object = require('es-object-atoms'); +var $push = callBound('Array.prototype.push'); +var $propIsEnumerable = callBound('Object.prototype.propertyIsEnumerable'); +var originalGetSymbols = hasSymbols ? $Object.getOwnPropertySymbols : null; + +// eslint-disable-next-line no-unused-vars +module.exports = function assign(target, source1) { + if (target == null) { throw new TypeError('target must be an object'); } + var to = $Object(target); // step 1 + if (arguments.length === 1) { + return to; // step 2 + } + for (var s = 1; s < arguments.length; ++s) { + var from = $Object(arguments[s]); // step 3.a.i + + // step 3.a.ii: + var keys = objectKeys(from); + var getSymbols = hasSymbols && ($Object.getOwnPropertySymbols || originalGetSymbols); + if (getSymbols) { + var syms = getSymbols(from); + for (var j = 0; j < syms.length; ++j) { + var key = syms[j]; + if ($propIsEnumerable(from, key)) { + $push(keys, key); + } + } + } + + // step 3.a.iii: + for (var i = 0; i < keys.length; ++i) { + var nextKey = keys[i]; + if ($propIsEnumerable(from, nextKey)) { // step 3.a.iii.2 + var propValue = from[nextKey]; // step 3.a.iii.2.a + to[nextKey] = propValue; // step 3.a.iii.2.b + } + } + } + + return to; // step 4 +}; diff --git a/node_modules/object.assign/index.js b/node_modules/object.assign/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9b50603769174865159dd05b178f9f18d890d63a --- /dev/null +++ b/node_modules/object.assign/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var defineProperties = require('define-properties'); +var callBind = require('call-bind'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var polyfill = callBind.apply(getPolyfill()); +// eslint-disable-next-line no-unused-vars +var bound = function assign(target, source1) { + return polyfill(Object, arguments); +}; + +defineProperties(bound, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = bound; diff --git a/node_modules/object.assign/package.json b/node_modules/object.assign/package.json new file mode 100644 index 0000000000000000000000000000000000000000..996fee0cd4b5ab41d7c1da5812adacdaadecb8e4 --- /dev/null +++ b/node_modules/object.assign/package.json @@ -0,0 +1,96 @@ +{ + "name": "object.assign", + "version": "4.1.7", + "author": "Jordan Harband", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "description": "ES6 spec-compliant Object.assign shim. From https://github.com/es-shims/es6-shim", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "pretest": "npm run lint && es-shim-api --bound", + "test": "npm run tests-only && npm run test:ses", + "posttest": "npx npm@'>=10.2' audit --production", + "tests-only": "npm run test:implementation && npm run test:shim", + "test:native": "nyc node test/native", + "test:shim": "nyc node test/shimmed", + "test:implementation": "nyc node test", + "test:ses": "node test/ses-compat", + "lint": "eslint .", + "build": "mkdir -p dist && browserify browserShim.js > dist/browser.js", + "prepublishOnly": "safe-publish-latest && npm run build", + "prepublish": "not-in-publish || npm run prepublishOnly" + }, + "repository": { + "type": "git", + "url": "git://github.com/ljharb/object.assign.git" + }, + "keywords": [ + "Object.assign", + "assign", + "ES6", + "extend", + "$.extend", + "jQuery", + "_.extend", + "Underscore", + "es-shim API", + "polyfill", + "shim" + ], + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", + "object-keys": "^1.1.1" + }, + "devDependencies": { + "@es-shims/api": "^2.5.1", + "@ljharb/eslint-config": "^21.1.1", + "browserify": "^16.5.2", + "eslint": "=8.8.0", + "for-each": "^0.3.3", + "functions-have-names": "^1.2.3", + "has-strict-mode": "^1.0.1", + "hasown": "^2.0.2", + "mock-property": "^1.1.0", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "ses": "^1.10.0", + "tape": "^5.9.0" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "bower.json", + "browserShim.js", + "!dist/" + ] + } +} diff --git a/node_modules/object.assign/polyfill.js b/node_modules/object.assign/polyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..ca94aea9ba30d7435bb481b8f8bfb098a9f007c0 --- /dev/null +++ b/node_modules/object.assign/polyfill.js @@ -0,0 +1,55 @@ +'use strict'; + +var implementation = require('./implementation'); + +var lacksProperEnumerationOrder = function () { + if (!Object.assign) { + return false; + } + /* + * v8, specifically in node 4.x, has a bug with incorrect property enumeration order + * note: this does not detect the bug unless there's 20 characters + */ + var str = 'abcdefghijklmnopqrst'; + var letters = str.split(''); + var map = {}; + for (var i = 0; i < letters.length; ++i) { + map[letters[i]] = letters[i]; + } + var obj = Object.assign({}, map); + var actual = ''; + for (var k in obj) { + actual += k; + } + return str !== actual; +}; + +var assignHasPendingExceptions = function () { + if (!Object.assign || !Object.preventExtensions) { + return false; + } + /* + * Firefox 37 still has "pending exception" logic in its Object.assign implementation, + * which is 72% slower than our shim, and Firefox 40's native implementation. + */ + var thrower = Object.preventExtensions({ 1: 2 }); + try { + Object.assign(thrower, 'xy'); + } catch (e) { + return thrower[1] === 'y'; + } + return false; +}; + +module.exports = function getPolyfill() { + if (!Object.assign) { + return implementation; + } + if (lacksProperEnumerationOrder()) { + return implementation; + } + if (assignHasPendingExceptions()) { + return implementation; + } + return Object.assign; +}; diff --git a/node_modules/object.assign/shim.js b/node_modules/object.assign/shim.js new file mode 100644 index 0000000000000000000000000000000000000000..9f896ae3cf90a39f574d789020c40cda3eb4e9bf --- /dev/null +++ b/node_modules/object.assign/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var define = require('define-properties'); +var getPolyfill = require('./polyfill'); + +module.exports = function shimAssign() { + var polyfill = getPolyfill(); + define( + Object, + { assign: polyfill }, + { assign: function () { return Object.assign !== polyfill; } } + ); + return polyfill; +}; diff --git a/node_modules/object.assign/test/implementation.js b/node_modules/object.assign/test/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..05d7d7ada705b5518cf0827899513f46e1e8751e --- /dev/null +++ b/node_modules/object.assign/test/implementation.js @@ -0,0 +1,19 @@ +'use strict'; + +var implementation = require('../implementation'); +var callBind = require('call-bind'); +var test = require('tape'); +var hasStrictMode = require('has-strict-mode')(); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad first arg/receiver', { skip: !hasStrictMode }, function (st) { + st['throws'](function () { implementation(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { implementation(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(callBind(implementation, Object), t); + + t.end(); +}); diff --git a/node_modules/object.assign/test/index.js b/node_modules/object.assign/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..776b2b3342e636b0c172d9192111cf7c37888454 --- /dev/null +++ b/node_modules/object.assign/test/index.js @@ -0,0 +1,17 @@ +'use strict'; + +var assign = require('../'); +var test = require('tape'); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', function (st) { + st['throws'](function () { assign(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { assign(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(assign, t); + + t.end(); +}); diff --git a/node_modules/object.assign/test/native.js b/node_modules/object.assign/test/native.js new file mode 100644 index 0000000000000000000000000000000000000000..49a70f7987691ee4b0f6193b434b83d4c97699b5 --- /dev/null +++ b/node_modules/object.assign/test/native.js @@ -0,0 +1,49 @@ +'use strict'; + +var test = require('tape'); +var defineProperties = require('define-properties'); +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); + +var runTests = require('./tests'); + +test('native', function (t) { + t.equal(Object.assign.length, 2, 'Object.assign has a length of 2'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal(Object.assign.name, 'assign', 'Object.assign has name "assign"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(Object, 'assign'), 'Object.assign is not enumerable'); + et.end(); + }); + + var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); + + t.test('bad object value', { skip: !supportsStrictMode }, function (st) { + st['throws'](function () { return Object.assign(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return Object.assign(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + // v8 in node 0.8 and 0.10 have non-enumerable string properties + var stringCharsAreEnumerable = isEnumerable.call('xy', 0); + t.test('when Object.assign is present and has pending exceptions', { skip: !stringCharsAreEnumerable || !Object.preventExtensions }, function (st) { + /* + * Firefox 37 still has "pending exception" logic in its Object.assign implementation, + * which is 72% slower than our shim, and Firefox 40's native implementation. + */ + var thrower = Object.preventExtensions({ 1: '2' }); + var error; + try { Object.assign(thrower, 'xy'); } catch (e) { error = e; } + st.equal(error instanceof TypeError, true, 'error is TypeError'); + st.equal(thrower[1], '2', 'thrower[1] === "2"'); + + st.end(); + }); + + runTests(Object.assign, t); + + t.end(); +}); diff --git a/node_modules/object.assign/test/ses-compat.js b/node_modules/object.assign/test/ses-compat.js new file mode 100644 index 0000000000000000000000000000000000000000..9669eb9a98e3931ad02a22b6a834e28f7234489e --- /dev/null +++ b/node_modules/object.assign/test/ses-compat.js @@ -0,0 +1,12 @@ +'use strict'; + +/* globals lockdown */ + +// requiring ses exposes "lockdown" on the global +require('ses'); + +// lockdown freezes the primordials +lockdown({ errorTaming: 'unsafe' }); + +// initialize the module +require('./'); diff --git a/node_modules/object.assign/test/shimmed.js b/node_modules/object.assign/test/shimmed.js new file mode 100644 index 0000000000000000000000000000000000000000..ee577587a8961307b30651c9bfe56559eccc5c54 --- /dev/null +++ b/node_modules/object.assign/test/shimmed.js @@ -0,0 +1,52 @@ +'use strict'; + +var assign = require('../'); +assign.shim(); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); + +var runTests = require('./tests'); + +test('shimmed', function (t) { + t.equal(Object.assign.length, 2, 'Object.assign has a length of 2'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal(Object.assign.name, 'assign', 'Object.assign has name "assign"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(Object, 'assign'), 'Object.assign is not enumerable'); + et.end(); + }); + + var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); + + t.test('bad object value', { skip: !supportsStrictMode }, function (st) { + st['throws'](function () { return Object.assign(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return Object.assign(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + // v8 in node 0.8 and 0.10 have non-enumerable string properties + var stringCharsAreEnumerable = isEnumerable.call('xy', 0); + t.test('when Object.assign is present and has pending exceptions', { skip: !stringCharsAreEnumerable || !Object.preventExtensions }, function (st) { + /* + * Firefox 37 still has "pending exception" logic in its Object.assign implementation, + * which is 72% slower than our shim, and Firefox 40's native implementation. + */ + var thrower = Object.preventExtensions({ 1: '2' }); + var error; + try { Object.assign(thrower, 'xy'); } catch (e) { error = e; } + st.equal(error instanceof TypeError, true, 'error is TypeError'); + st.equal(thrower[1], '2', 'thrower[1] === "2"'); + + st.end(); + }); + + runTests(Object.assign, t); + + t.end(); +}); diff --git a/node_modules/object.assign/test/tests.js b/node_modules/object.assign/test/tests.js new file mode 100644 index 0000000000000000000000000000000000000000..eff2793d3000ccfd92f3a8f18ec0f85518369f90 --- /dev/null +++ b/node_modules/object.assign/test/tests.js @@ -0,0 +1,232 @@ +'use strict'; + +var hasSymbols = require('has-symbols/shams')(); +var forEach = require('for-each'); +var hasOwn = require('hasown'); +var mockProperty = require('mock-property'); + +module.exports = function (assign, t) { + t.test('error cases', function (st) { + st['throws'](function () { assign(null); }, TypeError, 'target must be an object'); + st['throws'](function () { assign(undefined); }, TypeError, 'target must be an object'); + st['throws'](function () { assign(null, {}); }, TypeError, 'target must be an object'); + st['throws'](function () { assign(undefined, {}); }, TypeError, 'target must be an object'); + st.end(); + }); + + t.test('non-object target, no sources', function (st) { + var bool = assign(true); + st.equal(typeof bool, 'object', 'bool is object'); + st.equal(Boolean.prototype.valueOf.call(bool), true, 'bool coerces to `true`'); + + var number = assign(1); + st.equal(typeof number, 'object', 'number is object'); + st.equal(Number.prototype.valueOf.call(number), 1, 'number coerces to `1`'); + + var string = assign('1'); + st.equal(typeof string, 'object', 'number is object'); + st.equal(String.prototype.valueOf.call(string), '1', 'number coerces to `"1"`'); + + st.end(); + }); + + t.test('non-object target, with sources', function (st) { + var signal = {}; + + st.test('boolean', function (st2) { + var bool = assign(true, { a: signal }); + st2.equal(typeof bool, 'object', 'bool is object'); + st2.equal(Boolean.prototype.valueOf.call(bool), true, 'bool coerces to `true`'); + st2.equal(bool.a, signal, 'source properties copied'); + st2.end(); + }); + + st.test('number', function (st2) { + var number = assign(1, { a: signal }); + st2.equal(typeof number, 'object', 'number is object'); + st2.equal(Number.prototype.valueOf.call(number), 1, 'number coerces to `1`'); + st2.equal(number.a, signal, 'source properties copied'); + st2.end(); + }); + + st.test('string', function (st2) { + var string = assign('1', { a: signal }); + st2.equal(typeof string, 'object', 'number is object'); + st2.equal(String.prototype.valueOf.call(string), '1', 'number coerces to `"1"`'); + st2.equal(string.a, signal, 'source properties copied'); + st2.end(); + }); + + st.end(); + }); + + t.test('non-object sources', function (st) { + st.deepEqual(assign({ a: 1 }, null, { b: 2 }), { a: 1, b: 2 }, 'ignores null source'); + st.deepEqual(assign({ a: 1 }, { b: 2 }, undefined), { a: 1, b: 2 }, 'ignores undefined source'); + st.end(); + }); + + t.test('returns the modified target object', function (st) { + var target = {}; + var returned = assign(target, { a: 1 }); + st.equal(returned, target, 'returned object is the same reference as the target object'); + st.end(); + }); + + t.test('has the right length', function (st) { + st.equal(assign.length, 2, 'length is 2 => 2 required arguments'); + st.end(); + }); + + t.test('merge two objects', function (st) { + var target = { a: 1 }; + var returned = assign(target, { b: 2 }); + st.deepEqual(returned, { a: 1, b: 2 }, 'returned object has properties from both'); + st.end(); + }); + + t.test('works with functions', function (st) { + var target = function () {}; + target.a = 1; + var returned = assign(target, { b: 2 }); + st.equal(target, returned, 'returned object is target'); + st.equal(returned.a, 1); + st.equal(returned.b, 2); + st.end(); + }); + + t.test('works with primitives', function (st) { + var target = 2; + var source = { b: 42 }; + var returned = assign(target, source); + st.equal(Object.prototype.toString.call(returned), '[object Number]', 'returned is object form of number primitive'); + st.equal(Number(returned), target, 'returned and target have same valueOf'); + st.equal(returned.b, source.b); + st.end(); + }); + + /* globals window */ + t.test('works with window.location', { skip: typeof window === 'undefined' }, function (st) { + var target = {}; + assign(target, window.location); + for (var prop in window.location) { + if (hasOwn(window.location, prop)) { + st.deepEqual(target[prop], window.location[prop], prop + ' is copied'); + } + } + st.end(); + }); + + t.test('merge N objects', function (st) { + var target = { a: 1 }; + var source1 = { b: 2 }; + var source2 = { c: 3 }; + var returned = assign(target, source1, source2); + st.deepEqual(returned, { a: 1, b: 2, c: 3 }, 'returned object has properties from all sources'); + st.end(); + }); + + t.test('only iterates over own keys', function (st) { + var Foo = function () {}; + Foo.prototype.bar = true; + var foo = new Foo(); + foo.baz = true; + var target = { a: 1 }; + var returned = assign(target, foo); + st.equal(returned, target, 'returned object is the same reference as the target object'); + st.deepEqual(target, { a: 1, baz: true }, 'returned object has only own properties from both'); + st.end(); + }); + + t.test('includes enumerable symbols, after keys', { skip: !hasSymbols }, function (st) { + var visited = []; + var obj = {}; + Object.defineProperty(obj, 'a', { enumerable: true, get: function () { visited.push('a'); return 42; } }); + var symbol = Symbol('enumerable'); + Object.defineProperty(obj, symbol, { + enumerable: true, + get: function () { visited.push(symbol); return Infinity; } + }); + var nonEnumSymbol = Symbol('non-enumerable'); + Object.defineProperty(obj, nonEnumSymbol, { + enumerable: false, + get: function () { visited.push(nonEnumSymbol); return -Infinity; } + }); + var target = assign({}, obj); + st.deepEqual(visited, ['a', symbol], 'key is visited first, then symbol'); + st.equal(target.a, 42, 'target.a is 42'); + st.equal(target[symbol], Infinity, 'target[symbol] is Infinity'); + st.notEqual(target[nonEnumSymbol], -Infinity, 'target[nonEnumSymbol] is not -Infinity'); + st.end(); + }); + + t.test('does not fail when symbols are not present', { skip: !Object.isFrozen || Object.isFrozen(Object) }, function (st) { + st.teardown(mockProperty(Object, 'getOwnPropertySymbols', { 'delete': true })); + + var visited = []; + var obj = {}; + Object.defineProperty(obj, 'a', { enumerable: true, get: function () { visited.push('a'); return 42; } }); + var keys = ['a']; + if (hasSymbols) { + var symbol = Symbol('sym'); + Object.defineProperty(obj, symbol, { + enumerable: true, + get: function () { visited.push(symbol); return Infinity; } + }); + keys.push(symbol); + } + var target = assign({}, obj); + st.deepEqual(visited, keys, 'assign visits expected keys'); + st.equal(target.a, 42, 'target.a is 42'); + + if (hasSymbols) { + st.equal(target[symbol], Infinity); + } + st.end(); + }); + + t.test('preserves correct property enumeration order', function (st) { + var str = 'abcdefghijklmnopqrst'; + var letters = {}; + forEach(str.split(''), function (letter) { + letters[letter] = letter; + }); + + var n = 5; + st.comment('run the next test ' + n + ' times'); + var object = assign({}, letters); + var actual = ''; + for (var k in object) { + actual += k; + } + for (var i = 0; i < n; ++i) { + st.equal(actual, str, 'property enumeration order should be followed'); + } + st.end(); + }); + + t.test('checks enumerability and existence, in case of modification during [[Get]]', { skip: !Object.defineProperty }, function (st) { + var targetBvalue = {}; + var targetCvalue = {}; + var target = { b: targetBvalue, c: targetCvalue }; + var source = {}; + Object.defineProperty(source, 'a', { + enumerable: true, + get: function () { + delete this.b; + Object.defineProperty(this, 'c', { enumerable: false }); + return 'a'; + } + }); + var sourceBvalue = {}; + var sourceCvalue = {}; + source.b = sourceBvalue; + source.c = sourceCvalue; + var result = assign(target, source); + st.equal(result, target, 'sanity check: result is === target'); + st.equal(result.b, targetBvalue, 'target key not overwritten by deleted source key'); + st.equal(result.c, targetCvalue, 'target key not overwritten by non-enumerable source key'); + + st.end(); + }); +}; diff --git a/node_modules/on-finished/HISTORY.md b/node_modules/on-finished/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..1917595a714e11049ec9402d87aa625c68caa080 --- /dev/null +++ b/node_modules/on-finished/HISTORY.md @@ -0,0 +1,98 @@ +2.4.1 / 2022-02-22 +================== + + * Fix error on early async hooks implementations + +2.4.0 / 2022-02-21 +================== + + * Prevent loss of async hooks context + +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +2.2.1 / 2015-04-22 +================== + + * Fix `isFinished(req)` when data buffered + +2.2.0 / 2014-12-22 +================== + + * Add message object to callback arguments + +2.1.1 / 2014-10-22 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/node_modules/on-finished/LICENSE b/node_modules/on-finished/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5931fd23eab9dd3be559cd4bd81253df87a5297c --- /dev/null +++ b/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/on-finished/README.md b/node_modules/on-finished/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8973cded6589a6cc5a9e1718e3fb0d709fe6e8d8 --- /dev/null +++ b/node_modules/on-finished/README.md @@ -0,0 +1,162 @@ +# on-finished + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to an error, the first argument will contain the error. If the response +has already finished, the listener will be invoked. + +Listening to the end of a response would be used to close things associated +with the response, like open files. + +Listener is invoked as `listener(err, res)`. + + + +```js +onFinished(res, function (err, res) { + // clean up open fds, etc. + // err contains the error if request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to an error, the first argument will contain the error. If the request +has already finished, the listener will be invoked. + +Listening to the end of a request would be used to know when to continue +after reading the data. + +Listener is invoked as `listener(err, req)`. + + + +```js +var data = '' + +req.setEncoding('utf8') +req.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var fs = require('fs') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest (req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function () { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/on-finished/master?label=ci +[ci-url]: https://github.com/jshttp/on-finished/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/on-finished/master +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[node-image]: https://badgen.net/npm/node/on-finished +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/on-finished +[npm-url]: https://npmjs.org/package/on-finished +[npm-version-image]: https://badgen.net/npm/v/on-finished diff --git a/node_modules/on-finished/index.js b/node_modules/on-finished/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e68df7bde39bb47aa1fd7eff4b317b3969de75bd --- /dev/null +++ b/node_modules/on-finished/index.js @@ -0,0 +1,234 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var asyncHooks = tryRequireAsyncHooks() +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished (msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, wrap(listener)) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished (msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener (msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish (error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket (socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // istanbul ignore next: node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener (msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener (msg) { + function listener (err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +// istanbul ignore next: node.js 0.8 patch +function patchAssignSocket (res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket (socket) { + assignSocket.call(this, socket) + callback(socket) + } +} + +/** + * Try to require async_hooks + * @private + */ + +function tryRequireAsyncHooks () { + try { + return require('async_hooks') + } catch (e) { + return {} + } +} + +/** + * Wrap function with async resource, if possible. + * AsyncResource.bind static method backported. + * @private + */ + +function wrap (fn) { + var res + + // create anonymous resource + if (asyncHooks.AsyncResource) { + res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn') + } + + // incompatible node.js + if (!res || !res.runInAsyncScope) { + return fn + } + + // return bound function + return res.runInAsyncScope.bind(res, fn, null) +} diff --git a/node_modules/on-finished/package.json b/node_modules/on-finished/package.json new file mode 100644 index 0000000000000000000000000000000000000000..644cd814b9d745714e4d16753de8bc8856e201e4 --- /dev/null +++ b/node_modules/on-finished/package.json @@ -0,0 +1,39 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.4.1", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/on-finished", + "dependencies": { + "ee-first": "1.1.1" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/once/LICENSE b/node_modules/once/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..19129e315fe593965a2fdd50ec0d1253bcbd2ece --- /dev/null +++ b/node_modules/once/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/once/README.md b/node_modules/once/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1f1ffca9330e3ceddd54106e1ba63322fc9751f8 --- /dev/null +++ b/node_modules/once/README.md @@ -0,0 +1,79 @@ +# once + +Only call a function once. + +## usage + +```javascript +var once = require('once') + +function load (file, cb) { + cb = once(cb) + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Or add to the Function.prototype in a responsible way: + +```javascript +// only has to be done once +require('once').proto() + +function load (file, cb) { + cb = cb.once() + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Ironically, the prototype feature makes this module twice as +complicated as necessary. + +To check whether you function has been called, use `fn.called`. Once the +function is called for the first time the return value of the original +function is saved in `fn.value` and subsequent calls will continue to +return this value. + +```javascript +var once = require('once') + +function load (cb) { + cb = once(cb) + var stream = createStream() + stream.once('data', cb) + stream.once('end', function () { + if (!cb.called) cb(new Error('not found')) + }) +} +``` + +## `once.strict(func)` + +Throw an error if the function is called twice. + +Some functions are expected to be called only once. Using `once` for them would +potentially hide logical errors. + +In the example below, the `greet` function has to call the callback only once: + +```javascript +function greet (name, cb) { + // return is missing from the if statement + // when no name is passed, the callback is called twice + if (!name) cb('Hello anonymous') + cb('Hello ' + name) +} + +function log (msg) { + console.log(msg) +} + +// this will print 'Hello anonymous' but the logical error will be missed +greet(null, once(msg)) + +// once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time +greet(null, once.strict(msg)) +``` diff --git a/node_modules/once/once.js b/node_modules/once/once.js new file mode 100644 index 0000000000000000000000000000000000000000..235406736d9d9485bbc0dd0820dd661110da7a4d --- /dev/null +++ b/node_modules/once/once.js @@ -0,0 +1,42 @@ +var wrappy = require('wrappy') +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} diff --git a/node_modules/once/package.json b/node_modules/once/package.json new file mode 100644 index 0000000000000000000000000000000000000000..16815b2fa111936c9681a1b76c5fce98421c1631 --- /dev/null +++ b/node_modules/once/package.json @@ -0,0 +1,33 @@ +{ + "name": "once", + "version": "1.4.0", + "description": "Run a function exactly one time", + "main": "once.js", + "directories": { + "test": "test" + }, + "dependencies": { + "wrappy": "1" + }, + "devDependencies": { + "tap": "^7.0.1" + }, + "scripts": { + "test": "tap test/*.js" + }, + "files": [ + "once.js" + ], + "repository": { + "type": "git", + "url": "git://github.com/isaacs/once" + }, + "keywords": [ + "once", + "function", + "one", + "single" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC" +} diff --git a/node_modules/os-browserify/.npmignore b/node_modules/os-browserify/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..f356293eeef146cd2b1943dada766512fdc78e64 --- /dev/null +++ b/node_modules/os-browserify/.npmignore @@ -0,0 +1,14 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log diff --git a/node_modules/os-browserify/LICENSE b/node_modules/os-browserify/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4b870dac2d1035909e637a2606c9d2bc8ae21e0b --- /dev/null +++ b/node_modules/os-browserify/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 CoderPuppy + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/os-browserify/README.md b/node_modules/os-browserify/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4dd7d6ebccaab37b43812915130e7eede683a18e --- /dev/null +++ b/node_modules/os-browserify/README.md @@ -0,0 +1,5 @@ +# os-browserify + +The [os](https://nodejs.org/api/os.html) module from node.js, but for browsers. + +When you `require('os')` in [browserify](http://github.com/substack/node-browserify), this module will be loaded. diff --git a/node_modules/os-browserify/browser.js b/node_modules/os-browserify/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..22d9a2ad4516d22f3d47b40d15bb977f321f082d --- /dev/null +++ b/node_modules/os-browserify/browser.js @@ -0,0 +1,49 @@ +exports.endianness = function () { return 'LE' }; + +exports.hostname = function () { + if (typeof location !== 'undefined') { + return location.hostname + } + else return ''; +}; + +exports.loadavg = function () { return [] }; + +exports.uptime = function () { return 0 }; + +exports.freemem = function () { + return Number.MAX_VALUE; +}; + +exports.totalmem = function () { + return Number.MAX_VALUE; +}; + +exports.cpus = function () { return [] }; + +exports.type = function () { return 'Browser' }; + +exports.release = function () { + if (typeof navigator !== 'undefined') { + return navigator.appVersion; + } + return ''; +}; + +exports.networkInterfaces += exports.getNetworkInterfaces += function () { return {} }; + +exports.arch = function () { return 'javascript' }; + +exports.platform = function () { return 'browser' }; + +exports.tmpdir = exports.tmpDir = function () { + return '/tmp'; +}; + +exports.EOL = '\n'; + +exports.homedir = function () { + return '/' +}; diff --git a/node_modules/os-browserify/main.js b/node_modules/os-browserify/main.js new file mode 100644 index 0000000000000000000000000000000000000000..5910697d87f515eb921459fe3da8c53aa478b1c5 --- /dev/null +++ b/node_modules/os-browserify/main.js @@ -0,0 +1 @@ +module.exports = require('os'); diff --git a/node_modules/os-browserify/package.json b/node_modules/os-browserify/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1ef42b490515a93fe8b2cd438e9f5aec8d1caaff --- /dev/null +++ b/node_modules/os-browserify/package.json @@ -0,0 +1,20 @@ +{ + "name": "os-browserify", + "version": "0.3.0", + "author": "CoderPuppy ", + "license": "MIT", + "main": "main.js", + "browser": "browser.js", + "jspm": { + "map": { + "./main.js": { + "node": "@node/os", + "browser": "./browser.js" + } + } + }, + "repository": { + "type": "git", + "url": "http://github.com/CoderPuppy/os-browserify.git" + } +} diff --git a/node_modules/p-limit/index.d.ts b/node_modules/p-limit/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f348d7f13a8b00c5559112bb177b4f527468c63b --- /dev/null +++ b/node_modules/p-limit/index.d.ts @@ -0,0 +1,42 @@ +declare namespace pLimit { + interface Limit { + /** + The number of promises that are currently running. + */ + readonly activeCount: number; + + /** + The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + */ + readonly pendingCount: number; + + /** + Discard pending promises that are waiting to run. + + This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + + Note: This does not cancel promises that are already running. + */ + clearQueue: () => void; + + /** + @param fn - Promise-returning/async function. + @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions. + @returns The promise returned by calling `fn(...arguments)`. + */ + ( + fn: (...arguments: Arguments) => PromiseLike | ReturnType, + ...arguments: Arguments + ): Promise; + } +} + +/** +Run multiple promise-returning & async functions with limited concurrency. + +@param concurrency - Concurrency limit. Minimum: `1`. +@returns A `limit` function. +*/ +declare function pLimit(concurrency: number): pLimit.Limit; + +export = pLimit; diff --git a/node_modules/p-limit/index.js b/node_modules/p-limit/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c2ae52d90db4776496b2cae20e636aea0d2dfceb --- /dev/null +++ b/node_modules/p-limit/index.js @@ -0,0 +1,71 @@ +'use strict'; +const Queue = require('yocto-queue'); + +const pLimit = concurrency => { + if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { + throw new TypeError('Expected `concurrency` to be a number from 1 and up'); + } + + const queue = new Queue(); + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.size > 0) { + queue.dequeue()(); + } + }; + + const run = async (fn, resolve, ...args) => { + activeCount++; + + const result = (async () => fn(...args))(); + + resolve(result); + + try { + await result; + } catch {} + + next(); + }; + + const enqueue = (fn, resolve, ...args) => { + queue.enqueue(run.bind(null, fn, resolve, ...args)); + + (async () => { + // This function needs to wait until the next microtask before comparing + // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously + // when the run function is dequeued and called. The comparison in the if-statement + // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. + await Promise.resolve(); + + if (activeCount < concurrency && queue.size > 0) { + queue.dequeue()(); + } + })(); + }; + + const generator = (fn, ...args) => new Promise(resolve => { + enqueue(fn, resolve, ...args); + }); + + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount + }, + pendingCount: { + get: () => queue.size + }, + clearQueue: { + value: () => { + queue.clear(); + } + } + }); + + return generator; +}; + +module.exports = pLimit; diff --git a/node_modules/p-limit/license b/node_modules/p-limit/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/p-limit/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/p-limit/package.json b/node_modules/p-limit/package.json new file mode 100644 index 0000000000000000000000000000000000000000..76514736fc9c490a3a377fc26a68ef956ab10f21 --- /dev/null +++ b/node_modules/p-limit/package.json @@ -0,0 +1,52 @@ +{ + "name": "p-limit", + "version": "3.1.0", + "description": "Run multiple promise-returning & async functions with limited concurrency", + "license": "MIT", + "repository": "sindresorhus/p-limit", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "limit", + "limited", + "concurrency", + "throttle", + "throat", + "rate", + "batch", + "ratelimit", + "task", + "queue", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "devDependencies": { + "ava": "^2.4.0", + "delay": "^4.4.0", + "in-range": "^2.0.0", + "random-int": "^2.0.1", + "time-span": "^4.0.0", + "tsd": "^0.13.1", + "xo": "^0.35.0" + } +} diff --git a/node_modules/p-limit/readme.md b/node_modules/p-limit/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..b283c1e635aab38570d6ef544dea70e2af741c7a --- /dev/null +++ b/node_modules/p-limit/readme.md @@ -0,0 +1,101 @@ +# p-limit + +> Run multiple promise-returning & async functions with limited concurrency + +## Install + +``` +$ npm install p-limit +``` + +## Usage + +```js +const pLimit = require('p-limit'); + +const limit = pLimit(1); + +const input = [ + limit(() => fetchSomething('foo')), + limit(() => fetchSomething('bar')), + limit(() => doSomething()) +]; + +(async () => { + // Only one promise is run at once + const result = await Promise.all(input); + console.log(result); +})(); +``` + +## API + +### pLimit(concurrency) + +Returns a `limit` function. + +#### concurrency + +Type: `number`\ +Minimum: `1`\ +Default: `Infinity` + +Concurrency limit. + +### limit(fn, ...args) + +Returns the promise returned by calling `fn(...args)`. + +#### fn + +Type: `Function` + +Promise-returning/async function. + +#### args + +Any arguments to pass through to `fn`. + +Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. + +### limit.activeCount + +The number of promises that are currently running. + +### limit.pendingCount + +The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + +### limit.clearQueue() + +Discard pending promises that are waiting to run. + +This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + +Note: This does not cancel promises that are already running. + +## FAQ + +### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package? + +This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue. + +## Related + +- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control +- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions +- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions +- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/p-locate/index.d.ts b/node_modules/p-locate/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..38c7e578f7665c2dc97c845454937e7eab8d8198 --- /dev/null +++ b/node_modules/p-locate/index.d.ts @@ -0,0 +1,53 @@ +declare namespace pLocate { + interface Options { + /** + Number of concurrently pending promises returned by `tester`. Minimum: `1`. + + @default Infinity + */ + readonly concurrency?: number; + + /** + Preserve `input` order when searching. + + Disable this to improve performance if you don't care about the order. + + @default true + */ + readonly preserveOrder?: boolean; + } +} + +/** +Get the first fulfilled promise that satisfies the provided testing function. + +@param input - An iterable of promises/values to test. +@param tester - This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. +@returns A `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. + +@example +``` +import pathExists = require('path-exists'); +import pLocate = require('p-locate'); + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +(async () => { + const foundPath = await pLocate(files, file => pathExists(file)); + + console.log(foundPath); + //=> 'rainbow' +})(); +``` +*/ +declare function pLocate( + input: Iterable | ValueType>, + tester: (element: ValueType) => PromiseLike | boolean, + options?: pLocate.Options +): Promise; + +export = pLocate; diff --git a/node_modules/p-locate/index.js b/node_modules/p-locate/index.js new file mode 100644 index 0000000000000000000000000000000000000000..641c3dd1e819d27f9efe65a9437b8980ca07e8c9 --- /dev/null +++ b/node_modules/p-locate/index.js @@ -0,0 +1,50 @@ +'use strict'; +const pLimit = require('p-limit'); + +class EndError extends Error { + constructor(value) { + super(); + this.value = value; + } +} + +// The input can also be a promise, so we await it +const testElement = async (element, tester) => tester(await element); + +// The input can also be a promise, so we `Promise.all()` them both +const finder = async element => { + const values = await Promise.all(element); + if (values[1] === true) { + throw new EndError(values[0]); + } + + return false; +}; + +const pLocate = async (iterable, tester, options) => { + options = { + concurrency: Infinity, + preserveOrder: true, + ...options + }; + + const limit = pLimit(options.concurrency); + + // Start all the promises concurrently with optional limit + const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); + + // Check the promises either serially or concurrently + const checkLimit = pLimit(options.preserveOrder ? 1 : Infinity); + + try { + await Promise.all(items.map(element => checkLimit(finder, element))); + } catch (error) { + if (error instanceof EndError) { + return error.value; + } + + throw error; + } +}; + +module.exports = pLocate; diff --git a/node_modules/p-locate/license b/node_modules/p-locate/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/p-locate/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/p-locate/package.json b/node_modules/p-locate/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2d5e447f55a7bdc7216e30ae3dcf0a6529c8ae14 --- /dev/null +++ b/node_modules/p-locate/package.json @@ -0,0 +1,54 @@ +{ + "name": "p-locate", + "version": "5.0.0", + "description": "Get the first fulfilled promise that satisfies the provided testing function", + "license": "MIT", + "repository": "sindresorhus/p-locate", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "locate", + "find", + "finder", + "search", + "searcher", + "test", + "array", + "collection", + "iterable", + "iterator", + "race", + "fulfilled", + "fastest", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "p-limit": "^3.0.2" + }, + "devDependencies": { + "ava": "^2.4.0", + "delay": "^4.1.0", + "in-range": "^2.0.0", + "time-span": "^4.0.0", + "tsd": "^0.13.1", + "xo": "^0.32.1" + } +} diff --git a/node_modules/p-locate/readme.md b/node_modules/p-locate/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..be85ec1d4483c8eb8463541623922669be3dee5b --- /dev/null +++ b/node_modules/p-locate/readme.md @@ -0,0 +1,93 @@ +# p-locate [![Build Status](https://travis-ci.com/sindresorhus/p-locate.svg?branch=master)](https://travis-ci.com/github/sindresorhus/p-locate) + +> Get the first fulfilled promise that satisfies the provided testing function + +Think of it like an async version of [`Array#find`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find). + +## Install + +``` +$ npm install p-locate +``` + +## Usage + +Here we find the first file that exists on disk, in array order. + +```js +const pathExists = require('path-exists'); +const pLocate = require('p-locate'); + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +(async () => { + const foundPath = await pLocate(files, file => pathExists(file)); + + console.log(foundPath); + //=> 'rainbow' +})(); +``` + +*The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.* + +## API + +### pLocate(input, tester, options?) + +Returns a `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. + +#### input + +Type: `Iterable` + +An iterable of promises/values to test. + +#### tester(element) + +Type: `Function` + +This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. + +#### options + +Type: `object` + +##### concurrency + +Type: `number`\ +Default: `Infinity`\ +Minimum: `1` + +Number of concurrently pending promises returned by `tester`. + +##### preserveOrder + +Type: `boolean`\ +Default: `true` + +Preserve `input` order when searching. + +Disable this to improve performance if you don't care about the order. + +## Related + +- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently +- [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently +- [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/pako/CHANGELOG.md b/node_modules/pako/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..a861326bd40507d5c8a9bd1e42ea284a9ae97a6c --- /dev/null +++ b/node_modules/pako/CHANGELOG.md @@ -0,0 +1,164 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + + +## [1.0.11] - 2020-01-29 +### Fixed +- Fix tests in node.js v12+, #179. + + +## [1.0.10] - 2019-02-28 +### Fixed +- Fix minified version, #161. + + +## [1.0.9] - 2019-02-28 +### Fixed +- Fix `new Buffer()` warning, #154. + + +## [1.0.8] - 2019-01-14 +### Fixed +- Fix raw inflate with dictionary, #155. + + +## [1.0.7] - 2018-11-29 +### Fixed +- Fixed RangeError in Crome 72, #150. + + +## [1.0.6] - 2017-09-14 +### Changed +- Improve @std/esm compatibility. + + +## [1.0.5] - 2017-03-17 +### Changed +- Maintenance. More formal `zlib` attribution and related + changes, #93. Thanks to @bastien-roucaries for the help. + + +## [1.0.4] - 2016-12-15 +### Changed +- Bump dev dependencies. + +### Fixed +- Make sure `err.message` is filled on throw. + +### Added +- Code examples for utf-16 string encoding & object compression. + + +## [1.0.3] - 2016-07-25 +### Fixed +- Maintenance: re-release to properly display latest version in npm registry + and badges. Because `npm publish` timestamp used instead of versions. + + +## [1.0.2] - 2016-07-21 +### Fixed +- Fixed nasty bug in deflate (wrong `d_buf` offset), which could cause + broken data in some rare cases. +- Also released as 0.2.9 to give chance to old dependents, not updated to 1.x + version. + + +## [1.0.1] - 2016-04-01 +### Added +- Added dictionary support. Thanks to @dignifiedquire. + + +## [1.0.0] - 2016-02-17 +### Changed +- Maintenance release (semver, coding style). + + +## [0.2.8] - 2015-09-14 +### Fixed +- Fixed regression after 0.2.4 for edge conditions in inflate wrapper (#65). + Added more tests to cover possible cases. + + +## [0.2.7] - 2015-06-09 +### Added +- Added Z_SYNC_FLUSH support. Thanks to @TinoLange. + + +## [0.2.6] - 2015-03-24 +### Added +- Allow ArrayBuffer input. + + +## [0.2.5] - 2014-07-19 +### Fixed +- Workaround for Chrome 38.0.2096.0 script parser bug, #30. + + +## [0.2.4] - 2014-07-07 +### Fixed +- Fixed bug in inflate wrapper, #29 + + +## [0.2.3] - 2014-06-09 +### Changed +- Maintenance release, dependencies update. + + +## [0.2.2] - 2014-06-04 +### Fixed +- Fixed iOS 5.1 Safari issue with `apply(typed_array)`, #26. + + +## [0.2.1] - 2014-05-01 +### Fixed +- Fixed collision on switch dynamic/fixed tables. + + +## [0.2.0] - 2014-04-18 +### Added +- Added custom gzip headers support. +- Added strings support. +- More coverage tests. + +### Fixed +- Improved memory allocations for small chunks. +- ZStream properties rename/cleanup. + + +## [0.1.1] - 2014-03-20 +### Fixed +- Bugfixes for inflate/deflate. + + +## [0.1.0] - 2014-03-15 +### Added +- First release. + + +[1.0.10]: https://github.com/nodeca/pako/compare/1.0.10...1.0.11 +[1.0.10]: https://github.com/nodeca/pako/compare/1.0.9...1.0.10 +[1.0.9]: https://github.com/nodeca/pako/compare/1.0.8...1.0.9 +[1.0.8]: https://github.com/nodeca/pako/compare/1.0.7...1.0.8 +[1.0.7]: https://github.com/nodeca/pako/compare/1.0.6...1.0.7 +[1.0.6]: https://github.com/nodeca/pako/compare/1.0.5...1.0.6 +[1.0.5]: https://github.com/nodeca/pako/compare/1.0.4...1.0.5 +[1.0.4]: https://github.com/nodeca/pako/compare/1.0.3...1.0.4 +[1.0.3]: https://github.com/nodeca/pako/compare/1.0.2...1.0.3 +[1.0.2]: https://github.com/nodeca/pako/compare/1.0.1...1.0.2 +[1.0.1]: https://github.com/nodeca/pako/compare/1.0.0...1.0.1 +[1.0.0]: https://github.com/nodeca/pako/compare/0.2.8...1.0.0 +[0.2.8]: https://github.com/nodeca/pako/compare/0.2.7...0.2.8 +[0.2.7]: https://github.com/nodeca/pako/compare/0.2.6...0.2.7 +[0.2.6]: https://github.com/nodeca/pako/compare/0.2.5...0.2.6 +[0.2.5]: https://github.com/nodeca/pako/compare/0.2.4...0.2.5 +[0.2.4]: https://github.com/nodeca/pako/compare/0.2.3...0.2.4 +[0.2.3]: https://github.com/nodeca/pako/compare/0.2.2...0.2.3 +[0.2.2]: https://github.com/nodeca/pako/compare/0.2.1...0.2.2 +[0.2.1]: https://github.com/nodeca/pako/compare/0.2.0...0.2.1 +[0.2.0]: https://github.com/nodeca/pako/compare/0.1.1...0.2.0 +[0.1.1]: https://github.com/nodeca/pako/compare/0.1.0...0.1.1 +[0.1.0]: https://github.com/nodeca/pako/releases/tag/0.1.0 diff --git a/node_modules/pako/LICENSE b/node_modules/pako/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a934ef8db478453e38b2f29af67610916fa9fc99 --- /dev/null +++ b/node_modules/pako/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (C) 2014-2017 by Vitaly Puzrin and Andrei Tuputcyn + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/pako/README.md b/node_modules/pako/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e952992cf52a071854252cbe44e51fe83ee89ddc --- /dev/null +++ b/node_modules/pako/README.md @@ -0,0 +1,191 @@ +pako +========================================== + +[![Build Status](https://travis-ci.org/nodeca/pako.svg?branch=master)](https://travis-ci.org/nodeca/pako) +[![NPM version](https://img.shields.io/npm/v/pako.svg)](https://www.npmjs.org/package/pako) + +> zlib port to javascript, very fast! + +__Why pako is cool:__ + +- Almost as fast in modern JS engines as C implementation (see benchmarks). +- Works in browsers, you can browserify any separate component. +- Chunking support for big blobs. +- Results are binary equal to well known [zlib](http://www.zlib.net/) (now contains ported zlib v1.2.8). + +This project was done to understand how fast JS can be and is it necessary to +develop native C modules for CPU-intensive tasks. Enjoy the result! + + +__Famous projects, using pako:__ + +- [browserify](http://browserify.org/) (via [browserify-zlib](https://github.com/devongovett/browserify-zlib)) +- [JSZip](http://stuk.github.io/jszip/) +- [mincer](https://github.com/nodeca/mincer) +- [JS-Git](https://github.com/creationix/js-git) and + [Tedit](https://chrome.google.com/webstore/detail/tedit-development-environ/ooekdijbnbbjdfjocaiflnjgoohnblgf) + by [@creationix](https://github.com/creationix) + + +__Benchmarks:__ + +``` +node v0.10.26, 1mb sample: + + deflate-dankogai x 4.73 ops/sec ±0.82% (15 runs sampled) + deflate-gildas x 4.58 ops/sec ±2.33% (15 runs sampled) + deflate-imaya x 3.22 ops/sec ±3.95% (12 runs sampled) + ! deflate-pako x 6.99 ops/sec ±0.51% (21 runs sampled) + deflate-pako-string x 5.89 ops/sec ±0.77% (18 runs sampled) + deflate-pako-untyped x 4.39 ops/sec ±1.58% (14 runs sampled) + * deflate-zlib x 14.71 ops/sec ±4.23% (59 runs sampled) + inflate-dankogai x 32.16 ops/sec ±0.13% (56 runs sampled) + inflate-imaya x 30.35 ops/sec ±0.92% (53 runs sampled) + ! inflate-pako x 69.89 ops/sec ±1.46% (71 runs sampled) + inflate-pako-string x 19.22 ops/sec ±1.86% (49 runs sampled) + inflate-pako-untyped x 17.19 ops/sec ±0.85% (32 runs sampled) + * inflate-zlib x 70.03 ops/sec ±1.64% (81 runs sampled) + +node v0.11.12, 1mb sample: + + deflate-dankogai x 5.60 ops/sec ±0.49% (17 runs sampled) + deflate-gildas x 5.06 ops/sec ±6.00% (16 runs sampled) + deflate-imaya x 3.52 ops/sec ±3.71% (13 runs sampled) + ! deflate-pako x 11.52 ops/sec ±0.22% (32 runs sampled) + deflate-pako-string x 9.53 ops/sec ±1.12% (27 runs sampled) + deflate-pako-untyped x 5.44 ops/sec ±0.72% (17 runs sampled) + * deflate-zlib x 14.05 ops/sec ±3.34% (63 runs sampled) + inflate-dankogai x 42.19 ops/sec ±0.09% (56 runs sampled) + inflate-imaya x 79.68 ops/sec ±1.07% (68 runs sampled) + ! inflate-pako x 97.52 ops/sec ±0.83% (80 runs sampled) + inflate-pako-string x 45.19 ops/sec ±1.69% (57 runs sampled) + inflate-pako-untyped x 24.35 ops/sec ±2.59% (40 runs sampled) + * inflate-zlib x 60.32 ops/sec ±1.36% (69 runs sampled) +``` + +zlib's test is partially affected by marshalling (that make sense for inflate only). +You can change deflate level to 0 in benchmark source, to investigate details. +For deflate level 6 results can be considered as correct. + +__Install:__ + +node.js: + +``` +npm install pako +``` + +browser: + +``` +bower install pako +``` + + +Example & API +------------- + +Full docs - http://nodeca.github.io/pako/ + +```javascript +var pako = require('pako'); + +// Deflate +// +var input = new Uint8Array(); +//... fill input data here +var output = pako.deflate(input); + +// Inflate (simple wrapper can throw exception on broken stream) +// +var compressed = new Uint8Array(); +//... fill data to uncompress here +try { + var result = pako.inflate(compressed); +} catch (err) { + console.log(err); +} + +// +// Alternate interface for chunking & without exceptions +// + +var inflator = new pako.Inflate(); + +inflator.push(chunk1, false); +inflator.push(chunk2, false); +... +inflator.push(chunkN, true); // true -> last chunk + +if (inflator.err) { + console.log(inflator.msg); +} + +var output = inflator.result; + +``` + +Sometime you can wish to work with strings. For example, to send +big objects as json to server. Pako detects input data type. You can +force output to be string with option `{ to: 'string' }`. + +```javascript +var pako = require('pako'); + +var test = { my: 'super', puper: [456, 567], awesome: 'pako' }; + +var binaryString = pako.deflate(JSON.stringify(test), { to: 'string' }); + +// +// Here you can do base64 encode, make xhr requests and so on. +// + +var restored = JSON.parse(pako.inflate(binaryString, { to: 'string' })); +``` + + +Notes +----- + +Pako does not contain some specific zlib functions: + +- __deflate__ - methods `deflateCopy`, `deflateBound`, `deflateParams`, + `deflatePending`, `deflatePrime`, `deflateTune`. +- __inflate__ - methods `inflateCopy`, `inflateMark`, + `inflatePrime`, `inflateGetDictionary`, `inflateSync`, `inflateSyncPoint`, `inflateUndermine`. +- High level inflate/deflate wrappers (classes) may not support some flush + modes. Those should work: Z_NO_FLUSH, Z_FINISH, Z_SYNC_FLUSH. + + +pako for enterprise +------------------- + +Available as part of the Tidelift Subscription + +The maintainers of pako and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-pako?utm_source=npm-pako&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + + +Authors +------- + +- Andrey Tupitsin [@anrd83](https://github.com/andr83) +- Vitaly Puzrin [@puzrin](https://github.com/puzrin) + +Personal thanks to: + +- Vyacheslav Egorov ([@mraleph](https://github.com/mraleph)) for his awesome + tutorials about optimising JS code for v8, [IRHydra](http://mrale.ph/irhydra/) + tool and his advices. +- David Duponchel ([@dduponchel](https://github.com/dduponchel)) for help with + testing. + +Original implementation (in C): + +- [zlib](http://zlib.net/) by Jean-loup Gailly and Mark Adler. + + +License +------- + +- MIT - all files, except `/lib/zlib` folder +- ZLIB - `/lib/zlib` content diff --git a/node_modules/pako/dist/pako.js b/node_modules/pako/dist/pako.js new file mode 100644 index 0000000000000000000000000000000000000000..9ab7c686a9b49c6908d2f869c41a841b20485dbb --- /dev/null +++ b/node_modules/pako/dist/pako.js @@ -0,0 +1,6818 @@ +/* pako 1.0.11 nodeca/pako */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.pako = f()}})(function(){var define,module,exports;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;i Array + * + * Chunks of output data, if [[Deflate#onData]] not overridden. + **/ + +/** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + +/** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + + +/** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ +function Deflate(options) { + if (!(this instanceof Deflate)) return new Deflate(options); + + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: '' + }, options || {}); + + var opt = this.options; + + if (opt.raw && (opt.windowBits > 0)) { + opt.windowBits = -opt.windowBits; + } + + else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { + opt.windowBits += 16; + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_deflate.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } + + if (opt.dictionary) { + var dict; + // Convert data if needed + if (typeof opt.dictionary === 'string') { + // If we need to compress text, change encoding to utf8. + dict = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + + status = zlib_deflate.deflateSetDictionary(this.strm, dict); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + this._dict_set = true; + } +} + +/** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Deflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + + if (this.ended) { return false; } + + _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings.string2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { + if (this.options.to === 'string') { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + + // Finalize on the last chunk. + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Deflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Deflate.prototype.onEnd = function (status) { + // On success - join + if (status === Z_OK) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate algorithm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * - dictionary + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ +function deflate(input, options) { + var deflator = new Deflate(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg || msg[deflator.err]; } + + return deflator.result; +} + + +/** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); +} + + +/** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ +function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); +} + + +exports.Deflate = Deflate; +exports.deflate = deflate; +exports.deflateRaw = deflateRaw; +exports.gzip = gzip; + +},{"./utils/common":3,"./utils/strings":4,"./zlib/deflate":8,"./zlib/messages":13,"./zlib/zstream":15}],2:[function(require,module,exports){ +'use strict'; + + +var zlib_inflate = require('./zlib/inflate'); +var utils = require('./utils/common'); +var strings = require('./utils/strings'); +var c = require('./zlib/constants'); +var msg = require('./zlib/messages'); +var ZStream = require('./zlib/zstream'); +var GZheader = require('./zlib/gzheader'); + +var toString = Object.prototype.toString; + +/** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + +/* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overridden. + **/ + +/** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + +/** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + +/** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ +function Inflate(options) { + if (!(this instanceof Inflate)) return new Inflate(options); + + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: '' + }, options || {}); + + var opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_inflate.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + + this.header = new GZheader(); + + zlib_inflate.inflateGetHeader(this.strm, this.header); + + // Setup dictionary + if (opt.dictionary) { + // Convert data if needed + if (typeof opt.dictionary === 'string') { + opt.dictionary = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { //In raw mode we need to set the dictionary early + status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + } + } +} + +/** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Inflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status, _mode; + var next_out_utf8, tail, utf8str; + + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; + + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // Only binary strings can be decompressed on practice + strm.input = strings.binstring2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ + + if (status === c.Z_NEED_DICT && dictionary) { + status = zlib_inflate.inflateSetDictionary(this.strm, dictionary); + } + + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { + + if (this.options.to === 'string') { + + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Inflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Inflate.prototype.onEnd = function (status) { + // On success - join + if (status === c.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 aligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ +function inflate(input, options) { + var inflator = new Inflate(options); + + inflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) { throw inflator.msg || msg[inflator.err]; } + + return inflator.result; +} + + +/** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); +} + + +/** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + +exports.Inflate = Inflate; +exports.inflate = inflate; +exports.inflateRaw = inflateRaw; +exports.ungzip = inflate; + +},{"./utils/common":3,"./utils/strings":4,"./zlib/constants":6,"./zlib/gzheader":9,"./zlib/inflate":11,"./zlib/messages":13,"./zlib/zstream":15}],3:[function(require,module,exports){ +'use strict'; + + +var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + +function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// reduce buffer size, avoiding mem copy +exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; + } +}; + +var fnUntyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + return [].concat.apply([], chunks); + } +}; + + +// Enable/Disable typed arrays use, for testing +// +exports.setTyped = function (on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } +}; + +exports.setTyped(TYPED_OK); + +},{}],4:[function(require,module,exports){ +// String encode/decode helpers +'use strict'; + + +var utils = require('./common'); + + +// Quick check if we can use fast array to bin string conversion +// +// - apply(Array) can fail on Android 2.2 +// - apply(Uint8Array) can fail on iOS 5.1 Safari +// +var STR_APPLY_OK = true; +var STR_APPLY_UIA_OK = true; + +try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; } +try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } + + +// Table with utf8 lengths (calculated by first byte of sequence) +// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, +// because max possible codepoint is 0x10ffff +var _utf8len = new utils.Buf8(256); +for (var q = 0; q < 256; q++) { + _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); +} +_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start + + +// convert string to array (typed, when possible) +exports.string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new utils.Buf8(buf_len); + + // convert + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper (used in 2 places) +function buf2binstring(buf, len) { + // On Chrome, the arguments in a function call that are allowed is `65534`. + // If the length of the buffer is smaller than that, we can use this optimization, + // otherwise we will take a slower path. + if (len < 65534) { + if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + + +// Convert byte array to binary string +exports.buf2binstring = function (buf) { + return buf2binstring(buf, buf.length); +}; + + +// Convert binary string (typed, when possible) +exports.binstring2buf = function (str) { + var buf = new utils.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; +}; + + +// convert array to string +exports.buf2string = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len * 2); + + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + // quick process ascii + if (c < 0x80) { utf16buf[out++] = c; continue; } + + c_len = _utf8len[c]; + // skip 5 & 6 byte codes + if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +exports.utf8border = function (buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max - 1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means buffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len[buf[pos]] > max) ? pos : max; +}; + +},{"./common":3}],5:[function(require,module,exports){ +'use strict'; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; + +},{}],6:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; + +},{}],7:[function(require,module,exports){ +'use strict'; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; + +},{}],8:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); +var trees = require('./trees'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var msg = require('./messages'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; +} + + +exports.deflateInit = deflateInit; +exports.deflateInit2 = deflateInit2; +exports.deflateReset = deflateReset; +exports.deflateResetKeep = deflateResetKeep; +exports.deflateSetHeader = deflateSetHeader; +exports.deflate = deflate; +exports.deflateEnd = deflateEnd; +exports.deflateSetDictionary = deflateSetDictionary; +exports.deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + +},{"../utils/common":3,"./adler32":5,"./crc32":7,"./messages":13,"./trees":14}],9:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} + +module.exports = GZheader; + +},{}],10:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + +},{}],11:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var inflate_fast = require('./inffast'); +var inflate_table = require('./inftrees'); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + +function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +exports.inflateReset = inflateReset; +exports.inflateReset2 = inflateReset2; +exports.inflateResetKeep = inflateResetKeep; +exports.inflateInit = inflateInit; +exports.inflateInit2 = inflateInit2; +exports.inflate = inflate; +exports.inflateEnd = inflateEnd; +exports.inflateGetHeader = inflateGetHeader; +exports.inflateSetDictionary = inflateSetDictionary; +exports.inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + +},{"../utils/common":3,"./adler32":5,"./crc32":7,"./inffast":10,"./inftrees":12}],12:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + +},{"../utils/common":3}],13:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; + +},{}],14:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +/* eslint-disable space-unary-ops */ + +var utils = require('../utils/common'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +exports._tr_init = _tr_init; +exports._tr_stored_block = _tr_stored_block; +exports._tr_flush_block = _tr_flush_block; +exports._tr_tally = _tr_tally; +exports._tr_align = _tr_align; + +},{"../utils/common":3}],15:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; + +},{}],"/":[function(require,module,exports){ +// Top level file is just a mixin of submodules & constants +'use strict'; + +var assign = require('./lib/utils/common').assign; + +var deflate = require('./lib/deflate'); +var inflate = require('./lib/inflate'); +var constants = require('./lib/zlib/constants'); + +var pako = {}; + +assign(pako, deflate, inflate, constants); + +module.exports = pako; + +},{"./lib/deflate":1,"./lib/inflate":2,"./lib/utils/common":3,"./lib/zlib/constants":6}]},{},[])("/") +}); diff --git a/node_modules/pako/dist/pako.min.js b/node_modules/pako/dist/pako.min.js new file mode 100644 index 0000000000000000000000000000000000000000..ba397319e12a3f9af8338f4494de65077197355b --- /dev/null +++ b/node_modules/pako/dist/pako.min.js @@ -0,0 +1 @@ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).pako=t()}}(function(){return function r(s,o,l){function h(e,t){if(!o[e]){if(!s[e]){var a="function"==typeof require&&require;if(!t&&a)return a(e,!0);if(d)return d(e,!0);var i=new Error("Cannot find module '"+e+"'");throw i.code="MODULE_NOT_FOUND",i}var n=o[e]={exports:{}};s[e][0].call(n.exports,function(t){return h(s[e][1][t]||t)},n,n.exports,r,s,o,l)}return o[e].exports}for(var d="function"==typeof require&&require,t=0;t>>6:(a<65536?e[r++]=224|a>>>12:(e[r++]=240|a>>>18,e[r++]=128|a>>>12&63),e[r++]=128|a>>>6&63),e[r++]=128|63&a);return e},a.buf2binstring=function(t){return d(t,t.length)},a.binstring2buf=function(t){for(var e=new l.Buf8(t.length),a=0,i=e.length;a>10&1023,o[i++]=56320|1023&n)}return d(o,i)},a.utf8border=function(t,e){var a;for((e=e||t.length)>t.length&&(e=t.length),a=e-1;0<=a&&128==(192&t[a]);)a--;return a<0?e:0===a?e:a+h[t[a]]>e?a:e}},{"./common":3}],5:[function(t,e,a){"use strict";e.exports=function(t,e,a,i){for(var n=65535&t|0,r=t>>>16&65535|0,s=0;0!==a;){for(a-=s=2e3>>1:t>>>1;e[a]=t}return e}();e.exports=function(t,e,a,i){var n=o,r=i+a;t^=-1;for(var s=i;s>>8^n[255&(t^e[s])];return-1^t}},{}],8:[function(t,e,a){"use strict";var l,_=t("../utils/common"),h=t("./trees"),u=t("./adler32"),c=t("./crc32"),i=t("./messages"),d=0,f=4,b=0,g=-2,m=-1,w=4,n=2,p=8,v=9,r=286,s=30,o=19,k=2*r+1,y=15,x=3,z=258,B=z+x+1,S=42,E=113,A=1,Z=2,R=3,C=4;function N(t,e){return t.msg=i[e],e}function O(t){return(t<<1)-(4t.avail_out&&(a=t.avail_out),0!==a&&(_.arraySet(t.output,e.pending_buf,e.pending_out,a,t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))}function U(t,e){h._tr_flush_block(t,0<=t.block_start?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,I(t.strm)}function T(t,e){t.pending_buf[t.pending++]=e}function F(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function L(t,e){var a,i,n=t.max_chain_length,r=t.strstart,s=t.prev_length,o=t.nice_match,l=t.strstart>t.w_size-B?t.strstart-(t.w_size-B):0,h=t.window,d=t.w_mask,f=t.prev,_=t.strstart+z,u=h[r+s-1],c=h[r+s];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do{if(h[(a=e)+s]===c&&h[a+s-1]===u&&h[a]===h[r]&&h[++a]===h[r+1]){r+=2,a++;do{}while(h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&r<_);if(i=z-(_-r),r=_-z,sl&&0!=--n);return s<=t.lookahead?s:t.lookahead}function H(t){var e,a,i,n,r,s,o,l,h,d,f=t.w_size;do{if(n=t.window_size-t.lookahead-t.strstart,t.strstart>=f+(f-B)){for(_.arraySet(t.window,t.window,f,f,0),t.match_start-=f,t.strstart-=f,t.block_start-=f,e=a=t.hash_size;i=t.head[--e],t.head[e]=f<=i?i-f:0,--a;);for(e=a=f;i=t.prev[--e],t.prev[e]=f<=i?i-f:0,--a;);n+=f}if(0===t.strm.avail_in)break;if(s=t.strm,o=t.window,l=t.strstart+t.lookahead,h=n,d=void 0,d=s.avail_in,h=x)for(r=t.strstart-t.insert,t.ins_h=t.window[r],t.ins_h=(t.ins_h<=x&&(t.ins_h=(t.ins_h<=x)if(i=h._tr_tally(t,t.strstart-t.match_start,t.match_length-x),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=x){for(t.match_length--;t.strstart++,t.ins_h=(t.ins_h<=x&&(t.ins_h=(t.ins_h<=x&&t.match_length<=t.prev_length){for(n=t.strstart+t.lookahead-x,i=h._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-x),t.lookahead-=t.prev_length-1,t.prev_length-=2;++t.strstart<=n&&(t.ins_h=(t.ins_h<t.pending_buf_size-5&&(a=t.pending_buf_size-5);;){if(t.lookahead<=1){if(H(t),0===t.lookahead&&e===d)return A;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var i=t.block_start+a;if((0===t.strstart||t.strstart>=i)&&(t.lookahead=t.strstart-i,t.strstart=i,U(t,!1),0===t.strm.avail_out))return A;if(t.strstart-t.block_start>=t.w_size-B&&(U(t,!1),0===t.strm.avail_out))return A}return t.insert=0,e===f?(U(t,!0),0===t.strm.avail_out?R:C):(t.strstart>t.block_start&&(U(t,!1),t.strm.avail_out),A)}),new M(4,4,8,4,j),new M(4,5,16,8,j),new M(4,6,32,32,j),new M(4,4,16,16,K),new M(8,16,32,32,K),new M(8,16,128,128,K),new M(8,32,128,256,K),new M(32,128,258,1024,K),new M(32,258,258,4096,K)],a.deflateInit=function(t,e){return G(t,e,p,15,8,0)},a.deflateInit2=G,a.deflateReset=q,a.deflateResetKeep=Y,a.deflateSetHeader=function(t,e){return t&&t.state?2!==t.state.wrap?g:(t.state.gzhead=e,b):g},a.deflate=function(t,e){var a,i,n,r;if(!t||!t.state||5>8&255),T(i,i.gzhead.time>>16&255),T(i,i.gzhead.time>>24&255),T(i,9===i.level?2:2<=i.strategy||i.level<2?4:0),T(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(T(i,255&i.gzhead.extra.length),T(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=c(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69):(T(i,0),T(i,0),T(i,0),T(i,0),T(i,0),T(i,9===i.level?2:2<=i.strategy||i.level<2?4:0),T(i,3),i.status=E);else{var s=p+(i.w_bits-8<<4)<<8;s|=(2<=i.strategy||i.level<2?0:i.level<6?1:6===i.level?2:3)<<6,0!==i.strstart&&(s|=32),s+=31-s%31,i.status=E,F(i,s),0!==i.strstart&&(F(i,t.adler>>>16),F(i,65535&t.adler)),t.adler=1}if(69===i.status)if(i.gzhead.extra){for(n=i.pending;i.gzindex<(65535&i.gzhead.extra.length)&&(i.pending!==i.pending_buf_size||(i.gzhead.hcrc&&i.pending>n&&(t.adler=c(t.adler,i.pending_buf,i.pending-n,n)),I(t),n=i.pending,i.pending!==i.pending_buf_size));)T(i,255&i.gzhead.extra[i.gzindex]),i.gzindex++;i.gzhead.hcrc&&i.pending>n&&(t.adler=c(t.adler,i.pending_buf,i.pending-n,n)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=73)}else i.status=73;if(73===i.status)if(i.gzhead.name){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(t.adler=c(t.adler,i.pending_buf,i.pending-n,n)),I(t),n=i.pending,i.pending===i.pending_buf_size)){r=1;break}T(i,r=i.gzindexn&&(t.adler=c(t.adler,i.pending_buf,i.pending-n,n)),0===r&&(i.gzindex=0,i.status=91)}else i.status=91;if(91===i.status)if(i.gzhead.comment){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(t.adler=c(t.adler,i.pending_buf,i.pending-n,n)),I(t),n=i.pending,i.pending===i.pending_buf_size)){r=1;break}T(i,r=i.gzindexn&&(t.adler=c(t.adler,i.pending_buf,i.pending-n,n)),0===r&&(i.status=103)}else i.status=103;if(103===i.status&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&I(t),i.pending+2<=i.pending_buf_size&&(T(i,255&t.adler),T(i,t.adler>>8&255),t.adler=0,i.status=E)):i.status=E),0!==i.pending){if(I(t),0===t.avail_out)return i.last_flush=-1,b}else if(0===t.avail_in&&O(e)<=O(a)&&e!==f)return N(t,-5);if(666===i.status&&0!==t.avail_in)return N(t,-5);if(0!==t.avail_in||0!==i.lookahead||e!==d&&666!==i.status){var o=2===i.strategy?function(t,e){for(var a;;){if(0===t.lookahead&&(H(t),0===t.lookahead)){if(e===d)return A;break}if(t.match_length=0,a=h._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(U(t,!1),0===t.strm.avail_out))return A}return t.insert=0,e===f?(U(t,!0),0===t.strm.avail_out?R:C):t.last_lit&&(U(t,!1),0===t.strm.avail_out)?A:Z}(i,e):3===i.strategy?function(t,e){for(var a,i,n,r,s=t.window;;){if(t.lookahead<=z){if(H(t),t.lookahead<=z&&e===d)return A;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=x&&0t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=x?(a=h._tr_tally(t,1,t.match_length-x),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=h._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(U(t,!1),0===t.strm.avail_out))return A}return t.insert=0,e===f?(U(t,!0),0===t.strm.avail_out?R:C):t.last_lit&&(U(t,!1),0===t.strm.avail_out)?A:Z}(i,e):l[i.level].func(i,e);if(o!==R&&o!==C||(i.status=666),o===A||o===R)return 0===t.avail_out&&(i.last_flush=-1),b;if(o===Z&&(1===e?h._tr_align(i):5!==e&&(h._tr_stored_block(i,0,0,!1),3===e&&(D(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),I(t),0===t.avail_out))return i.last_flush=-1,b}return e!==f?b:i.wrap<=0?1:(2===i.wrap?(T(i,255&t.adler),T(i,t.adler>>8&255),T(i,t.adler>>16&255),T(i,t.adler>>24&255),T(i,255&t.total_in),T(i,t.total_in>>8&255),T(i,t.total_in>>16&255),T(i,t.total_in>>24&255)):(F(i,t.adler>>>16),F(i,65535&t.adler)),I(t),0=a.w_size&&(0===r&&(D(a.head),a.strstart=0,a.block_start=0,a.insert=0),h=new _.Buf8(a.w_size),_.arraySet(h,e,d-a.w_size,a.w_size,0),e=h,d=a.w_size),s=t.avail_in,o=t.next_in,l=t.input,t.avail_in=d,t.next_in=0,t.input=e,H(a);a.lookahead>=x;){for(i=a.strstart,n=a.lookahead-(x-1);a.ins_h=(a.ins_h<>>=v=p>>>24,c-=v,0===(v=p>>>16&255))S[r++]=65535&p;else{if(!(16&v)){if(0==(64&v)){p=b[(65535&p)+(u&(1<>>=v,c-=v),c<15&&(u+=B[i++]<>>=v=p>>>24,c-=v,!(16&(v=p>>>16&255))){if(0==(64&v)){p=g[(65535&p)+(u&(1<>>=v,c-=v,(v=r-s)>3,u&=(1<<(c-=k<<3))-1,t.next_in=i,t.next_out=r,t.avail_in=i>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function r(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Z.Buf16(320),this.work=new Z.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function s(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=F,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Z.Buf32(i),e.distcode=e.distdyn=new Z.Buf32(n),e.sane=1,e.back=-1,U):T}function o(t){var e;return t&&t.state?((e=t.state).wsize=0,e.whave=0,e.wnext=0,s(t)):T}function l(t,e){var a,i;return t&&t.state?(i=t.state,e<0?(a=0,e=-e):(a=1+(e>>4),e<48&&(e&=15)),e&&(e<8||15=r.wsize?(Z.arraySet(r.window,e,a-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(i<(n=r.wsize-r.wnext)&&(n=i),Z.arraySet(r.window,e,a-i,n,r.wnext),(i-=n)?(Z.arraySet(r.window,e,a-i,i,0),r.wnext=i,r.whave=r.wsize):(r.wnext+=n,r.wnext===r.wsize&&(r.wnext=0),r.whave>>8&255,a.check=C(a.check,E,2,0),d=h=0,a.mode=2;break}if(a.flags=0,a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg="incorrect header check",a.mode=30;break}if(8!=(15&h)){t.msg="unknown compression method",a.mode=30;break}if(d-=4,y=8+(15&(h>>>=4)),0===a.wbits)a.wbits=y;else if(y>a.wbits){t.msg="invalid window size",a.mode=30;break}a.dmax=1<>8&1),512&a.flags&&(E[0]=255&h,E[1]=h>>>8&255,a.check=C(a.check,E,2,0)),d=h=0,a.mode=3;case 3:for(;d<32;){if(0===o)break t;o--,h+=i[r++]<>>8&255,E[2]=h>>>16&255,E[3]=h>>>24&255,a.check=C(a.check,E,4,0)),d=h=0,a.mode=4;case 4:for(;d<16;){if(0===o)break t;o--,h+=i[r++]<>8),512&a.flags&&(E[0]=255&h,E[1]=h>>>8&255,a.check=C(a.check,E,2,0)),d=h=0,a.mode=5;case 5:if(1024&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[r++]<>>8&255,a.check=C(a.check,E,2,0)),d=h=0}else a.head&&(a.head.extra=null);a.mode=6;case 6:if(1024&a.flags&&(o<(u=a.length)&&(u=o),u&&(a.head&&(y=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Array(a.head.extra_len)),Z.arraySet(a.head.extra,i,r,u,y)),512&a.flags&&(a.check=C(a.check,i,u,r)),o-=u,r+=u,a.length-=u),a.length))break t;a.length=0,a.mode=7;case 7:if(2048&a.flags){if(0===o)break t;for(u=0;y=i[r+u++],a.head&&y&&a.length<65536&&(a.head.name+=String.fromCharCode(y)),y&&u>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=12;break;case 10:for(;d<32;){if(0===o)break t;o--,h+=i[r++]<>>=7&d,d-=7&d,a.mode=27;break}for(;d<3;){if(0===o)break t;o--,h+=i[r++]<>>=1)){case 0:a.mode=14;break;case 1:if(H(a),a.mode=20,6!==e)break;h>>>=2,d-=2;break t;case 2:a.mode=17;break;case 3:t.msg="invalid block type",a.mode=30}h>>>=2,d-=2;break;case 14:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[r++]<>>16^65535)){t.msg="invalid stored block lengths",a.mode=30;break}if(a.length=65535&h,d=h=0,a.mode=15,6===e)break t;case 15:a.mode=16;case 16:if(u=a.length){if(o>>=5,d-=5,a.ndist=1+(31&h),h>>>=5,d-=5,a.ncode=4+(15&h),h>>>=4,d-=4,286>>=3,d-=3}for(;a.have<19;)a.lens[A[a.have++]]=0;if(a.lencode=a.lendyn,a.lenbits=7,z={bits:a.lenbits},x=O(0,a.lens,0,19,a.lencode,0,a.work,z),a.lenbits=z.bits,x){t.msg="invalid code lengths set",a.mode=30;break}a.have=0,a.mode=19;case 19:for(;a.have>>16&255,w=65535&S,!((g=S>>>24)<=d);){if(0===o)break t;o--,h+=i[r++]<>>=g,d-=g,a.lens[a.have++]=w;else{if(16===w){for(B=g+2;d>>=g,d-=g,0===a.have){t.msg="invalid bit length repeat",a.mode=30;break}y=a.lens[a.have-1],u=3+(3&h),h>>>=2,d-=2}else if(17===w){for(B=g+3;d>>=g)),h>>>=3,d-=3}else{for(B=g+7;d>>=g)),h>>>=7,d-=7}if(a.have+u>a.nlen+a.ndist){t.msg="invalid bit length repeat",a.mode=30;break}for(;u--;)a.lens[a.have++]=y}}if(30===a.mode)break;if(0===a.lens[256]){t.msg="invalid code -- missing end-of-block",a.mode=30;break}if(a.lenbits=9,z={bits:a.lenbits},x=O(D,a.lens,0,a.nlen,a.lencode,0,a.work,z),a.lenbits=z.bits,x){t.msg="invalid literal/lengths set",a.mode=30;break}if(a.distbits=6,a.distcode=a.distdyn,z={bits:a.distbits},x=O(I,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,z),a.distbits=z.bits,x){t.msg="invalid distances set",a.mode=30;break}if(a.mode=20,6===e)break t;case 20:a.mode=21;case 21:if(6<=o&&258<=l){t.next_out=s,t.avail_out=l,t.next_in=r,t.avail_in=o,a.hold=h,a.bits=d,N(t,_),s=t.next_out,n=t.output,l=t.avail_out,r=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,12===a.mode&&(a.back=-1);break}for(a.back=0;m=(S=a.lencode[h&(1<>>16&255,w=65535&S,!((g=S>>>24)<=d);){if(0===o)break t;o--,h+=i[r++]<>p)])>>>16&255,w=65535&S,!(p+(g=S>>>24)<=d);){if(0===o)break t;o--,h+=i[r++]<>>=p,d-=p,a.back+=p}if(h>>>=g,d-=g,a.back+=g,a.length=w,0===m){a.mode=26;break}if(32&m){a.back=-1,a.mode=12;break}if(64&m){t.msg="invalid literal/length code",a.mode=30;break}a.extra=15&m,a.mode=22;case 22:if(a.extra){for(B=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra}a.was=a.length,a.mode=23;case 23:for(;m=(S=a.distcode[h&(1<>>16&255,w=65535&S,!((g=S>>>24)<=d);){if(0===o)break t;o--,h+=i[r++]<>p)])>>>16&255,w=65535&S,!(p+(g=S>>>24)<=d);){if(0===o)break t;o--,h+=i[r++]<>>=p,d-=p,a.back+=p}if(h>>>=g,d-=g,a.back+=g,64&m){t.msg="invalid distance code",a.mode=30;break}a.offset=w,a.extra=15&m,a.mode=24;case 24:if(a.extra){for(B=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra}if(a.offset>a.dmax){t.msg="invalid distance too far back",a.mode=30;break}a.mode=25;case 25:if(0===l)break t;if(u=_-l,a.offset>u){if((u=a.offset-u)>a.whave&&a.sane){t.msg="invalid distance too far back",a.mode=30;break}u>a.wnext?(u-=a.wnext,c=a.wsize-u):c=a.wnext-u,u>a.length&&(u=a.length),b=a.window}else b=n,c=s-a.offset,u=a.length;for(lu?(b=N[O+s[p]],g=A[Z+s[p]]):(b=96,g=0),l=1<>z)+(h-=l)]=c<<24|b<<16|g|0,0!==h;);for(l=1<>=1;if(0!==l?(E&=l-1,E+=l):E=0,p++,0==--R[w]){if(w===k)break;w=e[a+s[p]]}if(y>>7)]}function T(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function F(t,e,a){t.bi_valid>n-a?(t.bi_buf|=e<>n-t.bi_valid,t.bi_valid+=a-n):(t.bi_buf|=e<>>=1,a<<=1,0<--e;);return a>>>1}function j(t,e,a){var i,n,r=new Array(m+1),s=0;for(i=1;i<=m;i++)r[i]=s=s+a[i-1]<<1;for(n=0;n<=e;n++){var o=t[2*n+1];0!==o&&(t[2*n]=H(r[o]++,o))}}function K(t){var e;for(e=0;e<_;e++)t.dyn_ltree[2*e]=0;for(e=0;e>1;1<=a;a--)Y(t,r,a);for(n=l;a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],Y(t,r,1),i=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=i,r[2*n]=r[2*a]+r[2*i],t.depth[n]=(t.depth[a]>=t.depth[i]?t.depth[a]:t.depth[i])+1,r[2*a+1]=r[2*i+1]=n,t.heap[1]=n++,Y(t,r,1),2<=t.heap_len;);t.heap[--t.heap_max]=t.heap[1],function(t,e){var a,i,n,r,s,o,l=e.dyn_tree,h=e.max_code,d=e.stat_desc.static_tree,f=e.stat_desc.has_stree,_=e.stat_desc.extra_bits,u=e.stat_desc.extra_base,c=e.stat_desc.max_length,b=0;for(r=0;r<=m;r++)t.bl_count[r]=0;for(l[2*t.heap[t.heap_max]+1]=0,a=t.heap_max+1;a>=7;i>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return o;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return h;for(e=32;e>>3,(r=t.static_len+3+7>>>3)<=n&&(n=r)):n=r=a+5,a+4<=n&&-1!==e?Q(t,e,a,i):4===t.strategy||r===n?(F(t,2+(i?1:0),3),q(t,S,E)):(F(t,4+(i?1:0),3),function(t,e,a,i){var n;for(F(t,e-257,5),F(t,a-1,5),F(t,i-4,4),n=0;n>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&a,t.last_lit++,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(Z[a]+f+1)]++,t.dyn_dtree[2*U(e)]++),t.last_lit===t.lit_bufsize-1},a._tr_align=function(t){var e;F(t,2,3),L(t,w,S),16===(e=t).bi_valid?(T(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}},{"../utils/common":3}],15:[function(t,e,a){"use strict";e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/":[function(t,e,a){"use strict";var i={};(0,t("./lib/utils/common").assign)(i,t("./lib/deflate"),t("./lib/inflate"),t("./lib/zlib/constants")),e.exports=i},{"./lib/deflate":1,"./lib/inflate":2,"./lib/utils/common":3,"./lib/zlib/constants":6}]},{},[])("/")}); diff --git a/node_modules/pako/dist/pako_deflate.js b/node_modules/pako/dist/pako_deflate.js new file mode 100644 index 0000000000000000000000000000000000000000..d6bbaa159fd0d375c40ee670b9183837d68017b9 --- /dev/null +++ b/node_modules/pako/dist/pako_deflate.js @@ -0,0 +1,3997 @@ +/* pako 1.0.11 nodeca/pako */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.pako = f()}})(function(){var define,module,exports;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;i= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); +} +_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start + + +// convert string to array (typed, when possible) +exports.string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new utils.Buf8(buf_len); + + // convert + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper (used in 2 places) +function buf2binstring(buf, len) { + // On Chrome, the arguments in a function call that are allowed is `65534`. + // If the length of the buffer is smaller than that, we can use this optimization, + // otherwise we will take a slower path. + if (len < 65534) { + if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + + +// Convert byte array to binary string +exports.buf2binstring = function (buf) { + return buf2binstring(buf, buf.length); +}; + + +// Convert binary string (typed, when possible) +exports.binstring2buf = function (str) { + var buf = new utils.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; +}; + + +// convert array to string +exports.buf2string = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len * 2); + + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + // quick process ascii + if (c < 0x80) { utf16buf[out++] = c; continue; } + + c_len = _utf8len[c]; + // skip 5 & 6 byte codes + if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +exports.utf8border = function (buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max - 1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means buffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len[buf[pos]] > max) ? pos : max; +}; + +},{"./common":1}],3:[function(require,module,exports){ +'use strict'; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; + +},{}],4:[function(require,module,exports){ +'use strict'; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; + +},{}],5:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); +var trees = require('./trees'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var msg = require('./messages'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; +} + + +exports.deflateInit = deflateInit; +exports.deflateInit2 = deflateInit2; +exports.deflateReset = deflateReset; +exports.deflateResetKeep = deflateResetKeep; +exports.deflateSetHeader = deflateSetHeader; +exports.deflate = deflate; +exports.deflateEnd = deflateEnd; +exports.deflateSetDictionary = deflateSetDictionary; +exports.deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + +},{"../utils/common":1,"./adler32":3,"./crc32":4,"./messages":6,"./trees":7}],6:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; + +},{}],7:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +/* eslint-disable space-unary-ops */ + +var utils = require('../utils/common'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +exports._tr_init = _tr_init; +exports._tr_stored_block = _tr_stored_block; +exports._tr_flush_block = _tr_flush_block; +exports._tr_tally = _tr_tally; +exports._tr_align = _tr_align; + +},{"../utils/common":1}],8:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; + +},{}],"/lib/deflate.js":[function(require,module,exports){ +'use strict'; + + +var zlib_deflate = require('./zlib/deflate'); +var utils = require('./utils/common'); +var strings = require('./utils/strings'); +var msg = require('./zlib/messages'); +var ZStream = require('./zlib/zstream'); + +var toString = Object.prototype.toString; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +var Z_NO_FLUSH = 0; +var Z_FINISH = 4; + +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_SYNC_FLUSH = 2; + +var Z_DEFAULT_COMPRESSION = -1; + +var Z_DEFAULT_STRATEGY = 0; + +var Z_DEFLATED = 8; + +/* ===========================================================================*/ + + +/** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ + +/* internal + * Deflate.chunks -> Array + * + * Chunks of output data, if [[Deflate#onData]] not overridden. + **/ + +/** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + +/** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + + +/** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ +function Deflate(options) { + if (!(this instanceof Deflate)) return new Deflate(options); + + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: '' + }, options || {}); + + var opt = this.options; + + if (opt.raw && (opt.windowBits > 0)) { + opt.windowBits = -opt.windowBits; + } + + else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { + opt.windowBits += 16; + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_deflate.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } + + if (opt.dictionary) { + var dict; + // Convert data if needed + if (typeof opt.dictionary === 'string') { + // If we need to compress text, change encoding to utf8. + dict = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + + status = zlib_deflate.deflateSetDictionary(this.strm, dict); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + this._dict_set = true; + } +} + +/** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Deflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + + if (this.ended) { return false; } + + _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings.string2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { + if (this.options.to === 'string') { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + + // Finalize on the last chunk. + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Deflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Deflate.prototype.onEnd = function (status) { + // On success - join + if (status === Z_OK) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate algorithm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * - dictionary + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ +function deflate(input, options) { + var deflator = new Deflate(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg || msg[deflator.err]; } + + return deflator.result; +} + + +/** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); +} + + +/** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ +function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); +} + + +exports.Deflate = Deflate; +exports.deflate = deflate; +exports.deflateRaw = deflateRaw; +exports.gzip = gzip; + +},{"./utils/common":1,"./utils/strings":2,"./zlib/deflate":5,"./zlib/messages":6,"./zlib/zstream":8}]},{},[])("/lib/deflate.js") +}); diff --git a/node_modules/pako/dist/pako_deflate.min.js b/node_modules/pako/dist/pako_deflate.min.js new file mode 100644 index 0000000000000000000000000000000000000000..779255340dde66b299c9d9a04c4a5c04d508bee4 --- /dev/null +++ b/node_modules/pako/dist/pako_deflate.min.js @@ -0,0 +1 @@ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).pako=t()}}(function(){return function i(s,h,l){function o(e,t){if(!h[e]){if(!s[e]){var a="function"==typeof require&&require;if(!t&&a)return a(e,!0);if(_)return _(e,!0);var n=new Error("Cannot find module '"+e+"'");throw n.code="MODULE_NOT_FOUND",n}var r=h[e]={exports:{}};s[e][0].call(r.exports,function(t){return o(s[e][1][t]||t)},r,r.exports,i,s,h,l)}return h[e].exports}for(var _="function"==typeof require&&require,t=0;t>>6:(a<65536?e[i++]=224|a>>>12:(e[i++]=240|a>>>18,e[i++]=128|a>>>12&63),e[i++]=128|a>>>6&63),e[i++]=128|63&a);return e},a.buf2binstring=function(t){return _(t,t.length)},a.binstring2buf=function(t){for(var e=new l.Buf8(t.length),a=0,n=e.length;a>10&1023,h[n++]=56320|1023&r)}return _(h,n)},a.utf8border=function(t,e){var a;for((e=e||t.length)>t.length&&(e=t.length),a=e-1;0<=a&&128==(192&t[a]);)a--;return a<0?e:0===a?e:a+o[t[a]]>e?a:e}},{"./common":1}],3:[function(t,e,a){"use strict";e.exports=function(t,e,a,n){for(var r=65535&t|0,i=t>>>16&65535|0,s=0;0!==a;){for(a-=s=2e3>>1:t>>>1;e[a]=t}return e}();e.exports=function(t,e,a,n){var r=h,i=n+a;t^=-1;for(var s=n;s>>8^r[255&(t^e[s])];return-1^t}},{}],5:[function(t,e,a){"use strict";var l,u=t("../utils/common"),o=t("./trees"),f=t("./adler32"),c=t("./crc32"),n=t("./messages"),_=0,d=4,p=0,g=-2,m=-1,b=4,r=2,v=8,w=9,i=286,s=30,h=19,y=2*i+1,k=15,z=3,x=258,B=x+z+1,A=42,C=113,S=1,j=2,E=3,U=4;function D(t,e){return t.msg=n[e],e}function I(t){return(t<<1)-(4t.avail_out&&(a=t.avail_out),0!==a&&(u.arraySet(t.output,e.pending_buf,e.pending_out,a,t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))}function T(t,e){o._tr_flush_block(t,0<=t.block_start?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,q(t.strm)}function L(t,e){t.pending_buf[t.pending++]=e}function N(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function R(t,e){var a,n,r=t.max_chain_length,i=t.strstart,s=t.prev_length,h=t.nice_match,l=t.strstart>t.w_size-B?t.strstart-(t.w_size-B):0,o=t.window,_=t.w_mask,d=t.prev,u=t.strstart+x,f=o[i+s-1],c=o[i+s];t.prev_length>=t.good_match&&(r>>=2),h>t.lookahead&&(h=t.lookahead);do{if(o[(a=e)+s]===c&&o[a+s-1]===f&&o[a]===o[i]&&o[++a]===o[i+1]){i+=2,a++;do{}while(o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&il&&0!=--r);return s<=t.lookahead?s:t.lookahead}function H(t){var e,a,n,r,i,s,h,l,o,_,d=t.w_size;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=d+(d-B)){for(u.arraySet(t.window,t.window,d,d,0),t.match_start-=d,t.strstart-=d,t.block_start-=d,e=a=t.hash_size;n=t.head[--e],t.head[e]=d<=n?n-d:0,--a;);for(e=a=d;n=t.prev[--e],t.prev[e]=d<=n?n-d:0,--a;);r+=d}if(0===t.strm.avail_in)break;if(s=t.strm,h=t.window,l=t.strstart+t.lookahead,o=r,_=void 0,_=s.avail_in,o<_&&(_=o),a=0===_?0:(s.avail_in-=_,u.arraySet(h,s.input,s.next_in,_,l),1===s.state.wrap?s.adler=f(s.adler,h,_,l):2===s.state.wrap&&(s.adler=c(s.adler,h,_,l)),s.next_in+=_,s.total_in+=_,_),t.lookahead+=a,t.lookahead+t.insert>=z)for(i=t.strstart-t.insert,t.ins_h=t.window[i],t.ins_h=(t.ins_h<=z&&(t.ins_h=(t.ins_h<=z)if(n=o._tr_tally(t,t.strstart-t.match_start,t.match_length-z),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=z){for(t.match_length--;t.strstart++,t.ins_h=(t.ins_h<=z&&(t.ins_h=(t.ins_h<=z&&t.match_length<=t.prev_length){for(r=t.strstart+t.lookahead-z,n=o._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-z),t.lookahead-=t.prev_length-1,t.prev_length-=2;++t.strstart<=r&&(t.ins_h=(t.ins_h<t.pending_buf_size-5&&(a=t.pending_buf_size-5);;){if(t.lookahead<=1){if(H(t),0===t.lookahead&&e===_)return S;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+a;if((0===t.strstart||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,T(t,!1),0===t.strm.avail_out))return S;if(t.strstart-t.block_start>=t.w_size-B&&(T(t,!1),0===t.strm.avail_out))return S}return t.insert=0,e===d?(T(t,!0),0===t.strm.avail_out?E:U):(t.strstart>t.block_start&&(T(t,!1),t.strm.avail_out),S)}),new M(4,4,8,4,F),new M(4,5,16,8,F),new M(4,6,32,32,F),new M(4,4,16,16,K),new M(8,16,32,32,K),new M(8,16,128,128,K),new M(8,32,128,256,K),new M(32,128,258,1024,K),new M(32,258,258,4096,K)],a.deflateInit=function(t,e){return Q(t,e,v,15,8,0)},a.deflateInit2=Q,a.deflateReset=J,a.deflateResetKeep=G,a.deflateSetHeader=function(t,e){return t&&t.state?2!==t.state.wrap?g:(t.state.gzhead=e,p):g},a.deflate=function(t,e){var a,n,r,i;if(!t||!t.state||5>8&255),L(n,n.gzhead.time>>16&255),L(n,n.gzhead.time>>24&255),L(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),L(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(L(n,255&n.gzhead.extra.length),L(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=c(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(L(n,0),L(n,0),L(n,0),L(n,0),L(n,0),L(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),L(n,3),n.status=C);else{var s=v+(n.w_bits-8<<4)<<8;s|=(2<=n.strategy||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(s|=32),s+=31-s%31,n.status=C,N(n,s),0!==n.strstart&&(N(n,t.adler>>>16),N(n,65535&t.adler)),t.adler=1}if(69===n.status)if(n.gzhead.extra){for(r=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>r&&(t.adler=c(t.adler,n.pending_buf,n.pending-r,r)),q(t),r=n.pending,n.pending!==n.pending_buf_size));)L(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>r&&(t.adler=c(t.adler,n.pending_buf,n.pending-r,r)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){r=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(t.adler=c(t.adler,n.pending_buf,n.pending-r,r)),q(t),r=n.pending,n.pending===n.pending_buf_size)){i=1;break}L(n,i=n.gzindexr&&(t.adler=c(t.adler,n.pending_buf,n.pending-r,r)),0===i&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){r=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(t.adler=c(t.adler,n.pending_buf,n.pending-r,r)),q(t),r=n.pending,n.pending===n.pending_buf_size)){i=1;break}L(n,i=n.gzindexr&&(t.adler=c(t.adler,n.pending_buf,n.pending-r,r)),0===i&&(n.status=103)}else n.status=103;if(103===n.status&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&q(t),n.pending+2<=n.pending_buf_size&&(L(n,255&t.adler),L(n,t.adler>>8&255),t.adler=0,n.status=C)):n.status=C),0!==n.pending){if(q(t),0===t.avail_out)return n.last_flush=-1,p}else if(0===t.avail_in&&I(e)<=I(a)&&e!==d)return D(t,-5);if(666===n.status&&0!==t.avail_in)return D(t,-5);if(0!==t.avail_in||0!==n.lookahead||e!==_&&666!==n.status){var h=2===n.strategy?function(t,e){for(var a;;){if(0===t.lookahead&&(H(t),0===t.lookahead)){if(e===_)return S;break}if(t.match_length=0,a=o._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(T(t,!1),0===t.strm.avail_out))return S}return t.insert=0,e===d?(T(t,!0),0===t.strm.avail_out?E:U):t.last_lit&&(T(t,!1),0===t.strm.avail_out)?S:j}(n,e):3===n.strategy?function(t,e){for(var a,n,r,i,s=t.window;;){if(t.lookahead<=x){if(H(t),t.lookahead<=x&&e===_)return S;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=z&&0t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=z?(a=o._tr_tally(t,1,t.match_length-z),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=o._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(T(t,!1),0===t.strm.avail_out))return S}return t.insert=0,e===d?(T(t,!0),0===t.strm.avail_out?E:U):t.last_lit&&(T(t,!1),0===t.strm.avail_out)?S:j}(n,e):l[n.level].func(n,e);if(h!==E&&h!==U||(n.status=666),h===S||h===E)return 0===t.avail_out&&(n.last_flush=-1),p;if(h===j&&(1===e?o._tr_align(n):5!==e&&(o._tr_stored_block(n,0,0,!1),3===e&&(O(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),q(t),0===t.avail_out))return n.last_flush=-1,p}return e!==d?p:n.wrap<=0?1:(2===n.wrap?(L(n,255&t.adler),L(n,t.adler>>8&255),L(n,t.adler>>16&255),L(n,t.adler>>24&255),L(n,255&t.total_in),L(n,t.total_in>>8&255),L(n,t.total_in>>16&255),L(n,t.total_in>>24&255)):(N(n,t.adler>>>16),N(n,65535&t.adler)),q(t),0=a.w_size&&(0===i&&(O(a.head),a.strstart=0,a.block_start=0,a.insert=0),o=new u.Buf8(a.w_size),u.arraySet(o,e,_-a.w_size,a.w_size,0),e=o,_=a.w_size),s=t.avail_in,h=t.next_in,l=t.input,t.avail_in=_,t.next_in=0,t.input=e,H(a);a.lookahead>=z;){for(n=a.strstart,r=a.lookahead-(z-1);a.ins_h=(a.ins_h<>>7)]}function L(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function N(t,e,a){t.bi_valid>r-a?(t.bi_buf|=e<>r-t.bi_valid,t.bi_valid+=a-r):(t.bi_buf|=e<>>=1,a<<=1,0<--e;);return a>>>1}function F(t,e,a){var n,r,i=new Array(m+1),s=0;for(n=1;n<=m;n++)i[n]=s=s+a[n-1]<<1;for(r=0;r<=e;r++){var h=t[2*r+1];0!==h&&(t[2*r]=H(i[h]++,h))}}function K(t){var e;for(e=0;e>1;1<=a;a--)G(t,i,a);for(r=l;a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],G(t,i,1),n=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=n,i[2*r]=i[2*a]+i[2*n],t.depth[r]=(t.depth[a]>=t.depth[n]?t.depth[a]:t.depth[n])+1,i[2*a+1]=i[2*n+1]=r,t.heap[1]=r++,G(t,i,1),2<=t.heap_len;);t.heap[--t.heap_max]=t.heap[1],function(t,e){var a,n,r,i,s,h,l=e.dyn_tree,o=e.max_code,_=e.stat_desc.static_tree,d=e.stat_desc.has_stree,u=e.stat_desc.extra_bits,f=e.stat_desc.extra_base,c=e.stat_desc.max_length,p=0;for(i=0;i<=m;i++)t.bl_count[i]=0;for(l[2*t.heap[t.heap_max]+1]=0,a=t.heap_max+1;a>=7;n>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return h;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return o;for(e=32;e>>3,(i=t.static_len+3+7>>>3)<=r&&(r=i)):r=i=a+5,a+4<=r&&-1!==e?Y(t,e,a,n):4===t.strategy||i===r?(N(t,2+(n?1:0),3),J(t,A,C)):(N(t,4+(n?1:0),3),function(t,e,a,n){var r;for(N(t,e-257,5),N(t,a-1,5),N(t,n-4,4),r=0;r>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&a,t.last_lit++,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(j[a]+d+1)]++,t.dyn_dtree[2*T(e)]++),t.last_lit===t.lit_bufsize-1},a._tr_align=function(t){var e;N(t,2,3),R(t,b,A),16===(e=t).bi_valid?(L(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}},{"../utils/common":1}],8:[function(t,e,a){"use strict";e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/deflate.js":[function(t,e,a){"use strict";var s=t("./zlib/deflate"),h=t("./utils/common"),l=t("./utils/strings"),r=t("./zlib/messages"),i=t("./zlib/zstream"),o=Object.prototype.toString,_=0,d=-1,u=0,f=8;function c(t){if(!(this instanceof c))return new c(t);this.options=h.assign({level:d,method:f,chunkSize:16384,windowBits:15,memLevel:8,strategy:u,to:""},t||{});var e=this.options;e.raw&&0= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); +} +_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start + + +// convert string to array (typed, when possible) +exports.string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new utils.Buf8(buf_len); + + // convert + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper (used in 2 places) +function buf2binstring(buf, len) { + // On Chrome, the arguments in a function call that are allowed is `65534`. + // If the length of the buffer is smaller than that, we can use this optimization, + // otherwise we will take a slower path. + if (len < 65534) { + if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + + +// Convert byte array to binary string +exports.buf2binstring = function (buf) { + return buf2binstring(buf, buf.length); +}; + + +// Convert binary string (typed, when possible) +exports.binstring2buf = function (str) { + var buf = new utils.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; +}; + + +// convert array to string +exports.buf2string = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len * 2); + + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + // quick process ascii + if (c < 0x80) { utf16buf[out++] = c; continue; } + + c_len = _utf8len[c]; + // skip 5 & 6 byte codes + if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +exports.utf8border = function (buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max - 1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means buffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len[buf[pos]] > max) ? pos : max; +}; + +},{"./common":1}],3:[function(require,module,exports){ +'use strict'; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; + +},{}],4:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; + +},{}],5:[function(require,module,exports){ +'use strict'; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; + +},{}],6:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} + +module.exports = GZheader; + +},{}],7:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + +},{}],8:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var inflate_fast = require('./inffast'); +var inflate_table = require('./inftrees'); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + +function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +exports.inflateReset = inflateReset; +exports.inflateReset2 = inflateReset2; +exports.inflateResetKeep = inflateResetKeep; +exports.inflateInit = inflateInit; +exports.inflateInit2 = inflateInit2; +exports.inflate = inflate; +exports.inflateEnd = inflateEnd; +exports.inflateGetHeader = inflateGetHeader; +exports.inflateSetDictionary = inflateSetDictionary; +exports.inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + +},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + +},{"../utils/common":1}],10:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; + +},{}],11:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; + +},{}],"/lib/inflate.js":[function(require,module,exports){ +'use strict'; + + +var zlib_inflate = require('./zlib/inflate'); +var utils = require('./utils/common'); +var strings = require('./utils/strings'); +var c = require('./zlib/constants'); +var msg = require('./zlib/messages'); +var ZStream = require('./zlib/zstream'); +var GZheader = require('./zlib/gzheader'); + +var toString = Object.prototype.toString; + +/** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + +/* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overridden. + **/ + +/** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + +/** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + +/** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ +function Inflate(options) { + if (!(this instanceof Inflate)) return new Inflate(options); + + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: '' + }, options || {}); + + var opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_inflate.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + + this.header = new GZheader(); + + zlib_inflate.inflateGetHeader(this.strm, this.header); + + // Setup dictionary + if (opt.dictionary) { + // Convert data if needed + if (typeof opt.dictionary === 'string') { + opt.dictionary = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { //In raw mode we need to set the dictionary early + status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + } + } +} + +/** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Inflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status, _mode; + var next_out_utf8, tail, utf8str; + + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; + + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // Only binary strings can be decompressed on practice + strm.input = strings.binstring2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ + + if (status === c.Z_NEED_DICT && dictionary) { + status = zlib_inflate.inflateSetDictionary(this.strm, dictionary); + } + + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { + + if (this.options.to === 'string') { + + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Inflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Inflate.prototype.onEnd = function (status) { + // On success - join + if (status === c.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 aligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ +function inflate(input, options) { + var inflator = new Inflate(options); + + inflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) { throw inflator.msg || msg[inflator.err]; } + + return inflator.result; +} + + +/** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); +} + + +/** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + +exports.Inflate = Inflate; +exports.inflate = inflate; +exports.inflateRaw = inflateRaw; +exports.ungzip = inflate; + +},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js") +}); diff --git a/node_modules/pako/dist/pako_inflate.min.js b/node_modules/pako/dist/pako_inflate.min.js new file mode 100644 index 0000000000000000000000000000000000000000..a191a78a8956cddf28adaf7542631123014a04bf --- /dev/null +++ b/node_modules/pako/dist/pako_inflate.min.js @@ -0,0 +1 @@ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).pako=e()}}(function(){return function r(o,s,f){function l(t,e){if(!s[t]){if(!o[t]){var i="function"==typeof require&&require;if(!e&&i)return i(t,!0);if(d)return d(t,!0);var n=new Error("Cannot find module '"+t+"'");throw n.code="MODULE_NOT_FOUND",n}var a=s[t]={exports:{}};o[t][0].call(a.exports,function(e){return l(o[t][1][e]||e)},a,a.exports,r,o,s,f)}return s[t].exports}for(var d="function"==typeof require&&require,e=0;e>>6:(i<65536?t[r++]=224|i>>>12:(t[r++]=240|i>>>18,t[r++]=128|i>>>12&63),t[r++]=128|i>>>6&63),t[r++]=128|63&i);return t},i.buf2binstring=function(e){return d(e,e.length)},i.binstring2buf=function(e){for(var t=new f.Buf8(e.length),i=0,n=t.length;i>10&1023,s[n++]=56320|1023&a)}return d(s,n)},i.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;0<=i&&128==(192&e[i]);)i--;return i<0?t:0===i?t:i+l[e[i]]>t?i:t}},{"./common":1}],3:[function(e,t,i){"use strict";t.exports=function(e,t,i,n){for(var a=65535&e|0,r=e>>>16&65535|0,o=0;0!==i;){for(i-=o=2e3>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t,i,n){var a=s,r=n+i;e^=-1;for(var o=n;o>>8^a[255&(e^t[o])];return-1^e}},{}],6:[function(e,t,i){"use strict";t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,i){"use strict";t.exports=function(e,t){var i,n,a,r,o,s,f,l,d,c,u,h,b,m,w,k,_,g,v,p,x,y,S,E,Z;i=e.state,n=e.next_in,E=e.input,a=n+(e.avail_in-5),r=e.next_out,Z=e.output,o=r-(t-e.avail_out),s=r+(e.avail_out-257),f=i.dmax,l=i.wsize,d=i.whave,c=i.wnext,u=i.window,h=i.hold,b=i.bits,m=i.lencode,w=i.distcode,k=(1<>>=v=g>>>24,b-=v,0===(v=g>>>16&255))Z[r++]=65535&g;else{if(!(16&v)){if(0==(64&v)){g=m[(65535&g)+(h&(1<>>=v,b-=v),b<15&&(h+=E[n++]<>>=v=g>>>24,b-=v,!(16&(v=g>>>16&255))){if(0==(64&v)){g=w[(65535&g)+(h&(1<>>=v,b-=v,(v=r-o)>3,h&=(1<<(b-=p<<3))-1,e.next_in=n,e.next_out=r,e.avail_in=n>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function r(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new z.Buf16(320),this.work=new z.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function o(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=F,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new z.Buf32(n),t.distcode=t.distdyn=new z.Buf32(a),t.sane=1,t.back=-1,T):U}function s(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,o(e)):U}function f(e,t){var i,n;return e&&e.state?(n=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15=r.wsize?(z.arraySet(r.window,t,i-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(n<(a=r.wsize-r.wnext)&&(a=n),z.arraySet(r.window,t,i-n,a,r.wnext),(n-=a)?(z.arraySet(r.window,t,i-n,n,0),r.wnext=n,r.whave=r.wsize):(r.wnext+=a,r.wnext===r.wsize&&(r.wnext=0),r.whave>>8&255,i.check=N(i.check,B,2,0),d=l=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&l)<<8)+(l>>8))%31){e.msg="incorrect header check",i.mode=30;break}if(8!=(15&l)){e.msg="unknown compression method",i.mode=30;break}if(d-=4,x=8+(15&(l>>>=4)),0===i.wbits)i.wbits=x;else if(x>i.wbits){e.msg="invalid window size",i.mode=30;break}i.dmax=1<>8&1),512&i.flags&&(B[0]=255&l,B[1]=l>>>8&255,i.check=N(i.check,B,2,0)),d=l=0,i.mode=3;case 3:for(;d<32;){if(0===s)break e;s--,l+=n[r++]<>>8&255,B[2]=l>>>16&255,B[3]=l>>>24&255,i.check=N(i.check,B,4,0)),d=l=0,i.mode=4;case 4:for(;d<16;){if(0===s)break e;s--,l+=n[r++]<>8),512&i.flags&&(B[0]=255&l,B[1]=l>>>8&255,i.check=N(i.check,B,2,0)),d=l=0,i.mode=5;case 5:if(1024&i.flags){for(;d<16;){if(0===s)break e;s--,l+=n[r++]<>>8&255,i.check=N(i.check,B,2,0)),d=l=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(s<(h=i.length)&&(h=s),h&&(i.head&&(x=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),z.arraySet(i.head.extra,n,r,h,x)),512&i.flags&&(i.check=N(i.check,n,h,r)),s-=h,r+=h,i.length-=h),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===s)break e;for(h=0;x=n[r+h++],i.head&&x&&i.length<65536&&(i.head.name+=String.fromCharCode(x)),x&&h>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=12;break;case 10:for(;d<32;){if(0===s)break e;s--,l+=n[r++]<>>=7&d,d-=7&d,i.mode=27;break}for(;d<3;){if(0===s)break e;s--,l+=n[r++]<>>=1)){case 0:i.mode=14;break;case 1:if(H(i),i.mode=20,6!==t)break;l>>>=2,d-=2;break e;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=30}l>>>=2,d-=2;break;case 14:for(l>>>=7&d,d-=7&d;d<32;){if(0===s)break e;s--,l+=n[r++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=30;break}if(i.length=65535&l,d=l=0,i.mode=15,6===t)break e;case 15:i.mode=16;case 16:if(h=i.length){if(s>>=5,d-=5,i.ndist=1+(31&l),l>>>=5,d-=5,i.ncode=4+(15&l),l>>>=4,d-=4,286>>=3,d-=3}for(;i.have<19;)i.lens[A[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,S={bits:i.lenbits},y=C(0,i.lens,0,19,i.lencode,0,i.work,S),i.lenbits=S.bits,y){e.msg="invalid code lengths set",i.mode=30;break}i.have=0,i.mode=19;case 19:for(;i.have>>16&255,_=65535&Z,!((w=Z>>>24)<=d);){if(0===s)break e;s--,l+=n[r++]<>>=w,d-=w,i.lens[i.have++]=_;else{if(16===_){for(E=w+2;d>>=w,d-=w,0===i.have){e.msg="invalid bit length repeat",i.mode=30;break}x=i.lens[i.have-1],h=3+(3&l),l>>>=2,d-=2}else if(17===_){for(E=w+3;d>>=w)),l>>>=3,d-=3}else{for(E=w+7;d>>=w)),l>>>=7,d-=7}if(i.have+h>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=30;break}for(;h--;)i.lens[i.have++]=x}}if(30===i.mode)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=30;break}if(i.lenbits=9,S={bits:i.lenbits},y=C(I,i.lens,0,i.nlen,i.lencode,0,i.work,S),i.lenbits=S.bits,y){e.msg="invalid literal/lengths set",i.mode=30;break}if(i.distbits=6,i.distcode=i.distdyn,S={bits:i.distbits},y=C(D,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,S),i.distbits=S.bits,y){e.msg="invalid distances set",i.mode=30;break}if(i.mode=20,6===t)break e;case 20:i.mode=21;case 21:if(6<=s&&258<=f){e.next_out=o,e.avail_out=f,e.next_in=r,e.avail_in=s,i.hold=l,i.bits=d,O(e,u),o=e.next_out,a=e.output,f=e.avail_out,r=e.next_in,n=e.input,s=e.avail_in,l=i.hold,d=i.bits,12===i.mode&&(i.back=-1);break}for(i.back=0;k=(Z=i.lencode[l&(1<>>16&255,_=65535&Z,!((w=Z>>>24)<=d);){if(0===s)break e;s--,l+=n[r++]<>g)])>>>16&255,_=65535&Z,!(g+(w=Z>>>24)<=d);){if(0===s)break e;s--,l+=n[r++]<>>=g,d-=g,i.back+=g}if(l>>>=w,d-=w,i.back+=w,i.length=_,0===k){i.mode=26;break}if(32&k){i.back=-1,i.mode=12;break}if(64&k){e.msg="invalid literal/length code",i.mode=30;break}i.extra=15&k,i.mode=22;case 22:if(i.extra){for(E=i.extra;d>>=i.extra,d-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;k=(Z=i.distcode[l&(1<>>16&255,_=65535&Z,!((w=Z>>>24)<=d);){if(0===s)break e;s--,l+=n[r++]<>g)])>>>16&255,_=65535&Z,!(g+(w=Z>>>24)<=d);){if(0===s)break e;s--,l+=n[r++]<>>=g,d-=g,i.back+=g}if(l>>>=w,d-=w,i.back+=w,64&k){e.msg="invalid distance code",i.mode=30;break}i.offset=_,i.extra=15&k,i.mode=24;case 24:if(i.extra){for(E=i.extra;d>>=i.extra,d-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=30;break}i.mode=25;case 25:if(0===f)break e;if(h=u-f,i.offset>h){if((h=i.offset-h)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=30;break}h>i.wnext?(h-=i.wnext,b=i.wsize-h):b=i.wnext-h,h>i.length&&(h=i.length),m=i.window}else m=a,b=o-i.offset,h=i.length;for(fh?(m=O[C+o[g]],w=A[z+o[g]]):(m=96,w=0),f=1<<_-S,v=l=1<>S)+(l-=f)]=b<<24|m<<16|w|0,0!==l;);for(f=1<<_-1;B&f;)f>>=1;if(0!==f?(B&=f-1,B+=f):B=0,g++,0==--R[_]){if(_===p)break;_=t[i+o[g]]}if(x<_&&(B&c)!==d){for(0===S&&(S=x),u+=v,E=1<<(y=_-S);y+S Array + * + * Chunks of output data, if [[Deflate#onData]] not overridden. + **/ + +/** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + +/** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + + +/** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ +function Deflate(options) { + if (!(this instanceof Deflate)) return new Deflate(options); + + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: '' + }, options || {}); + + var opt = this.options; + + if (opt.raw && (opt.windowBits > 0)) { + opt.windowBits = -opt.windowBits; + } + + else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { + opt.windowBits += 16; + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_deflate.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } + + if (opt.dictionary) { + var dict; + // Convert data if needed + if (typeof opt.dictionary === 'string') { + // If we need to compress text, change encoding to utf8. + dict = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + + status = zlib_deflate.deflateSetDictionary(this.strm, dict); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + this._dict_set = true; + } +} + +/** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Deflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + + if (this.ended) { return false; } + + _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings.string2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { + if (this.options.to === 'string') { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + + // Finalize on the last chunk. + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Deflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Deflate.prototype.onEnd = function (status) { + // On success - join + if (status === Z_OK) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate algorithm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * - dictionary + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ +function deflate(input, options) { + var deflator = new Deflate(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg || msg[deflator.err]; } + + return deflator.result; +} + + +/** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); +} + + +/** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ +function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); +} + + +exports.Deflate = Deflate; +exports.deflate = deflate; +exports.deflateRaw = deflateRaw; +exports.gzip = gzip; diff --git a/node_modules/pako/lib/inflate.js b/node_modules/pako/lib/inflate.js new file mode 100644 index 0000000000000000000000000000000000000000..7535d15af147c347b1c46562f3876dd40354ba28 --- /dev/null +++ b/node_modules/pako/lib/inflate.js @@ -0,0 +1,423 @@ +'use strict'; + + +var zlib_inflate = require('./zlib/inflate'); +var utils = require('./utils/common'); +var strings = require('./utils/strings'); +var c = require('./zlib/constants'); +var msg = require('./zlib/messages'); +var ZStream = require('./zlib/zstream'); +var GZheader = require('./zlib/gzheader'); + +var toString = Object.prototype.toString; + +/** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + +/* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overridden. + **/ + +/** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + +/** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + +/** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ +function Inflate(options) { + if (!(this instanceof Inflate)) return new Inflate(options); + + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: '' + }, options || {}); + + var opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_inflate.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + + this.header = new GZheader(); + + zlib_inflate.inflateGetHeader(this.strm, this.header); + + // Setup dictionary + if (opt.dictionary) { + // Convert data if needed + if (typeof opt.dictionary === 'string') { + opt.dictionary = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { //In raw mode we need to set the dictionary early + status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + } + } +} + +/** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Inflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status, _mode; + var next_out_utf8, tail, utf8str; + + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; + + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // Only binary strings can be decompressed on practice + strm.input = strings.binstring2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ + + if (status === c.Z_NEED_DICT && dictionary) { + status = zlib_inflate.inflateSetDictionary(this.strm, dictionary); + } + + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { + + if (this.options.to === 'string') { + + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Inflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Inflate.prototype.onEnd = function (status) { + // On success - join + if (status === c.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 aligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ +function inflate(input, options) { + var inflator = new Inflate(options); + + inflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) { throw inflator.msg || msg[inflator.err]; } + + return inflator.result; +} + + +/** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); +} + + +/** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + +exports.Inflate = Inflate; +exports.inflate = inflate; +exports.inflateRaw = inflateRaw; +exports.ungzip = inflate; diff --git a/node_modules/pako/lib/utils/common.js b/node_modules/pako/lib/utils/common.js new file mode 100644 index 0000000000000000000000000000000000000000..58be4beb4af3e0153371608a3566e1a074437a7c --- /dev/null +++ b/node_modules/pako/lib/utils/common.js @@ -0,0 +1,105 @@ +'use strict'; + + +var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + +function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// reduce buffer size, avoiding mem copy +exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; + } +}; + +var fnUntyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + return [].concat.apply([], chunks); + } +}; + + +// Enable/Disable typed arrays use, for testing +// +exports.setTyped = function (on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } +}; + +exports.setTyped(TYPED_OK); diff --git a/node_modules/pako/lib/utils/strings.js b/node_modules/pako/lib/utils/strings.js new file mode 100644 index 0000000000000000000000000000000000000000..b07a732d6b18101e07eacb138dffb0761fd54d4f --- /dev/null +++ b/node_modules/pako/lib/utils/strings.js @@ -0,0 +1,187 @@ +// String encode/decode helpers +'use strict'; + + +var utils = require('./common'); + + +// Quick check if we can use fast array to bin string conversion +// +// - apply(Array) can fail on Android 2.2 +// - apply(Uint8Array) can fail on iOS 5.1 Safari +// +var STR_APPLY_OK = true; +var STR_APPLY_UIA_OK = true; + +try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; } +try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } + + +// Table with utf8 lengths (calculated by first byte of sequence) +// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, +// because max possible codepoint is 0x10ffff +var _utf8len = new utils.Buf8(256); +for (var q = 0; q < 256; q++) { + _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); +} +_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start + + +// convert string to array (typed, when possible) +exports.string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new utils.Buf8(buf_len); + + // convert + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper (used in 2 places) +function buf2binstring(buf, len) { + // On Chrome, the arguments in a function call that are allowed is `65534`. + // If the length of the buffer is smaller than that, we can use this optimization, + // otherwise we will take a slower path. + if (len < 65534) { + if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + + +// Convert byte array to binary string +exports.buf2binstring = function (buf) { + return buf2binstring(buf, buf.length); +}; + + +// Convert binary string (typed, when possible) +exports.binstring2buf = function (str) { + var buf = new utils.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; +}; + + +// convert array to string +exports.buf2string = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len * 2); + + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + // quick process ascii + if (c < 0x80) { utf16buf[out++] = c; continue; } + + c_len = _utf8len[c]; + // skip 5 & 6 byte codes + if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +exports.utf8border = function (buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max - 1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means buffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len[buf[pos]] > max) ? pos : max; +}; diff --git a/node_modules/pako/lib/zlib/README b/node_modules/pako/lib/zlib/README new file mode 100644 index 0000000000000000000000000000000000000000..88a8752470dc696bf358e9622cc164572436f688 --- /dev/null +++ b/node_modules/pako/lib/zlib/README @@ -0,0 +1,59 @@ +Content of this folder follows zlib C sources as close as possible. +That's intended to simplify maintainability and guarantee equal API +and result. + +Key differences: + +- Everything is in JavaScript. +- No platform-dependent blocks. +- Some things like crc32 rewritten to keep size small and make JIT + work better. +- Some code is different due missed features in JS (macros, pointers, + structures, header files) +- Specific API methods are not implemented (see notes in root readme) + +This port is based on zlib 1.2.8. + +This port is under zlib license (see below) with contribution and addition of javascript +port under expat license (see LICENSE at root of project) + +Copyright: +(C) 1995-2013 Jean-loup Gailly and Mark Adler +(C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + + +From zlib's README +============================================================================= + +Acknowledgments: + + The deflate format used by zlib was defined by Phil Katz. The deflate and + zlib specifications were written by L. Peter Deutsch. Thanks to all the + people who reported problems and suggested various improvements in zlib; they + are too numerous to cite here. + +Copyright notice: + + (C) 1995-2013 Jean-loup Gailly and Mark Adler + +Copyright (c) <''year''> <''copyright holders''> + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu diff --git a/node_modules/pako/lib/zlib/adler32.js b/node_modules/pako/lib/zlib/adler32.js new file mode 100644 index 0000000000000000000000000000000000000000..d440a9810d1ce6dc31bcab5e704a57ab219a1d89 --- /dev/null +++ b/node_modules/pako/lib/zlib/adler32.js @@ -0,0 +1,51 @@ +'use strict'; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; diff --git a/node_modules/pako/lib/zlib/constants.js b/node_modules/pako/lib/zlib/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..569b8724175e4025e6da6f06bd58a33a4c42a899 --- /dev/null +++ b/node_modules/pako/lib/zlib/constants.js @@ -0,0 +1,68 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; diff --git a/node_modules/pako/lib/zlib/crc32.js b/node_modules/pako/lib/zlib/crc32.js new file mode 100644 index 0000000000000000000000000000000000000000..6a96092462a293036c5b39efe2d0d849ab01c27f --- /dev/null +++ b/node_modules/pako/lib/zlib/crc32.js @@ -0,0 +1,59 @@ +'use strict'; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; diff --git a/node_modules/pako/lib/zlib/deflate.js b/node_modules/pako/lib/zlib/deflate.js new file mode 100644 index 0000000000000000000000000000000000000000..314569892c5d1e4efc2ccff1651f1a29505281a1 --- /dev/null +++ b/node_modules/pako/lib/zlib/deflate.js @@ -0,0 +1,1874 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); +var trees = require('./trees'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var msg = require('./messages'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; +} + + +exports.deflateInit = deflateInit; +exports.deflateInit2 = deflateInit2; +exports.deflateReset = deflateReset; +exports.deflateResetKeep = deflateResetKeep; +exports.deflateSetHeader = deflateSetHeader; +exports.deflate = deflate; +exports.deflateEnd = deflateEnd; +exports.deflateSetDictionary = deflateSetDictionary; +exports.deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ diff --git a/node_modules/pako/lib/zlib/gzheader.js b/node_modules/pako/lib/zlib/gzheader.js new file mode 100644 index 0000000000000000000000000000000000000000..9582cba603259edf791ebf4392aecb8eeedb3f4d --- /dev/null +++ b/node_modules/pako/lib/zlib/gzheader.js @@ -0,0 +1,58 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} + +module.exports = GZheader; diff --git a/node_modules/pako/lib/zlib/inffast.js b/node_modules/pako/lib/zlib/inffast.js new file mode 100644 index 0000000000000000000000000000000000000000..4cc958feedcfab29a5a3a5d902d19a8f736967a9 --- /dev/null +++ b/node_modules/pako/lib/zlib/inffast.js @@ -0,0 +1,345 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; diff --git a/node_modules/pako/lib/zlib/inflate.js b/node_modules/pako/lib/zlib/inflate.js new file mode 100644 index 0000000000000000000000000000000000000000..6384844845c5e818b71ecb1e4179a9c96bbd7a8c --- /dev/null +++ b/node_modules/pako/lib/zlib/inflate.js @@ -0,0 +1,1556 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var inflate_fast = require('./inffast'); +var inflate_table = require('./inftrees'); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + +function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +exports.inflateReset = inflateReset; +exports.inflateReset2 = inflateReset2; +exports.inflateResetKeep = inflateResetKeep; +exports.inflateInit = inflateInit; +exports.inflateInit2 = inflateInit2; +exports.inflate = inflate; +exports.inflateEnd = inflateEnd; +exports.inflateGetHeader = inflateGetHeader; +exports.inflateSetDictionary = inflateSetDictionary; +exports.inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ diff --git a/node_modules/pako/lib/zlib/inftrees.js b/node_modules/pako/lib/zlib/inftrees.js new file mode 100644 index 0000000000000000000000000000000000000000..ec4e4e909628877cfc7f438860d9999f99e14ebe --- /dev/null +++ b/node_modules/pako/lib/zlib/inftrees.js @@ -0,0 +1,343 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; diff --git a/node_modules/pako/lib/zlib/messages.js b/node_modules/pako/lib/zlib/messages.js new file mode 100644 index 0000000000000000000000000000000000000000..426daec6b6ec21f5fddebecfc548b5609ebc7973 --- /dev/null +++ b/node_modules/pako/lib/zlib/messages.js @@ -0,0 +1,32 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; diff --git a/node_modules/pako/lib/zlib/trees.js b/node_modules/pako/lib/zlib/trees.js new file mode 100644 index 0000000000000000000000000000000000000000..aaf15dba626651e04d56e07750c1b6f514265b14 --- /dev/null +++ b/node_modules/pako/lib/zlib/trees.js @@ -0,0 +1,1222 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +/* eslint-disable space-unary-ops */ + +var utils = require('../utils/common'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +exports._tr_init = _tr_init; +exports._tr_stored_block = _tr_stored_block; +exports._tr_flush_block = _tr_flush_block; +exports._tr_tally = _tr_tally; +exports._tr_align = _tr_align; diff --git a/node_modules/pako/lib/zlib/zstream.js b/node_modules/pako/lib/zlib/zstream.js new file mode 100644 index 0000000000000000000000000000000000000000..122acfef0f720234db175fe5b9d6a9369d310d02 --- /dev/null +++ b/node_modules/pako/lib/zlib/zstream.js @@ -0,0 +1,47 @@ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; diff --git a/node_modules/pako/package.json b/node_modules/pako/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7aaade84cf66707204ae18917d4e4fa1e4b911a7 --- /dev/null +++ b/node_modules/pako/package.json @@ -0,0 +1,44 @@ +{ + "name": "pako", + "description": "zlib port to javascript - fast, modularized, with browser support", + "version": "1.0.11", + "keywords": [ + "zlib", + "deflate", + "inflate", + "gzip" + ], + "homepage": "https://github.com/nodeca/pako", + "contributors": [ + "Andrei Tuputcyn (https://github.com/andr83)", + "Vitaly Puzrin (https://github.com/puzrin)", + "Friedel Ziegelmayer (https://github.com/dignifiedquire)", + "Kirill Efimov (https://github.com/Kirill89)", + "Jean-loup Gailly", + "Mark Adler" + ], + "files": [ + "index.js", + "dist/", + "lib/" + ], + "license": "(MIT AND Zlib)", + "repository": "nodeca/pako", + "scripts": { + "test": "make test" + }, + "devDependencies": { + "ansi": "^0.3.1", + "benchmark": "^2.1.4", + "browserify": "^16.2.3", + "buffer-from": "^1.1.1", + "eslint": "^5.9.0", + "istanbul": "^0.4.5", + "mocha": "^5.2.0", + "multiparty": "^4.1.3", + "ndoc": "^5.0.1", + "uglify-js": "=3.4.8", + "zlibjs": "^0.3.1" + }, + "dependencies": {} +} diff --git a/node_modules/parenthesis/LICENSE b/node_modules/parenthesis/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..913af54347b9edd549edb21e0ed9d9cbb0cfd039 --- /dev/null +++ b/node_modules/parenthesis/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright © 2016 Dmitry Ivanov + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/parenthesis/README.md b/node_modules/parenthesis/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5f16ce2f2728ce9bdca1d447077c32175d1f3aa5 --- /dev/null +++ b/node_modules/parenthesis/README.md @@ -0,0 +1,56 @@ +# parenthesis [![Build Status](https://travis-ci.org/dy/parenthesis.svg?branch=master)](https://travis-ci.org/dy/parenthesis) + +Parse parentheses from a string, return folded arrays. + +[![npm install parenthesis](https://nodei.co/npm/parenthesis.png?mini=true)](https://npmjs.org/package/parenthesis/) + + +```js +var parse = require('parenthesis') + +// Parse into nested format +parse('a(b[c{d}])') +// ['a(', ['b[', ['c{', ['d'], '}'], ']'], ')'] + +// Parse into flat format with cross-references +parse('a(b[c{d}])', { + brackets: ['()'], + escape: '\\', + flat: true +}) +// ['a(\\1)', 'b[c{d}]'] + + +// Stringify nested format +parse.stringify(['a(', ['b[', ['c{', ['d'], '}'], ']'], ')']) +// 'a(b[c{d}])' + +// Stringify flat format with cross-references +parse.stringify(['a(\\1)', 'b[c{d}]'], {flat: true, escape: '\\'}) +// 'a(b[c{d}])' +``` + +## API + +### tokens = paren.parse(string, brackets|opts?) + +Return array with tokens. + +Option | Default | Meaning +---|---|--- +`brackets` | `['{}', '[]', '()']` | Single brackets string or list of strings to detect brackets. Can be repeating brackets eg. `"" or ''`. +`escape` | `'___'` | Escape prefix for flat references. +`flat` | `false` | Return flat array instead of nested arrays. + +### str = paren.stringify(tokens, {flat}?) + +Stringify tokens back. Pass `{flat: true}` flag for flat tokens array. + +## Related + +* [balanced-match](http://npmjs.org/package/balanced-match) + + +## License + +© 2018 Dmitry Yv. MIT License diff --git a/node_modules/parenthesis/index.d.ts b/node_modules/parenthesis/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3aeba3d81a05dee24e5296e257ff5bd39d24551d --- /dev/null +++ b/node_modules/parenthesis/index.d.ts @@ -0,0 +1,46 @@ +declare module "parenthesis" { + namespace parens { + // One entry in the returned nested array + type Node = string | ArrayTree; + // A nested array of strings + interface ArrayTree extends Array {} + // Second-argument options used by the function + interface Opts { + // Single brackets string or list of strings to detect brackets. Can be repeating brackets eg. "" or ''. + brackets?: string | string[], + // Escape prefix for flat references. + escape?: string, + // `flat` is a boolean but since it affects return type, it's explicitly specified below + } + + // Parse parentheses from a string, return folded arrays + function parse( + str: string, + opts?: string | string[] | (parens.Opts & { flat?: false }) + ): parens.ArrayTree; + // Parse parentheses from a string, return flat array + function parse( + str: string, + opts: (parens.Opts & { flat: true }) + ): string[]; + + // Stringify tokens back. Pass {flat: true} flag for flat tokens array. + function stringify(tokens: ArrayTree, opts?: {flat: boolean}): string; + } + + // Parse parentheses from a string, return folded arrays + function parens( + str: string, + opts?: string | string[] | (parens.Opts & { flat?: false }) + ): parens.ArrayTree; + // Parse parentheses from a string, return flat array + function parens( + str: string, + opts: (parens.Opts & { flat: true }) + ): string[]; + function parens(tokens: parens.ArrayTree, opts?: {flat: boolean}): string; + + // imports via `import paren from "parenthesis", can call the export + // directly or use `paren.parse` / `paren.stringify`. + export = parens; +} diff --git a/node_modules/parenthesis/index.js b/node_modules/parenthesis/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e566418a303adbd1cabd0bee942d8096da0a310a --- /dev/null +++ b/node_modules/parenthesis/index.js @@ -0,0 +1,135 @@ +'use strict' + +/** + * @module parenthesis + */ + +function parse (str, opts) { + // pretend non-string parsed per-se + if (typeof str !== 'string') return [str] + + var res = [str] + + if (typeof opts === 'string' || Array.isArray(opts)) { + opts = {brackets: opts} + } + else if (!opts) opts = {} + + var brackets = opts.brackets ? (Array.isArray(opts.brackets) ? opts.brackets : [opts.brackets]) : ['{}', '[]', '()'] + + var escape = opts.escape || '___' + + var flat = !!opts.flat + + brackets.forEach(function (bracket) { + // create parenthesis regex + var pRE = new RegExp(['\\', bracket[0], '[^\\', bracket[0], '\\', bracket[1], ']*\\', bracket[1]].join('')) + + var ids = [] + + function replaceToken(token, idx, str){ + // save token to res + var refId = res.push(token.slice(bracket[0].length, -bracket[1].length)) - 1 + + ids.push(refId) + + return escape + refId + escape + } + + res.forEach(function (str, i) { + var prevStr + + // replace paren tokens till there’s none + var a = 0 + while (str != prevStr) { + prevStr = str + str = str.replace(pRE, replaceToken) + if (a++ > 10e3) throw Error('References have circular dependency. Please, check them.') + } + + res[i] = str + }) + + // wrap found refs to brackets + ids = ids.reverse() + res = res.map(function (str) { + ids.forEach(function (id) { + str = str.replace(new RegExp('(\\' + escape + id + '\\' + escape + ')', 'g'), bracket[0] + '$1' + bracket[1]) + }) + return str + }) + }) + + var re = new RegExp('\\' + escape + '([0-9]+)' + '\\' + escape) + + // transform references to tree + function nest (str, refs, escape) { + var res = [], match + + var a = 0 + while (match = re.exec(str)) { + if (a++ > 10e3) throw Error('Circular references in parenthesis') + + res.push(str.slice(0, match.index)) + + res.push(nest(refs[match[1]], refs)) + + str = str.slice(match.index + match[0].length) + } + + res.push(str) + + return res + } + + return flat ? res : nest(res[0], res) +} + +function stringify (arg, opts) { + if (opts && opts.flat) { + var escape = opts && opts.escape || '___' + + var str = arg[0], prevStr + + // pretend bad string stringified with no parentheses + if (!str) return '' + + + var re = new RegExp('\\' + escape + '([0-9]+)' + '\\' + escape) + + var a = 0 + while (str != prevStr) { + if (a++ > 10e3) throw Error('Circular references in ' + arg) + prevStr = str + str = str.replace(re, replaceRef) + } + + return str + } + + return arg.reduce(function f (prev, curr) { + if (Array.isArray(curr)) { + curr = curr.reduce(f, '') + } + return prev + curr + }, '') + + function replaceRef(match, idx){ + if (arg[idx] == null) throw Error('Reference ' + idx + 'is undefined') + return arg[idx] + } +} + +function parenthesis (arg, opts) { + if (Array.isArray(arg)) { + return stringify(arg, opts) + } + else { + return parse(arg, opts) + } +} + +parenthesis.parse = parse +parenthesis.stringify = stringify + +module.exports = parenthesis diff --git a/node_modules/parenthesis/package.json b/node_modules/parenthesis/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0ba2a2f12ba1b9da851249581713eb255ee0881f --- /dev/null +++ b/node_modules/parenthesis/package.json @@ -0,0 +1,46 @@ +{ + "name": "parenthesis", + "version": "3.1.8", + "description": "Parse parentheses from a string", + "main": "index.js", + "scripts": { + "test": "node test.js", + "test:browser": "budo test.js" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "repository": { + "type": "git", + "url": "git://github.com/dy/parenthesis.git" + }, + "keywords": [ + "paren", + "parenthesis", + "parse", + "brackets", + "parser", + "regexp", + "stringify", + "tokenizer", + "replace", + "csv", + "string" + ], + "author": { + "name": "Dmitry Yv", + "email": "df.creative@gmail.com", + "url": "http://github.com/dy" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/dy/parenthesis/issues" + }, + "homepage": "https://github.com/dy/parenthesis", + "devDependencies": { + "tape": "^4.9.0" + }, + "dependencies": {}, + "types": "index.d.ts" +} diff --git a/node_modules/parse-asn1/.eslintrc b/node_modules/parse-asn1/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..0bc0f455256afc0ba336f6d1d7acd44ec6180aed --- /dev/null +++ b/node_modules/parse-asn1/.eslintrc @@ -0,0 +1,34 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "camelcase": "off", + "func-style": "off", + "id-length": "off", + "max-lines-per-function": "off", + "multiline-comment-style": "off", + "no-negated-condition": "off", + "no-param-reassign": "warn", + "sort-keys": "off", + }, + + "overrides": [ + { + "files": "./asn1.js", + "rules": { + "no-underscore-dangle": "off", + } + }, + { + "files": [ + "./asn1.js", + "./certificate.js", + ], + "rules": { + "no-invalid-this": "off", + } + }, + ] +} diff --git a/node_modules/parse-asn1/.github/FUNDING.yml b/node_modules/parse-asn1/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..b14fee5d5a0c0fa889dfa0db72f19041566aa9ab --- /dev/null +++ b/node_modules/parse-asn1/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/parse-asn1 +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/parse-asn1/CHANGELOG.md b/node_modules/parse-asn1/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..89c9edbb67abe12f6d67079dffccbcc2e2a2e30e --- /dev/null +++ b/node_modules/parse-asn1/CHANGELOG.md @@ -0,0 +1,209 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v5.1.9](https://github.com/browserify/parse-asn1/compare/v5.1.8...v5.1.9) - 2025-09-24 + +### Commits + +- [meta] node 0.10 works now [`4596fae`](https://github.com/browserify/parse-asn1/commit/4596fae4ba80df5db0f335a400fc53d22b307633) +- [Deps] update `pbkdf2` [`6ef651a`](https://github.com/browserify/parse-asn1/commit/6ef651a9e6373e6e09c71330ea4a4cac4329c009) + +## [v5.1.8](https://github.com/browserify/parse-asn1/compare/v5.1.7...v5.1.8) - 2025-09-22 + +### Commits + +- [actions] split out node 10-20, and 20+ [`e186dbf`](https://github.com/browserify/parse-asn1/commit/e186dbf58216c9013b560f3f9627347985abd202) +- [meta] raise engines.node to match dep graph [`29d1def`](https://github.com/browserify/parse-asn1/commit/29d1defdaf3fc113069347a2edd284d118a73775) +- [Dev Deps] update `@ljharb/eslint-config`, `auto-changelog`, `tape` [`2648018`](https://github.com/browserify/parse-asn1/commit/264801813422e4f88ba1834e40e026cdf6bf3f30) +- [Deps] update `hash-base`, `pbkdf2` [`3ce78af`](https://github.com/browserify/parse-asn1/commit/3ce78af3720c95a71e1f264ebb20e8af63ad00bc) +- [Tests] replace `aud` with `npm audit` [`5ea1506`](https://github.com/browserify/parse-asn1/commit/5ea1506b28cb7c4f976ddb89877c0fe92d183ec9) +- [Tests] fix tests in node `4.0 - 4.4 | 5.0 - 5.9` [`4d24a07`](https://github.com/browserify/parse-asn1/commit/4d24a070402332083357da4edcacbee9d98e9dd5) +- [meta] add proper `npm version` npmrc settings [`f5d7025`](https://github.com/browserify/parse-asn1/commit/f5d702582d762e96a7deb7338a398a32224e9424) +- [Deps] remove unused `hash-base` dep [`93663af`](https://github.com/browserify/parse-asn1/commit/93663af2ba632c5a4c76847d410836ca8da3f00b) +- [Dev Deps] add missing peer dep [`f3e9076`](https://github.com/browserify/parse-asn1/commit/f3e9076f00bd43bacc283979bfb3c390e8414580) + +## [v5.1.7](https://github.com/browserify/parse-asn1/compare/v5.1.6...v5.1.7) - 2024-03-05 + +### Commits + +- [eslint] switch from standard to eslint [`794cf67`](https://github.com/browserify/parse-asn1/commit/794cf67208a69d4cc855f784a299906c6d6ef671) +- [meta] add `auto-changelog` [`8961374`](https://github.com/browserify/parse-asn1/commit/89613740568d94746d45adf8d1af029922ab9d54) +- [Tests] migrate from travis to github actions [`fdbdda5`](https://github.com/browserify/parse-asn1/commit/fdbdda5eeeaec0aeb8a740fa49deb449a47390ab) +- [meta] fix package.json indentation [`60eb8f3`](https://github.com/browserify/parse-asn1/commit/60eb8f3e2bd9e91dca0e9fd5e617864cde35cb35) +- [meta] switch from files to npmignore [`e41c881`](https://github.com/browserify/parse-asn1/commit/e41c881bf4cbf97609a82bfe4bfde4fdfcf54e39) +- [Tests] Buffer.from requires node >= 4 [`0f9ba08`](https://github.com/browserify/parse-asn1/commit/0f9ba08be2b626fc4d8d01dd96916c1dbd6a8fb7) +- [Deps] update `browserify-aes`, `evp_bytestokey`, `pbkdf2`, `safe-buffer` [`b5a64da`](https://github.com/browserify/parse-asn1/commit/b5a64da4651941980c91c04e9a4fae814c654aec) +- Only apps should have lockfiles [`75803fd`](https://github.com/browserify/parse-asn1/commit/75803fda05246c4cf5cd968c5cc87494c03d3cf0) +- [meta] add `safe-publish-latest` [`aba1931`](https://github.com/browserify/parse-asn1/commit/aba1931df788100a7ffaf6054e5b024caf3d9a23) +- [Tests] use `aud` [`2a848f6`](https://github.com/browserify/parse-asn1/commit/2a848f6c55d84896a52dcb3bcb54be637e42886d) +- [meta] add missing `engines.node` [`87e2bd3`](https://github.com/browserify/parse-asn1/commit/87e2bd3f9657ecb4fba7903a0c56305de273c3b6) +- [Dev Deps] update `tape` [`50baf1c`](https://github.com/browserify/parse-asn1/commit/50baf1c6a4af51a3d4eac1d1508cda69f6f5252a) +- [Deps] downgrade `asn1.js` to v4 since v5 drops support for node < 4 [`f230870`](https://github.com/browserify/parse-asn1/commit/f23087045497c93bd0a151e29b1e3f738e898cb8) +- [Deps] pin `hash-base` to ~3.0, due to a breaking change [`f15dc5f`](https://github.com/browserify/parse-asn1/commit/f15dc5f12898fd955ef27d037ba649724f6c5e17) + +## [v5.1.6](https://github.com/browserify/parse-asn1/compare/v5.1.5...v5.1.6) - 2020-08-11 + +### Merged + +- update asn1 [`#37`](https://github.com/browserify/parse-asn1/pull/37) +- remove 'create-hash' dependency [`#40`](https://github.com/browserify/parse-asn1/pull/40) + +### Commits + +- fix more deps [`8ebb8a3`](https://github.com/browserify/parse-asn1/commit/8ebb8a3c7aaabd25c90f64cb7304c961ba55cf1d) + +## [v5.1.5](https://github.com/browserify/parse-asn1/compare/v5.1.4...v5.1.5) - 2019-09-18 + +### Merged + +- Improving published files [`#38`](https://github.com/browserify/parse-asn1/pull/38) + +## [v5.1.4](https://github.com/browserify/parse-asn1/compare/v5.1.3...v5.1.4) - 2019-02-14 + +### Fixed + +- fixes #35, regex work for pems without linebreaks [`#35`](https://github.com/browserify/parse-asn1/issues/35) + +## [v5.1.3](https://github.com/browserify/parse-asn1/compare/v5.1.2...v5.1.3) - 2019-01-17 + +### Commits + +- rm const [`635d530`](https://github.com/browserify/parse-asn1/commit/635d530a4e29e07ac89814ef9e2a8de1f7c002ed) + +## [v5.1.2](https://github.com/browserify/parse-asn1/compare/v5.1.1...v5.1.2) - 2019-01-17 + +### Merged + +- Safe buffer [`#30`](https://github.com/browserify/parse-asn1/pull/30) +- Add curve as parameter to certificate algorithm [`#28`](https://github.com/browserify/parse-asn1/pull/28) + +### Commits + +- version is optional [`97ca375`](https://github.com/browserify/parse-asn1/commit/97ca3751f2c6b928f26fbc6558823042df7bec5d) + +## [v5.1.1](https://github.com/browserify/parse-asn1/compare/v5.1.0...v5.1.1) - 2018-04-11 + +### Merged + +- Create LICENSE [`#27`](https://github.com/browserify/parse-asn1/pull/27) +- make fixproc compliant with common newline conventions [`#22`](https://github.com/browserify/parse-asn1/pull/22) + +### Commits + +- Update README.md [`19789cd`](https://github.com/browserify/parse-asn1/commit/19789cdbd5f529351e2477fae4961d996fbc11a1) + +## [v5.1.0](https://github.com/browserify/parse-asn1/compare/v5.0.0...v5.1.0) - 2017-03-13 + +### Merged + +- add description [`#20`](https://github.com/browserify/parse-asn1/pull/20) +- Cert parsing [`#6`](https://github.com/browserify/parse-asn1/pull/6) + +### Commits + +- fix formatting [`febc75d`](https://github.com/browserify/parse-asn1/commit/febc75d6ae3e995ab28d4b1d3e5a040cdd1afb28) +- merge [`5e306be`](https://github.com/browserify/parse-asn1/commit/5e306be93671655c518569868066f53c9b298b62) +- fix style [`6131733`](https://github.com/browserify/parse-asn1/commit/6131733f2cea84ca6394e3e6bfe2040daf7eae66) +- cert parsing [`e571b18`](https://github.com/browserify/parse-asn1/commit/e571b18bf516bcd47c6a5699767ac27398a8e0df) +- update deps [`eab3500`](https://github.com/browserify/parse-asn1/commit/eab3500f62ddec3491e28c47dcfeb1e54459b747) +- iter stuff [`00b030c`](https://github.com/browserify/parse-asn1/commit/00b030c2d304ca3a003591abdd10a6e7ef2ce68d) +- credit [`c94dba3`](https://github.com/browserify/parse-asn1/commit/c94dba391223af0b72687868f88049bb0dfcb276) + +## [v5.0.0](https://github.com/browserify/parse-asn1/compare/v4.0.0...v5.0.0) - 2015-10-29 + +### Merged + +- bump asn1.js [`#17`](https://github.com/browserify/parse-asn1/pull/17) + +## [v4.0.0](https://github.com/browserify/parse-asn1/compare/v3.0.2...v4.0.0) - 2015-10-26 + +### Merged + +- bump bn [`#16`](https://github.com/browserify/parse-asn1/pull/16) + +## [v3.0.2](https://github.com/browserify/parse-asn1/compare/v3.0.1...v3.0.2) - 2015-09-28 + +### Merged + +- pull out evp [`#15`](https://github.com/browserify/parse-asn1/pull/15) +- evp: simplify overall logic [`#12`](https://github.com/browserify/parse-asn1/pull/12) + +### Fixed + +- adds .travis.yml, resolves #14 [`#14`](https://github.com/browserify/parse-asn1/issues/14) + +### Commits + +- standard [`10d65d0`](https://github.com/browserify/parse-asn1/commit/10d65d07202941a94ef914d883939d318bbbe33d) +- evp: standard-ish formatting [`be4e43d`](https://github.com/browserify/parse-asn1/commit/be4e43d8ca8a766ef77caf724e7204b3e299d601) +- evp: improve variable names [`080e62b`](https://github.com/browserify/parse-asn1/commit/080e62bdb1d3dde124ff736a7767cfaa6e4d71db) +- evp: simplify md_buf logic [`ed059dd`](https://github.com/browserify/parse-asn1/commit/ed059dd60802651722a3e7f7470bbc323b255c99) +- add badges [`ed3184d`](https://github.com/browserify/parse-asn1/commit/ed3184d7b189e32b3fec3d66de98b0676e10e11b) +- evp: remove unused ii, avoid inline expressions [`8058c1e`](https://github.com/browserify/parse-asn1/commit/8058c1ec4f39cfea4bb9fdfd81b675e063e28d1d) +- adds standard and travis targets [`e663708`](https://github.com/browserify/parse-asn1/commit/e66370856e1e20c4b3aa3089734a418b1a752d5e) +- evp: remove another semicolon [`7e1b6e5`](https://github.com/browserify/parse-asn1/commit/7e1b6e5fdb4781497262aa18939b31b2dbffbadd) +- evp: remove semicolon [`403330f`](https://github.com/browserify/parse-asn1/commit/403330fb5768c3572b2d3f45a4f003cadac541bf) +- Rename readme.md to README.md [`cf240ae`](https://github.com/browserify/parse-asn1/commit/cf240ae3283df6afd5aa5bc8e4e7922e8ce0aed2) + +## [v3.0.1](https://github.com/browserify/parse-asn1/compare/v3.0.0...v3.0.1) - 2015-05-20 + +### Merged + +- Upgrade deps [`#9`](https://github.com/browserify/parse-asn1/pull/9) +- pbkdf2 [`#5`](https://github.com/browserify/parse-asn1/pull/5) +- fixProc: simplify wrap [`#10`](https://github.com/browserify/parse-asn1/pull/10) + +### Fixed + +- switch line breaks to \r?\n instead of \n\r? fixes #7 [`#7`](https://github.com/browserify/parse-asn1/issues/7) + +### Commits + +- deal with iterations not being an integer [`c4aee9e`](https://github.com/browserify/parse-asn1/commit/c4aee9e971dac0b7cf9c125e563957cb4c5f2a05) +- update asn1.js [`92214f6`](https://github.com/browserify/parse-asn1/commit/92214f60a33f761fb97989e29f1d1588968aa621) +- update repo location [`5e7960a`](https://github.com/browserify/parse-asn1/commit/5e7960a19eab30468dbc6442bf0fce89d1d26e75) +- Add coverage directory to .npmignore. [`0d11c15`](https://github.com/browserify/parse-asn1/commit/0d11c15d7b2f1dea6243991e5bd98fe6057a80d7) +- rn .npmignore to .gitignore [`a9abb96`](https://github.com/browserify/parse-asn1/commit/a9abb96008289c241c3372151ac06a8e43a4343e) + +## [v3.0.0](https://github.com/browserify/parse-asn1/compare/v2.0.0...v3.0.0) - 2015-01-28 + +### Commits + +- add tests, remove dep [`b6ecaa2`](https://github.com/browserify/parse-asn1/commit/b6ecaa2ebca59d3ee9718fcc6515d7215a1bb89a) +- clean up [`dd84475`](https://github.com/browserify/parse-asn1/commit/dd84475f02741ebc08bed3fc02d36e6d0c1dde7e) +- make modularized [`7059346`](https://github.com/browserify/parse-asn1/commit/7059346a4b74e3b732151174c26d7eb547acba47) + +## [v2.0.0](https://github.com/browserify/parse-asn1/compare/v1.2.1...v2.0.0) - 2015-01-06 + +### Commits + +- Update asn1.js and bn.js to 1.0 [`9ab8411`](https://github.com/browserify/parse-asn1/commit/9ab8411d7fb489f9d5cde08efdd9ec041a11c99c) + +## [v1.2.1](https://github.com/browserify/parse-asn1/compare/v1.2.0...v1.2.1) - 2015-01-04 + +### Merged + +- Update asn1.js [`#1`](https://github.com/browserify/parse-asn1/pull/1) + +## [v1.2.0](https://github.com/browserify/parse-asn1/compare/v1.1.0...v1.2.0) - 2014-12-18 + +### Commits + +- varient version of passwords [`e1eef0b`](https://github.com/browserify/parse-asn1/commit/e1eef0b1d5534e7f0f08caf4242e0dda274882d5) + +## [v1.1.0](https://github.com/browserify/parse-asn1/compare/v1.0.1...v1.1.0) - 2014-12-18 + +### Commits + +- updates for dsa [`f1e82d2`](https://github.com/browserify/parse-asn1/commit/f1e82d2b61723ea17b8cd86eef5cbed3b0e4658c) + +## v1.0.1 - 2014-12-16 + +### Commits + +- first [`6cfeecb`](https://github.com/browserify/parse-asn1/commit/6cfeecb4cd46c8032833e76360386f9c64d88c19) +- handle strings [`df96666`](https://github.com/browserify/parse-asn1/commit/df9666656c6edf341a2e99549b197334c5fa2fc9) diff --git a/node_modules/parse-asn1/LICENSE b/node_modules/parse-asn1/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e0efcf251d049d2c98160af0e8989260c14cc89f --- /dev/null +++ b/node_modules/parse-asn1/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2017, crypto-browserify contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/parse-asn1/README.md b/node_modules/parse-asn1/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9cd4c153e698db696ac63eb92667994ac1e1579a --- /dev/null +++ b/node_modules/parse-asn1/README.md @@ -0,0 +1,8 @@ +# parse-asn1 + +[![TRAVIS](https://secure.travis-ci.org/crypto-browserify/parse-asn1.png)](http://travis-ci.org/crypto-browserify/parse-asn1) +[![NPM](http://img.shields.io/npm/v/parse-asn1.svg)](https://www.npmjs.org/package/parse-asn1) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +utility library for parsing asn1 files for use with browserify-sign. diff --git a/node_modules/parse-asn1/aesid.json b/node_modules/parse-asn1/aesid.json new file mode 100644 index 0000000000000000000000000000000000000000..24f653b40f2a29d64ec52a71ffaf1b0a682c1513 --- /dev/null +++ b/node_modules/parse-asn1/aesid.json @@ -0,0 +1,13 @@ +{"2.16.840.1.101.3.4.1.1": "aes-128-ecb", +"2.16.840.1.101.3.4.1.2": "aes-128-cbc", +"2.16.840.1.101.3.4.1.3": "aes-128-ofb", +"2.16.840.1.101.3.4.1.4": "aes-128-cfb", +"2.16.840.1.101.3.4.1.21": "aes-192-ecb", +"2.16.840.1.101.3.4.1.22": "aes-192-cbc", +"2.16.840.1.101.3.4.1.23": "aes-192-ofb", +"2.16.840.1.101.3.4.1.24": "aes-192-cfb", +"2.16.840.1.101.3.4.1.41": "aes-256-ecb", +"2.16.840.1.101.3.4.1.42": "aes-256-cbc", +"2.16.840.1.101.3.4.1.43": "aes-256-ofb", +"2.16.840.1.101.3.4.1.44": "aes-256-cfb" +} \ No newline at end of file diff --git a/node_modules/parse-asn1/asn1.js b/node_modules/parse-asn1/asn1.js new file mode 100644 index 0000000000000000000000000000000000000000..9b20c9460146498a880e219f0f5372256f5e952f --- /dev/null +++ b/node_modules/parse-asn1/asn1.js @@ -0,0 +1,123 @@ +// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js +// Fedor, you are amazing. + +'use strict'; + +var asn1 = require('asn1.js'); + +exports.certificate = require('./certificate'); + +var RSAPrivateKey = asn1.define('RSAPrivateKey', function () { + this.seq().obj( + this.key('version')['int'](), + this.key('modulus')['int'](), + this.key('publicExponent')['int'](), + this.key('privateExponent')['int'](), + this.key('prime1')['int'](), + this.key('prime2')['int'](), + this.key('exponent1')['int'](), + this.key('exponent2')['int'](), + this.key('coefficient')['int']() + ); +}); +exports.RSAPrivateKey = RSAPrivateKey; + +var RSAPublicKey = asn1.define('RSAPublicKey', function () { + this.seq().obj( + this.key('modulus')['int'](), + this.key('publicExponent')['int']() + ); +}); +exports.RSAPublicKey = RSAPublicKey; + +var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () { + this.seq().obj( + this.key('algorithm').objid(), + this.key('none').null_().optional(), + this.key('curve').objid().optional(), + this.key('params').seq().obj( + this.key('p')['int'](), + this.key('q')['int'](), + this.key('g')['int']() + ).optional() + ); +}); + +var PublicKey = asn1.define('SubjectPublicKeyInfo', function () { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ); +}); +exports.PublicKey = PublicKey; + +var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () { + this.seq().obj( + this.key('version')['int'](), + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPrivateKey').octstr() + ); +}); +exports.PrivateKey = PrivateKeyInfo; +var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () { + this.seq().obj( + this.key('algorithm').seq().obj( + this.key('id').objid(), + this.key('decrypt').seq().obj( + this.key('kde').seq().obj( + this.key('id').objid(), + this.key('kdeparams').seq().obj( + this.key('salt').octstr(), + this.key('iters')['int']() + ) + ), + this.key('cipher').seq().obj( + this.key('algo').objid(), + this.key('iv').octstr() + ) + ) + ), + this.key('subjectPrivateKey').octstr() + ); +}); + +exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo; + +var DSAPrivateKey = asn1.define('DSAPrivateKey', function () { + this.seq().obj( + this.key('version')['int'](), + this.key('p')['int'](), + this.key('q')['int'](), + this.key('g')['int'](), + this.key('pub_key')['int'](), + this.key('priv_key')['int']() + ); +}); +exports.DSAPrivateKey = DSAPrivateKey; + +exports.DSAparam = asn1.define('DSAparam', function () { + this['int'](); +}); + +var ECParameters = asn1.define('ECParameters', function () { + this.choice({ + namedCurve: this.objid() + }); +}); + +var ECPrivateKey = asn1.define('ECPrivateKey', function () { + this.seq().obj( + this.key('version')['int'](), + this.key('privateKey').octstr(), + this.key('parameters').optional().explicit(0).use(ECParameters), + this.key('publicKey').optional().explicit(1).bitstr() + ); +}); +exports.ECPrivateKey = ECPrivateKey; + +exports.signature = asn1.define('signature', function () { + this.seq().obj( + this.key('r')['int'](), + this.key('s')['int']() + ); +}); diff --git a/node_modules/parse-asn1/certificate.js b/node_modules/parse-asn1/certificate.js new file mode 100644 index 0000000000000000000000000000000000000000..3529c72a142ce250af2ab6ede4b7dafbcf3531e4 --- /dev/null +++ b/node_modules/parse-asn1/certificate.js @@ -0,0 +1,89 @@ +// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js +// thanks to @Rantanen + +'use strict'; + +var asn = require('asn1.js'); + +var Time = asn.define('Time', function () { + this.choice({ + utcTime: this.utctime(), + generalTime: this.gentime() + }); +}); + +var AttributeTypeValue = asn.define('AttributeTypeValue', function () { + this.seq().obj( + this.key('type').objid(), + this.key('value').any() + ); +}); + +var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () { + this.seq().obj( + this.key('algorithm').objid(), + this.key('parameters').optional(), + this.key('curve').objid().optional() + ); +}); + +var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ); +}); + +var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () { + this.setof(AttributeTypeValue); +}); + +var RDNSequence = asn.define('RDNSequence', function () { + this.seqof(RelativeDistinguishedName); +}); + +var Name = asn.define('Name', function () { + this.choice({ + rdnSequence: this.use(RDNSequence) + }); +}); + +var Validity = asn.define('Validity', function () { + this.seq().obj( + this.key('notBefore').use(Time), + this.key('notAfter').use(Time) + ); +}); + +var Extension = asn.define('Extension', function () { + this.seq().obj( + this.key('extnID').objid(), + this.key('critical').bool().def(false), + this.key('extnValue').octstr() + ); +}); + +var TBSCertificate = asn.define('TBSCertificate', function () { + this.seq().obj( + this.key('version').explicit(0)['int']().optional(), + this.key('serialNumber')['int'](), + this.key('signature').use(AlgorithmIdentifier), + this.key('issuer').use(Name), + this.key('validity').use(Validity), + this.key('subject').use(Name), + this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), + this.key('issuerUniqueID').implicit(1).bitstr().optional(), + this.key('subjectUniqueID').implicit(2).bitstr().optional(), + this.key('extensions').explicit(3).seqof(Extension).optional() + ); +}); + +var X509Certificate = asn.define('X509Certificate', function () { + this.seq().obj( + this.key('tbsCertificate').use(TBSCertificate), + this.key('signatureAlgorithm').use(AlgorithmIdentifier), + this.key('signatureValue').bitstr() + ); +}); + +module.exports = X509Certificate; diff --git a/node_modules/parse-asn1/fixProc.js b/node_modules/parse-asn1/fixProc.js new file mode 100644 index 0000000000000000000000000000000000000000..0e3d234ccfcb74de7407b66f869de9a56106ef94 --- /dev/null +++ b/node_modules/parse-asn1/fixProc.js @@ -0,0 +1,33 @@ +'use strict'; + +// adapted from https://github.com/apatil/pemstrip +var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m; +var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m; +var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m; +var evp = require('evp_bytestokey'); +var ciphers = require('browserify-aes'); +var Buffer = require('safe-buffer').Buffer; +module.exports = function (okey, password) { + var key = okey.toString(); + var match = key.match(findProc); + var decrypted; + if (!match) { + var match2 = key.match(fullRegex); + decrypted = Buffer.from(match2[2].replace(/[\r\n]/g, ''), 'base64'); + } else { + var suite = 'aes' + match[1]; + var iv = Buffer.from(match[2], 'hex'); + var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64'); + var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key; + var out = []; + var cipher = ciphers.createDecipheriv(suite, cipherKey, iv); + out.push(cipher.update(cipherText)); + out.push(cipher['final']()); + decrypted = Buffer.concat(out); + } + var tag = key.match(startRegex)[1]; + return { + tag: tag, + data: decrypted + }; +}; diff --git a/node_modules/parse-asn1/index.js b/node_modules/parse-asn1/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ad8607745166e9f6161ea943f71a93a4c3181ddc --- /dev/null +++ b/node_modules/parse-asn1/index.js @@ -0,0 +1,111 @@ +'use strict'; + +var asn1 = require('./asn1'); +var aesid = require('./aesid.json'); +var fixProc = require('./fixProc'); +var ciphers = require('browserify-aes'); +var pbkdf2Sync = require('pbkdf2').pbkdf2Sync; +var Buffer = require('safe-buffer').Buffer; + +function decrypt(data, password) { + var salt = data.algorithm.decrypt.kde.kdeparams.salt; + var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10); + var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]; + var iv = data.algorithm.decrypt.cipher.iv; + var cipherText = data.subjectPrivateKey; + var keylen = parseInt(algo.split('-')[1], 10) / 8; + var key = pbkdf2Sync(password, salt, iters, keylen, 'sha1'); + var cipher = ciphers.createDecipheriv(algo, key, iv); + var out = []; + out.push(cipher.update(cipherText)); + out.push(cipher['final']()); + return Buffer.concat(out); +} + +function parseKeys(buffer) { + var password; + if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) { + password = buffer.passphrase; + buffer = buffer.key; + } + if (typeof buffer === 'string') { + buffer = Buffer.from(buffer); + } + + var stripped = fixProc(buffer, password); + + var type = stripped.tag; + var data = stripped.data; + var subtype, ndata; + switch (type) { + case 'CERTIFICATE': + ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo; + // falls through + case 'PUBLIC KEY': + if (!ndata) { + ndata = asn1.PublicKey.decode(data, 'der'); + } + subtype = ndata.algorithm.algorithm.join('.'); + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der'); + case '1.2.840.10045.2.1': + ndata.subjectPrivateKey = ndata.subjectPublicKey; + return { + type: 'ec', + data: ndata + }; + case '1.2.840.10040.4.1': + ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der'); + return { + type: 'dsa', + data: ndata.algorithm.params + }; + default: throw new Error('unknown key id ' + subtype); + } + // throw new Error('unknown key type ' + type) + case 'ENCRYPTED PRIVATE KEY': + data = asn1.EncryptedPrivateKey.decode(data, 'der'); + data = decrypt(data, password); + // falls through + case 'PRIVATE KEY': + ndata = asn1.PrivateKey.decode(data, 'der'); + subtype = ndata.algorithm.algorithm.join('.'); + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der'); + case '1.2.840.10045.2.1': + return { + curve: ndata.algorithm.curve, + privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey + }; + case '1.2.840.10040.4.1': + ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der'); + return { + type: 'dsa', + params: ndata.algorithm.params + }; + default: throw new Error('unknown key id ' + subtype); + } + // throw new Error('unknown key type ' + type) + case 'RSA PUBLIC KEY': + return asn1.RSAPublicKey.decode(data, 'der'); + case 'RSA PRIVATE KEY': + return asn1.RSAPrivateKey.decode(data, 'der'); + case 'DSA PRIVATE KEY': + return { + type: 'dsa', + params: asn1.DSAPrivateKey.decode(data, 'der') + }; + case 'EC PRIVATE KEY': + data = asn1.ECPrivateKey.decode(data, 'der'); + return { + curve: data.parameters.value, + privateKey: data.privateKey + }; + default: throw new Error('unknown key type ' + type); + } +} +parseKeys.signature = asn1.signature; + +module.exports = parseKeys; diff --git a/node_modules/parse-asn1/package.json b/node_modules/parse-asn1/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ca0b42af6cc594fb2e43dd5cd72e4a1db905908f --- /dev/null +++ b/node_modules/parse-asn1/package.json @@ -0,0 +1,58 @@ +{ + "name": "parse-asn1", + "version": "5.1.9", + "description": "utility library for parsing asn1 files for use with browserify-sign.", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "lint": "eslint --ext=js,mjs .", + "tests-only": "tape 'test/**/*.js'", + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "npx npm@\">= 10.2\" audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/crypto-browserify/parse-asn1.git" + }, + "author": "", + "license": "ISC", + "dependencies": { + "asn1.js": "^4.10.1", + "browserify-aes": "^1.2.0", + "evp_bytestokey": "^1.0.3", + "pbkdf2": "^3.1.5", + "safe-buffer": "^5.2.1" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.2.0", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0" + }, + "engines": { + "node": ">= 0.10" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test" + ] + } +} diff --git a/node_modules/parse-rect/.eslintrc.json b/node_modules/parse-rect/.eslintrc.json new file mode 100644 index 0000000000000000000000000000000000000000..1e5e08b37332379d194a6a5e8fd259d8de4f7fc9 --- /dev/null +++ b/node_modules/parse-rect/.eslintrc.json @@ -0,0 +1,44 @@ +{ + "env": { + "browser": true, + "node": true, + "commonjs": true, + "es6": true + }, + "extends": "eslint:recommended", + "rules": { + "strict": 2, + "indent": 0, + "linebreak-style": 0, + "quotes": 0, + "semi": 0, + "no-cond-assign": 1, + "no-constant-condition": 1, + "no-duplicate-case": 1, + "no-empty": 1, + "no-ex-assign": 1, + "no-extra-boolean-cast": 1, + "no-extra-semi": 1, + "no-fallthrough": 1, + "no-func-assign": 1, + "no-global-assign": 1, + "no-implicit-globals": 2, + "no-inner-declarations": ["error", "functions"], + "no-irregular-whitespace": 2, + "no-loop-func": 1, + "no-magic-numbers": ["warn", { "ignore": [1, 0, -1], "ignoreArrayIndexes": true}], + "no-multi-str": 1, + "no-mixed-spaces-and-tabs": 1, + "no-proto": 1, + "no-sequences": 1, + "no-throw-literal": 1, + "no-unmodified-loop-condition": 1, + "no-useless-call": 1, + "no-void": 1, + "no-with": 2, + "wrap-iife": 1, + "no-redeclare": 1, + "no-unused-vars": ["error", { "vars": "all", "args": "none" }], + "no-sparse-arrays": 1 + } +} diff --git a/node_modules/parse-rect/.travis.yml b/node_modules/parse-rect/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..2ea53652d5e2375bdb9bde81676ee2031963188a --- /dev/null +++ b/node_modules/parse-rect/.travis.yml @@ -0,0 +1,5 @@ +sudo: false +language: node_js +node_js: + - 'node' + - '6' diff --git a/node_modules/parse-rect/index.js b/node_modules/parse-rect/index.js new file mode 100644 index 0000000000000000000000000000000000000000..84a88176cbc522b3451c95368e97b40d8d0f2fda --- /dev/null +++ b/node_modules/parse-rect/index.js @@ -0,0 +1,85 @@ +'use strict' + +var pick = require('pick-by-alias') + +module.exports = parseRect + +function parseRect (arg) { + var rect + + // direct arguments sequence + if (arguments.length > 1) { + arg = arguments + } + + // svg viewbox + if (typeof arg === 'string') { + arg = arg.split(/\s/).map(parseFloat) + } + else if (typeof arg === 'number') { + arg = [arg] + } + + // 0, 0, 100, 100 - array-like + if (arg.length && typeof arg[0] === 'number') { + // [w, w] + if (arg.length === 1) { + rect = { + width: arg[0], + height: arg[0], + x: 0, y: 0 + } + } + // [w, h] + else if (arg.length === 2) { + rect = { + width: arg[0], + height: arg[1], + x: 0, y: 0 + } + } + // [l, t, r, b] + else { + rect = { + x: arg[0], + y: arg[1], + width: (arg[2] - arg[0]) || 0, + height: (arg[3] - arg[1]) || 0 + } + } + } + // {x, y, w, h} or {l, t, b, r} + else if (arg) { + arg = pick(arg, { + left: 'x l left Left', + top: 'y t top Top', + width: 'w width W Width', + height: 'h height W Width', + bottom: 'b bottom Bottom', + right: 'r right Right' + }) + + rect = { + x: arg.left || 0, + y: arg.top || 0 + } + + if (arg.width == null) { + if (arg.right) rect.width = arg.right - rect.x + else rect.width = 0 + } + else { + rect.width = arg.width + } + + if (arg.height == null) { + if (arg.bottom) rect.height = arg.bottom - rect.y + else rect.height = 0 + } + else { + rect.height = arg.height + } + } + + return rect +} diff --git a/node_modules/parse-rect/license b/node_modules/parse-rect/license new file mode 100644 index 0000000000000000000000000000000000000000..fb2315440d1b16cfeb3eb2d46152c8bd110280c2 --- /dev/null +++ b/node_modules/parse-rect/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Dmitry Ivanov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/parse-rect/package.json b/node_modules/parse-rect/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e31ab74592c0555c9a9aa82538e619e381c34aa9 --- /dev/null +++ b/node_modules/parse-rect/package.json @@ -0,0 +1,24 @@ +{ + "name": "parse-rect", + "version": "1.2.0", + "description": "Parse any input rectangle format", + "main": "index.js", + "dependencies": { + "pick-by-alias": "^1.2.0" + }, + "devDependencies": {}, + "scripts": { + "test": "node test" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/dfcreative/parse-rect.git" + }, + "keywords": [ + "rect", + "rectangle", + "parse" + ], + "author": "Dmitry Yv ", + "license": "MIT" +} diff --git a/node_modules/parse-rect/readme.md b/node_modules/parse-rect/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..6a7fc5f9a3afdf8d34fc53ef706137ee5691d08b --- /dev/null +++ b/node_modules/parse-rect/readme.md @@ -0,0 +1,30 @@ +# parse-rect [![experimental](https://img.shields.io/badge/stability-unstable-green.svg)](http://github.com/badges/stability-badges) [![Build Status](https://travis-ci.org/dfcreative/parse-rect.png)](https://travis-ci.org/dfcreative/parse-rect) + +Take any rectangle-like argument and return rectangle values. + +[![npm install parse-rect](https://nodei.co/npm/parse-rect.png?mini=true)](https://npmjs.org/package/parse-rect/) + +```js +const parseRect = require('parse-rect') + +// {x: 10, y: 20, width: 90, height: 80} +parseRect('10 20 100 100') +parseRect(10, 20, 100, 100) +parseRect([10, 20, 100, 100]) +parseRect({ x: 10, y: 20, width: 90, height: 80 }) +parseRect({ x: 10, y: 20, w: 90, h: 80 }) +parseRect({ l: 10, t: 20, r: 100, b: 100 }) +parseRect({ left: 10, top: 20, right: 100, bottom: 100 }) + +// {x: 0, y: 0, width: 90, height: 80} +parseRect({ width: 90, height: 80 }) +parseRect([ 90, 80 ]) + +// {x: 0, y: 0, width: 90, height: 90} +parseRect(90) +parseRect([90]) +``` + +## License + +(c) 2018 Dmitry Yv. MIT License diff --git a/node_modules/parse-rect/test.js b/node_modules/parse-rect/test.js new file mode 100644 index 0000000000000000000000000000000000000000..3f389c07b1ebedf64837fd021be7a15a47b9306d --- /dev/null +++ b/node_modules/parse-rect/test.js @@ -0,0 +1,20 @@ +'use strict' + +const parseRect = require('./') +const assert = require('assert') + +var res = {x: 10, y: 20, width: 90, height: 80} +assert.deepEqual(parseRect('10 20 100 100'), res) +assert.deepEqual(parseRect(10, 20, 100, 100), res) +assert.deepEqual(parseRect([10, 20, 100, 100]), res) +assert.deepEqual(parseRect({ x: 10, y: 20, width: 90, height: 80 }), res) +assert.deepEqual(parseRect({ x: 10, y: 20, w: 90, h: 80 }), res) +assert.deepEqual(parseRect({ l: 10, t: 20, r: 100, b: 100 }), res) +assert.deepEqual(parseRect({ left: 10, top: 20, right: 100, bottom: 100 }), res) + +var res = {x: 0, y: 0, width: 90, height: 80} +assert.deepEqual(parseRect({ width: 90, height: 80 }), res) + +assert.deepEqual(parseRect([10, 20]), {width: 10, height: 20, x: 0, y: 0}) +assert.deepEqual(parseRect(10), {width: 10, height: 10, x: 0, y: 0}) +assert.deepEqual(parseRect([10]), {width: 10, height: 10, x: 0, y: 0}) diff --git a/node_modules/parse-svg-path/License b/node_modules/parse-svg-path/License new file mode 100644 index 0000000000000000000000000000000000000000..c9b77ebb4de12e2451ac7c67b43cf1ddceaf7739 --- /dev/null +++ b/node_modules/parse-svg-path/License @@ -0,0 +1,23 @@ + +The MIT License + +Copyright (c) 2013 Jake Rosoman + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/parse-svg-path/Readme.md b/node_modules/parse-svg-path/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..49801535bc223e82499d2754ba33bb3d883b9be3 --- /dev/null +++ b/node_modules/parse-svg-path/Readme.md @@ -0,0 +1,32 @@ + +# parse-svg-path + + A minimal svg path parser. For the delux model see [hughsk/svg-path-parser](//github.com/hughsk/svg-path-parser) or for the streaming model see [nfroidure/SVGPathData](//github.com/nfroidure/SVGPathData). + +## Installation + +- [packin](//github.com/jkroso/packin): `packin add jkroso/parse-svg-path` +- [component](//github.com/component/component#installing-packages): `component install jkroso/parse-svg-path` +- [npm](//npmjs.org/doc/cli/npm-install.html): `npm install parse-svg-path` + +then in your app: + +```js +var parse = require('parse-svg-path') +``` + +## API + +### parse(string) + + parse an svg path data string. Generates an Array + of commands where each command is an Array of the + form `[command, arg1, arg2, ...]` + +```js +parse('m1 2 3 4') // => [['m',1,2],['l',3,4]] +``` + +## Running the tests + +Just run `make` and navigate your browser to the test directory. diff --git a/node_modules/parse-svg-path/index.js b/node_modules/parse-svg-path/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6ba39ebbb1ab3ae0236643e69c7dbdb12661547f --- /dev/null +++ b/node_modules/parse-svg-path/index.js @@ -0,0 +1,57 @@ + +module.exports = parse + +/** + * expected argument lengths + * @type {Object} + */ + +var length = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0} + +/** + * segment pattern + * @type {RegExp} + */ + +var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig + +/** + * parse an svg path data string. Generates an Array + * of commands where each command is an Array of the + * form `[command, arg1, arg2, ...]` + * + * @param {String} path + * @return {Array} + */ + +function parse(path) { + var data = [] + path.replace(segment, function(_, command, args){ + var type = command.toLowerCase() + args = parseValues(args) + + // overloaded moveTo + if (type == 'm' && args.length > 2) { + data.push([command].concat(args.splice(0, 2))) + type = 'l' + command = command == 'm' ? 'l' : 'L' + } + + while (true) { + if (args.length == length[type]) { + args.unshift(command) + return data.push(args) + } + if (args.length < length[type]) throw new Error('malformed path data') + data.push([command].concat(args.splice(0, length[type]))) + } + }) + return data +} + +var number = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig + +function parseValues(args) { + var numbers = args.match(number) + return numbers ? numbers.map(Number) : [] +} diff --git a/node_modules/parse-svg-path/package.json b/node_modules/parse-svg-path/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b457a517c61343e70b51824faf4ec7ae88321600 --- /dev/null +++ b/node_modules/parse-svg-path/package.json @@ -0,0 +1,17 @@ +{ + "name": "parse-svg-path", + "version": "0.1.2", + "description": "svg path parser", + "keywords": ["svg","path","parse","parser"], + "dependencies": {}, + "devDependencies": { + "serve": "jkroso/serve#1.5.1", + "mocha": "*", + "chai": "*" + }, + "repository": "git://github.com/jkroso/parse-svg-path.git", + "bugs": "https://github.com/jkroso/parse-svg-path/issues", + "author": "Jake Rosoman", + "files": ["index.js"], + "license": "MIT" +} diff --git a/node_modules/parse-unit/.npmignore b/node_modules/parse-unit/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..bd11a0be2a1b9c72cfe67f1fa1b393aed0923fc3 --- /dev/null +++ b/node_modules/parse-unit/.npmignore @@ -0,0 +1,8 @@ +bower_components +node_modules +*.log +.DS_Store +bundle.js +test +test.js +demo/ \ No newline at end of file diff --git a/node_modules/parse-unit/LICENSE.md b/node_modules/parse-unit/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..927a999b6ee41b2e53992f0eecdd5ee939cf7038 --- /dev/null +++ b/node_modules/parse-unit/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) +Copyright (c) 2014 Matt DesLauriers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/parse-unit/README.md b/node_modules/parse-unit/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e44bae40bc7cb64df5e3c128015e0e7fb1524a08 --- /dev/null +++ b/node_modules/parse-unit/README.md @@ -0,0 +1,33 @@ +# parse-unit + +[![stable](http://badges.github.io/stability-badges/dist/stable.svg)](http://github.com/badges/stability-badges) + +Parses a number and unit string, eg `"20px"` into `[20, "px"]`. + +```js +var unit = require('parse-unit') + +//prints [50, "gold"] +console.log( unit("50 gold") ) +``` + +## Usage + +[![NPM](https://nodei.co/npm/parse-unit.png)](https://nodei.co/npm/parse-unit/) + +#### `parse(str[, out])` + +Parses the string and its unit, returning an array containing the number and unit, separated. + +``` +"-20 foo" => [-20, "foo"] +"5.5%" => [5.5, "%"] +5 => [5, ""] +"5" => [5, ""] +``` + +This will create a new array unless you specify an array to `out`, which allows you to re-use arrays. + +## License + +MIT, see [LICENSE.md](http://github.com/mattdesl/parse-unit/blob/master/LICENSE.md) for details. diff --git a/node_modules/parse-unit/index.js b/node_modules/parse-unit/index.js new file mode 100644 index 0000000000000000000000000000000000000000..921f68bb25e382c6ddbfbd796291073cc34e479a --- /dev/null +++ b/node_modules/parse-unit/index.js @@ -0,0 +1,10 @@ +module.exports = function parseUnit(str, out) { + if (!out) + out = [ 0, '' ] + + str = String(str) + var num = parseFloat(str, 10) + out[0] = num + out[1] = str.match(/[\d.\-\+]*\s*(.*)/)[1] || '' + return out +} \ No newline at end of file diff --git a/node_modules/parse-unit/package.json b/node_modules/parse-unit/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4562bbb91e4d3ef44d621abe2b2e10cfc96e53ae --- /dev/null +++ b/node_modules/parse-unit/package.json @@ -0,0 +1,42 @@ +{ + "name": "parse-unit", + "version": "1.0.1", + "description": "parses number and unit, '20px' into [20, 'px']", + "main": "index.js", + "license": "MIT", + "author": "Matt DesLauriers ", + "dependencies": {}, + "devDependencies": { + "tape": "~2.13.2" + }, + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/mattdesl/parse-unit.git" + }, + "keywords": [ + "parse", + "number", + "string", + "str", + "split", + "unit", + "in", + "m", + "px", + "%", + "pt", + "pc", + "em", + "deg", + "rad", + "css", + "value" + ], + "homepage": "https://github.com/mattdesl/parse-unit", + "bugs": { + "url": "https://github.com/mattdesl/parse-unit/issues" + } +} diff --git a/node_modules/parseurl/HISTORY.md b/node_modules/parseurl/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..8e409541d855de232cc24d29524282441d11cbc7 --- /dev/null +++ b/node_modules/parseurl/HISTORY.md @@ -0,0 +1,58 @@ +1.3.3 / 2019-04-15 +================== + + * Fix Node.js 0.8 return value inconsistencies + +1.3.2 / 2017-09-09 +================== + + * perf: reduce overhead for full URLs + * perf: unroll the "fast-path" `RegExp` + +1.3.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.3.0 / 2014-08-09 +================== + + * Add `parseurl.original` for parsing `req.originalUrl` with fallback + * Return `undefined` if `req.url` is `undefined` + +1.2.0 / 2014-07-21 +================== + + * Cache URLs based on original value + * Remove no-longer-needed URL mis-parse work-around + * Simplify the "fast-path" `RegExp` + +1.1.3 / 2014-07-08 +================== + + * Fix typo + +1.1.2 / 2014-07-08 +================== + + * Seriously fix Node.js 0.8 compatibility + +1.1.1 / 2014-07-08 +================== + + * Fix Node.js 0.8 compatibility + +1.1.0 / 2014-07-08 +================== + + * Incorporate URL href-only parse fast-path + +1.0.1 / 2014-03-08 +================== + + * Add missing `require` + +1.0.0 / 2014-03-08 +================== + + * Genesis from `connect` diff --git a/node_modules/parseurl/LICENSE b/node_modules/parseurl/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..27653d3db7e584321691af8f1bc30d49fe105d3e --- /dev/null +++ b/node_modules/parseurl/LICENSE @@ -0,0 +1,24 @@ + +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/parseurl/README.md b/node_modules/parseurl/README.md new file mode 100644 index 0000000000000000000000000000000000000000..443e716b85dc54a70d063109d4e9afa39022989d --- /dev/null +++ b/node_modules/parseurl/README.md @@ -0,0 +1,133 @@ +# parseurl + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Parse a URL with memoization. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install parseurl +``` + +## API + +```js +var parseurl = require('parseurl') +``` + +### parseurl(req) + +Parse the URL of the given request object (looks at the `req.url` property) +and return the result. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.url` does +not change will return a cached parsed object, rather than parsing again. + +### parseurl.original(req) + +Parse the original URL of the given request object and return the result. +This works by trying to parse `req.originalUrl` if it is a string, otherwise +parses `req.url`. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.originalUrl` +does not change will return a cached parsed object, rather than parsing again. + +## Benchmark + +```bash +$ npm run-script bench + +> parseurl@1.3.3 bench nodejs-parseurl +> node benchmark/index.js + + http_parser@2.8.0 + node@10.6.0 + v8@6.7.288.46-node.13 + uv@1.21.0 + zlib@1.2.11 + ares@1.14.0 + modules@64 + nghttp2@1.32.0 + napi@3 + openssl@1.1.0h + icu@61.1 + unicode@10.0 + cldr@33.0 + tz@2018c + +> node benchmark/fullurl.js + + Parsing URL "http://localhost:8888/foo/bar?user=tj&pet=fluffy" + + 4 tests completed. + + fasturl x 2,207,842 ops/sec ±3.76% (184 runs sampled) + nativeurl - legacy x 507,180 ops/sec ±0.82% (191 runs sampled) + nativeurl - whatwg x 290,044 ops/sec ±1.96% (189 runs sampled) + parseurl x 488,907 ops/sec ±2.13% (192 runs sampled) + +> node benchmark/pathquery.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" + + 4 tests completed. + + fasturl x 3,812,564 ops/sec ±3.15% (188 runs sampled) + nativeurl - legacy x 2,651,631 ops/sec ±1.68% (189 runs sampled) + nativeurl - whatwg x 161,837 ops/sec ±2.26% (189 runs sampled) + parseurl x 4,166,338 ops/sec ±2.23% (184 runs sampled) + +> node benchmark/samerequest.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" on same request object + + 4 tests completed. + + fasturl x 3,821,651 ops/sec ±2.42% (185 runs sampled) + nativeurl - legacy x 2,651,162 ops/sec ±1.90% (187 runs sampled) + nativeurl - whatwg x 175,166 ops/sec ±1.44% (188 runs sampled) + parseurl x 14,912,606 ops/sec ±3.59% (183 runs sampled) + +> node benchmark/simplepath.js + + Parsing URL "/foo/bar" + + 4 tests completed. + + fasturl x 12,421,765 ops/sec ±2.04% (191 runs sampled) + nativeurl - legacy x 7,546,036 ops/sec ±1.41% (188 runs sampled) + nativeurl - whatwg x 198,843 ops/sec ±1.83% (189 runs sampled) + parseurl x 24,244,006 ops/sec ±0.51% (194 runs sampled) + +> node benchmark/slash.js + + Parsing URL "/" + + 4 tests completed. + + fasturl x 17,159,456 ops/sec ±3.25% (188 runs sampled) + nativeurl - legacy x 11,635,097 ops/sec ±3.79% (184 runs sampled) + nativeurl - whatwg x 240,693 ops/sec ±0.83% (189 runs sampled) + parseurl x 42,279,067 ops/sec ±0.55% (190 runs sampled) +``` + +## License + + [MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/pillarjs/parseurl/master +[coveralls-url]: https://coveralls.io/r/pillarjs/parseurl?branch=master +[node-image]: https://badgen.net/npm/node/parseurl +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/parseurl +[npm-url]: https://npmjs.org/package/parseurl +[npm-version-image]: https://badgen.net/npm/v/parseurl +[travis-image]: https://badgen.net/travis/pillarjs/parseurl/master +[travis-url]: https://travis-ci.org/pillarjs/parseurl diff --git a/node_modules/parseurl/index.js b/node_modules/parseurl/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ece722327959f3bd9721488a035947387f1c1db1 --- /dev/null +++ b/node_modules/parseurl/index.js @@ -0,0 +1,158 @@ +/*! + * parseurl + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var url = require('url') +var parse = url.parse +var Url = url.Url + +/** + * Module exports. + * @public + */ + +module.exports = parseurl +module.exports.original = originalurl + +/** + * Parse the `req` url with memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public + */ + +function parseurl (req) { + var url = req.url + + if (url === undefined) { + // URL is undefined + return undefined + } + + var parsed = req._parsedUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return (req._parsedUrl = parsed) +}; + +/** + * Parse the `req` original url with fallback and memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public + */ + +function originalurl (req) { + var url = req.originalUrl + + if (typeof url !== 'string') { + // Fallback + return parseurl(req) + } + + var parsed = req._parsedOriginalUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return (req._parsedOriginalUrl = parsed) +}; + +/** + * Parse the `str` url with fast-path short-cut. + * + * @param {string} str + * @return {Object} + * @private + */ + +function fastparse (str) { + if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { + return parse(str) + } + + var pathname = str + var query = null + var search = null + + // This takes the regexp from https://github.com/joyent/node/pull/7878 + // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ + // And unrolls it into a for loop + for (var i = 1; i < str.length; i++) { + switch (str.charCodeAt(i)) { + case 0x3f: /* ? */ + if (search === null) { + pathname = str.substring(0, i) + query = str.substring(i + 1) + search = str.substring(i) + } + break + case 0x09: /* \t */ + case 0x0a: /* \n */ + case 0x0c: /* \f */ + case 0x0d: /* \r */ + case 0x20: /* */ + case 0x23: /* # */ + case 0xa0: + case 0xfeff: + return parse(str) + } + } + + var url = Url !== undefined + ? new Url() + : {} + + url.path = str + url.href = str + url.pathname = pathname + + if (search !== null) { + url.query = query + url.search = search + } + + return url +} + +/** + * Determine if parsed is still fresh for url. + * + * @param {string} url + * @param {object} parsedUrl + * @return {boolean} + * @private + */ + +function fresh (url, parsedUrl) { + return typeof parsedUrl === 'object' && + parsedUrl !== null && + (Url === undefined || parsedUrl instanceof Url) && + parsedUrl._raw === url +} diff --git a/node_modules/parseurl/package.json b/node_modules/parseurl/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6b443ca7a84aa09444101a104dd8f8946dc9fa58 --- /dev/null +++ b/node_modules/parseurl/package.json @@ -0,0 +1,40 @@ +{ + "name": "parseurl", + "description": "parse a url with memoization", + "version": "1.3.3", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "repository": "pillarjs/parseurl", + "license": "MIT", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.1", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "fast-url-parser": "1.1.3", + "istanbul": "0.4.5", + "mocha": "6.1.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --check-leaks --bail --reporter spec test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec test/" + } +} diff --git a/node_modules/path-browserify/.github/FUNDING.yml b/node_modules/path-browserify/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..a163f0e4c7269b3c229daeb5b60626cfe6257565 --- /dev/null +++ b/node_modules/path-browserify/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/path-browserify +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/path-browserify/.travis.yml b/node_modules/path-browserify/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..b14ef45bbdfb70fcf5b808c92f3c8b6fbc35ff6a --- /dev/null +++ b/node_modules/path-browserify/.travis.yml @@ -0,0 +1,16 @@ +language: node_js +sudo: false +node_js: + - "10" + - "9" + - "8" + - "6" + - "4" + - "iojs" + - "0.12" + - "0.10" + - "0.8" +before_install: + # Old npm certs are untrusted https://github.com/npm/npm/issues/20191 + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.8" ]; then export NPM_CONFIG_STRICT_SSL=false; fi' + - 'nvm install-latest-npm' diff --git a/node_modules/path-browserify/CHANGELOG.md b/node_modules/path-browserify/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..957fb130e3c26bd8f80d2c6d3077628641316e49 --- /dev/null +++ b/node_modules/path-browserify/CHANGELOG.md @@ -0,0 +1,20 @@ +# path-browserify change log + +All notable changes to this project will be documented in this file. + +This project adheres to [Semantic Versioning](http://semver.org/). + +## 1.0.1 +* Fix a duplicate test name. +* Tweak LICENSE text so Github can recognise it. +* Tweak LICENSE text to include the year and author. +* Add security policy file. + +## 1.0.0 +This release updates to the Node v10.3.0 API. **This change is breaking**, +because path methods now throw errors when called with arguments that are not +strings. + +* Add `path.parse` and `path.format`. +* Add `path.posix` as an alias to `path`. +* Port tests from Node.js. diff --git a/node_modules/path-browserify/LICENSE b/node_modules/path-browserify/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f52ee8c7249baebfc063b5284958105b199bc2c2 --- /dev/null +++ b/node_modules/path-browserify/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) 2013 James Halliday + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/path-browserify/README.md b/node_modules/path-browserify/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2f639c2477b348401c39d629dbb7215e4a057794 --- /dev/null +++ b/node_modules/path-browserify/README.md @@ -0,0 +1,45 @@ +# path-browserify [![Build Status](https://travis-ci.org/browserify/path-browserify.png?branch=master)](https://travis-ci.org/browserify/path-browserify) + +> The `path` module from Node.js for browsers + +This implements the Node.js [`path`][path] module for environments that do not have it, like browsers. + +> `path-browserify` currently matches the **Node.js 10.3** API. + +## Install + +You usually do not have to install `path-browserify` yourself! If your code runs in Node.js, `path` is built in. If your code runs in the browser, bundlers like [browserify](https://github.com/browserify/browserify) or [webpack](https://github.com/webpack/webpack) include the `path-browserify` module by default. + +But if none of those apply, with npm do: + +``` +npm install path-browserify +``` + +## Usage + +```javascript +var path = require('path') + +var filename = 'logo.png'; +var logo = path.join('./assets/img', filename); +document.querySelector('#logo').src = logo; +``` + +## API + +See the [Node.js path docs][path]. `path-browserify` currently matches the Node.js 10.3 API. +`path-browserify` only implements the POSIX functions, not the win32 ones. + +## Contributing + +PRs are very welcome! The main way to contribute to `path-browserify` is by porting features, bugfixes and tests from Node.js. Ideally, code contributions to this module are copy-pasted from Node.js and transpiled to ES5, rather than reimplemented from scratch. Matching the Node.js code as closely as possible makes maintenance simpler when new changes land in Node.js. +This module intends to provide exactly the same API as Node.js, so features that are not available in the core `path` module will not be accepted. Feature requests should instead be directed at [nodejs/node](https://github.com/nodejs/node) and will be added to this module once they are implemented in Node.js. + +If there is a difference in behaviour between Node.js's `path` module and this module, please open an issue! + +## License + +[MIT](./LICENSE) + +[path]: https://nodejs.org/docs/v10.3.0/api/path.html diff --git a/node_modules/path-browserify/index.js b/node_modules/path-browserify/index.js new file mode 100644 index 0000000000000000000000000000000000000000..24235288130acf35900f66f60c350d19583816e6 --- /dev/null +++ b/node_modules/path-browserify/index.js @@ -0,0 +1,529 @@ +// 'path' module extracted from Node.js v8.11.1 (only the posix part) +// transplited with Babel + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +function assertPath(path) { + if (typeof path !== 'string') { + throw new TypeError('Path must be a string. Received ' + JSON.stringify(path)); + } +} + +// Resolves . and .. elements in a path with directory names +function normalizeStringPosix(path, allowAboveRoot) { + var res = ''; + var lastSegmentLength = 0; + var lastSlash = -1; + var dots = 0; + var code; + for (var i = 0; i <= path.length; ++i) { + if (i < path.length) + code = path.charCodeAt(i); + else if (code === 47 /*/*/) + break; + else + code = 47 /*/*/; + if (code === 47 /*/*/) { + if (lastSlash === i - 1 || dots === 1) { + // NOOP + } else if (lastSlash !== i - 1 && dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) { + if (res.length > 2) { + var lastSlashIndex = res.lastIndexOf('/'); + if (lastSlashIndex !== res.length - 1) { + if (lastSlashIndex === -1) { + res = ''; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf('/'); + } + lastSlash = i; + dots = 0; + continue; + } + } else if (res.length === 2 || res.length === 1) { + res = ''; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + if (res.length > 0) + res += '/..'; + else + res = '..'; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) + res += '/' + path.slice(lastSlash + 1, i); + else + res = path.slice(lastSlash + 1, i); + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } else if (code === 46 /*.*/ && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} + +function _format(sep, pathObject) { + var dir = pathObject.dir || pathObject.root; + var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || ''); + if (!dir) { + return base; + } + if (dir === pathObject.root) { + return dir + base; + } + return dir + sep + base; +} + +var posix = { + // path.resolve([from ...], to) + resolve: function resolve() { + var resolvedPath = ''; + var resolvedAbsolute = false; + var cwd; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path; + if (i >= 0) + path = arguments[i]; + else { + if (cwd === undefined) + cwd = process.cwd(); + path = cwd; + } + + assertPath(path); + + // Skip empty entries + if (path.length === 0) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute); + + if (resolvedAbsolute) { + if (resolvedPath.length > 0) + return '/' + resolvedPath; + else + return '/'; + } else if (resolvedPath.length > 0) { + return resolvedPath; + } else { + return '.'; + } + }, + + normalize: function normalize(path) { + assertPath(path); + + if (path.length === 0) return '.'; + + var isAbsolute = path.charCodeAt(0) === 47 /*/*/; + var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/; + + // Normalize the path + path = normalizeStringPosix(path, !isAbsolute); + + if (path.length === 0 && !isAbsolute) path = '.'; + if (path.length > 0 && trailingSeparator) path += '/'; + + if (isAbsolute) return '/' + path; + return path; + }, + + isAbsolute: function isAbsolute(path) { + assertPath(path); + return path.length > 0 && path.charCodeAt(0) === 47 /*/*/; + }, + + join: function join() { + if (arguments.length === 0) + return '.'; + var joined; + for (var i = 0; i < arguments.length; ++i) { + var arg = arguments[i]; + assertPath(arg); + if (arg.length > 0) { + if (joined === undefined) + joined = arg; + else + joined += '/' + arg; + } + } + if (joined === undefined) + return '.'; + return posix.normalize(joined); + }, + + relative: function relative(from, to) { + assertPath(from); + assertPath(to); + + if (from === to) return ''; + + from = posix.resolve(from); + to = posix.resolve(to); + + if (from === to) return ''; + + // Trim any leading backslashes + var fromStart = 1; + for (; fromStart < from.length; ++fromStart) { + if (from.charCodeAt(fromStart) !== 47 /*/*/) + break; + } + var fromEnd = from.length; + var fromLen = fromEnd - fromStart; + + // Trim any leading backslashes + var toStart = 1; + for (; toStart < to.length; ++toStart) { + if (to.charCodeAt(toStart) !== 47 /*/*/) + break; + } + var toEnd = to.length; + var toLen = toEnd - toStart; + + // Compare paths to find the longest common path from root + var length = fromLen < toLen ? fromLen : toLen; + var lastCommonSep = -1; + var i = 0; + for (; i <= length; ++i) { + if (i === length) { + if (toLen > length) { + if (to.charCodeAt(toStart + i) === 47 /*/*/) { + // We get here if `from` is the exact base path for `to`. + // For example: from='/foo/bar'; to='/foo/bar/baz' + return to.slice(toStart + i + 1); + } else if (i === 0) { + // We get here if `from` is the root + // For example: from='/'; to='/foo' + return to.slice(toStart + i); + } + } else if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === 47 /*/*/) { + // We get here if `to` is the exact base path for `from`. + // For example: from='/foo/bar/baz'; to='/foo/bar' + lastCommonSep = i; + } else if (i === 0) { + // We get here if `to` is the root. + // For example: from='/foo'; to='/' + lastCommonSep = 0; + } + } + break; + } + var fromCode = from.charCodeAt(fromStart + i); + var toCode = to.charCodeAt(toStart + i); + if (fromCode !== toCode) + break; + else if (fromCode === 47 /*/*/) + lastCommonSep = i; + } + + var out = ''; + // Generate the relative path based on the path difference between `to` + // and `from` + for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { + if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) { + if (out.length === 0) + out += '..'; + else + out += '/..'; + } + } + + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts + if (out.length > 0) + return out + to.slice(toStart + lastCommonSep); + else { + toStart += lastCommonSep; + if (to.charCodeAt(toStart) === 47 /*/*/) + ++toStart; + return to.slice(toStart); + } + }, + + _makeLong: function _makeLong(path) { + return path; + }, + + dirname: function dirname(path) { + assertPath(path); + if (path.length === 0) return '.'; + var code = path.charCodeAt(0); + var hasRoot = code === 47 /*/*/; + var end = -1; + var matchedSlash = true; + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47 /*/*/) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) return hasRoot ? '/' : '.'; + if (hasRoot && end === 1) return '//'; + return path.slice(0, end); + }, + + basename: function basename(path, ext) { + if (ext !== undefined && typeof ext !== 'string') throw new TypeError('"ext" argument must be a string'); + assertPath(path); + + var start = 0; + var end = -1; + var matchedSlash = true; + var i; + + if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { + if (ext.length === path.length && ext === path) return ''; + var extIdx = ext.length - 1; + var firstNonSlashEnd = -1; + for (i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else { + if (firstNonSlashEnd === -1) { + // We saw the first non-path separator, remember this index in case + // we need it if the extension ends up not matching + matchedSlash = false; + firstNonSlashEnd = i + 1; + } + if (extIdx >= 0) { + // Try to match the explicit extension + if (code === ext.charCodeAt(extIdx)) { + if (--extIdx === -1) { + // We matched the extension, so mark this as the end of our path + // component + end = i; + } + } else { + // Extension does not match, so our result is the entire path + // component + extIdx = -1; + end = firstNonSlashEnd; + } + } + } + } + + if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length; + return path.slice(start, end); + } else { + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + + if (end === -1) return ''; + return path.slice(start, end); + } + }, + + extname: function extname(path) { + assertPath(path); + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + for (var i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46 /*.*/) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + startDot = i; + else if (preDotState !== 1) + preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if (startDot === -1 || end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ''; + } + return path.slice(startDot, end); + }, + + format: function format(pathObject) { + if (pathObject === null || typeof pathObject !== 'object') { + throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject); + } + return _format('/', pathObject); + }, + + parse: function parse(path) { + assertPath(path); + + var ret = { root: '', dir: '', base: '', ext: '', name: '' }; + if (path.length === 0) return ret; + var code = path.charCodeAt(0); + var isAbsolute = code === 47 /*/*/; + var start; + if (isAbsolute) { + ret.root = '/'; + start = 1; + } else { + start = 0; + } + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + var i = path.length - 1; + + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + + // Get non-dir info + for (; i >= start; --i) { + code = path.charCodeAt(i); + if (code === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46 /*.*/) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if (startDot === -1 || end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + if (end !== -1) { + if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end); + } + } else { + if (startPart === 0 && isAbsolute) { + ret.name = path.slice(1, startDot); + ret.base = path.slice(1, end); + } else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + } + ret.ext = path.slice(startDot, end); + } + + if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/'; + + return ret; + }, + + sep: '/', + delimiter: ':', + win32: null, + posix: null +}; + +posix.posix = posix; + +module.exports = posix; diff --git a/node_modules/path-browserify/package.json b/node_modules/path-browserify/package.json new file mode 100644 index 0000000000000000000000000000000000000000..821e0cf4b392b86d2b3f2395a81ef8bc18af15c2 --- /dev/null +++ b/node_modules/path-browserify/package.json @@ -0,0 +1,30 @@ +{ + "name": "path-browserify", + "description": "the path module from node core for browsers", + "version": "1.0.1", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "bugs": "https://github.com/browserify/path-browserify/issues", + "dependencies": {}, + "devDependencies": { + "tape": "^4.9.0" + }, + "homepage": "https://github.com/browserify/path-browserify", + "keywords": [ + "browser", + "browserify", + "path" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/browserify/path-browserify.git" + }, + "scripts": { + "test": "node test" + } +} diff --git a/node_modules/path-browserify/security.md b/node_modules/path-browserify/security.md new file mode 100644 index 0000000000000000000000000000000000000000..a14ace6a57db70992630a568df6a7bf57763d26b --- /dev/null +++ b/node_modules/path-browserify/security.md @@ -0,0 +1,10 @@ +# Security Policy + +## Supported Versions +Only the latest major version is supported at any given time. + +## Reporting a Vulnerability + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff --git a/node_modules/path-browserify/test/index.js b/node_modules/path-browserify/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a0fbe2bd10c6ba09b917f22e821f4df737d1a40b --- /dev/null +++ b/node_modules/path-browserify/test/index.js @@ -0,0 +1,9 @@ +require('./test-path'); +require('./test-path-basename'); +require('./test-path-dirname'); +require('./test-path-extname'); +require('./test-path-isabsolute'); +require('./test-path-join'); +require('./test-path-relative'); +require('./test-path-resolve'); +require('./test-path-zero-length-strings'); diff --git a/node_modules/path-browserify/test/test-path-basename.js b/node_modules/path-browserify/test/test-path-basename.js new file mode 100644 index 0000000000000000000000000000000000000000..81fa1dcefdee3c9b2eb016607faa055aeb87db85 --- /dev/null +++ b/node_modules/path-browserify/test/test-path-basename.js @@ -0,0 +1,79 @@ +'use strict'; +var tape = require('tape'); +var path = require('../'); + +tape('path.basename', function (t) { + t.strictEqual(path.basename(__filename), 'test-path-basename.js'); + t.strictEqual(path.basename(__filename, '.js'), 'test-path-basename'); + t.strictEqual(path.basename('.js', '.js'), ''); + t.strictEqual(path.basename(''), ''); + t.strictEqual(path.basename('/dir/basename.ext'), 'basename.ext'); + t.strictEqual(path.basename('/basename.ext'), 'basename.ext'); + t.strictEqual(path.basename('basename.ext'), 'basename.ext'); + t.strictEqual(path.basename('basename.ext/'), 'basename.ext'); + t.strictEqual(path.basename('basename.ext//'), 'basename.ext'); + t.strictEqual(path.basename('aaa/bbb', '/bbb'), 'bbb'); + t.strictEqual(path.basename('aaa/bbb', 'a/bbb'), 'bbb'); + t.strictEqual(path.basename('aaa/bbb', 'bbb'), 'bbb'); + t.strictEqual(path.basename('aaa/bbb//', 'bbb'), 'bbb'); + t.strictEqual(path.basename('aaa/bbb', 'bb'), 'b'); + t.strictEqual(path.basename('aaa/bbb', 'b'), 'bb'); + t.strictEqual(path.basename('/aaa/bbb', '/bbb'), 'bbb'); + t.strictEqual(path.basename('/aaa/bbb', 'a/bbb'), 'bbb'); + t.strictEqual(path.basename('/aaa/bbb', 'bbb'), 'bbb'); + t.strictEqual(path.basename('/aaa/bbb//', 'bbb'), 'bbb'); + t.strictEqual(path.basename('/aaa/bbb', 'bb'), 'b'); + t.strictEqual(path.basename('/aaa/bbb', 'b'), 'bb'); + t.strictEqual(path.basename('/aaa/bbb'), 'bbb'); + t.strictEqual(path.basename('/aaa/'), 'aaa'); + t.strictEqual(path.basename('/aaa/b'), 'b'); + t.strictEqual(path.basename('/a/b'), 'b'); + t.strictEqual(path.basename('//a'), 'a'); + t.end(); +}) + +tape('path.win32.basename', { skip: true }, function (t) { + // On Windows a backslash acts as a path separator. + t.strictEqual(path.win32.basename('\\dir\\basename.ext'), 'basename.ext'); + t.strictEqual(path.win32.basename('\\basename.ext'), 'basename.ext'); + t.strictEqual(path.win32.basename('basename.ext'), 'basename.ext'); + t.strictEqual(path.win32.basename('basename.ext\\'), 'basename.ext'); + t.strictEqual(path.win32.basename('basename.ext\\\\'), 'basename.ext'); + t.strictEqual(path.win32.basename('foo'), 'foo'); + t.strictEqual(path.win32.basename('aaa\\bbb', '\\bbb'), 'bbb'); + t.strictEqual(path.win32.basename('aaa\\bbb', 'a\\bbb'), 'bbb'); + t.strictEqual(path.win32.basename('aaa\\bbb', 'bbb'), 'bbb'); + t.strictEqual(path.win32.basename('aaa\\bbb\\\\\\\\', 'bbb'), 'bbb'); + t.strictEqual(path.win32.basename('aaa\\bbb', 'bb'), 'b'); + t.strictEqual(path.win32.basename('aaa\\bbb', 'b'), 'bb'); + t.strictEqual(path.win32.basename('C:'), ''); + t.strictEqual(path.win32.basename('C:.'), '.'); + t.strictEqual(path.win32.basename('C:\\'), ''); + t.strictEqual(path.win32.basename('C:\\dir\\base.ext'), 'base.ext'); + t.strictEqual(path.win32.basename('C:\\basename.ext'), 'basename.ext'); + t.strictEqual(path.win32.basename('C:basename.ext'), 'basename.ext'); + t.strictEqual(path.win32.basename('C:basename.ext\\'), 'basename.ext'); + t.strictEqual(path.win32.basename('C:basename.ext\\\\'), 'basename.ext'); + t.strictEqual(path.win32.basename('C:foo'), 'foo'); + t.strictEqual(path.win32.basename('file:stream'), 'file:stream'); + t.end(); +}); + +tape('On unix a backslash is just treated as any other character.', function (t) { + t.strictEqual(path.posix.basename('\\dir\\basename.ext'), + '\\dir\\basename.ext'); + t.strictEqual(path.posix.basename('\\basename.ext'), '\\basename.ext'); + t.strictEqual(path.posix.basename('basename.ext'), 'basename.ext'); + t.strictEqual(path.posix.basename('basename.ext\\'), 'basename.ext\\'); + t.strictEqual(path.posix.basename('basename.ext\\\\'), 'basename.ext\\\\'); + t.strictEqual(path.posix.basename('foo'), 'foo'); + t.end(); +}); + +tape('POSIX filenames may include control characters', function (t) { + // c.f. http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html + var controlCharFilename = "Icon" + (String.fromCharCode(13)); + t.strictEqual(path.posix.basename(("/a/b/" + controlCharFilename)), + controlCharFilename); + t.end(); +}); diff --git a/node_modules/path-browserify/test/test-path-dirname.js b/node_modules/path-browserify/test/test-path-dirname.js new file mode 100644 index 0000000000000000000000000000000000000000..c775071aad620546a7de955be6514c944fe8a58a --- /dev/null +++ b/node_modules/path-browserify/test/test-path-dirname.js @@ -0,0 +1,58 @@ +'use strict'; +var tape = require('tape'); +var path = require('../'); + +tape('path.posix.dirname', function (t) { + t.strictEqual(path.posix.dirname('/a/b/'), '/a'); + t.strictEqual(path.posix.dirname('/a/b'), '/a'); + t.strictEqual(path.posix.dirname('/a'), '/'); + t.strictEqual(path.posix.dirname(''), '.'); + t.strictEqual(path.posix.dirname('/'), '/'); + t.strictEqual(path.posix.dirname('////'), '/'); + t.strictEqual(path.posix.dirname('//a'), '//'); + t.strictEqual(path.posix.dirname('foo'), '.'); + t.end(); +}); + +tape('path.win32.dirname', { skip: true }, function (t) { + t.strictEqual(path.win32.dirname('c:\\'), 'c:\\'); + t.strictEqual(path.win32.dirname('c:\\foo'), 'c:\\'); + t.strictEqual(path.win32.dirname('c:\\foo\\'), 'c:\\'); + t.strictEqual(path.win32.dirname('c:\\foo\\bar'), 'c:\\foo'); + t.strictEqual(path.win32.dirname('c:\\foo\\bar\\'), 'c:\\foo'); + t.strictEqual(path.win32.dirname('c:\\foo\\bar\\baz'), 'c:\\foo\\bar'); + t.strictEqual(path.win32.dirname('\\'), '\\'); + t.strictEqual(path.win32.dirname('\\foo'), '\\'); + t.strictEqual(path.win32.dirname('\\foo\\'), '\\'); + t.strictEqual(path.win32.dirname('\\foo\\bar'), '\\foo'); + t.strictEqual(path.win32.dirname('\\foo\\bar\\'), '\\foo'); + t.strictEqual(path.win32.dirname('\\foo\\bar\\baz'), '\\foo\\bar'); + t.strictEqual(path.win32.dirname('c:'), 'c:'); + t.strictEqual(path.win32.dirname('c:foo'), 'c:'); + t.strictEqual(path.win32.dirname('c:foo\\'), 'c:'); + t.strictEqual(path.win32.dirname('c:foo\\bar'), 'c:foo'); + t.strictEqual(path.win32.dirname('c:foo\\bar\\'), 'c:foo'); + t.strictEqual(path.win32.dirname('c:foo\\bar\\baz'), 'c:foo\\bar'); + t.strictEqual(path.win32.dirname('file:stream'), '.'); + t.strictEqual(path.win32.dirname('dir\\file:stream'), 'dir'); + t.strictEqual(path.win32.dirname('\\\\unc\\share'), + '\\\\unc\\share'); + t.strictEqual(path.win32.dirname('\\\\unc\\share\\foo'), + '\\\\unc\\share\\'); + t.strictEqual(path.win32.dirname('\\\\unc\\share\\foo\\'), + '\\\\unc\\share\\'); + t.strictEqual(path.win32.dirname('\\\\unc\\share\\foo\\bar'), + '\\\\unc\\share\\foo'); + t.strictEqual(path.win32.dirname('\\\\unc\\share\\foo\\bar\\'), + '\\\\unc\\share\\foo'); + t.strictEqual(path.win32.dirname('\\\\unc\\share\\foo\\bar\\baz'), + '\\\\unc\\share\\foo\\bar'); + t.strictEqual(path.win32.dirname('/a/b/'), '/a'); + t.strictEqual(path.win32.dirname('/a/b'), '/a'); + t.strictEqual(path.win32.dirname('/a'), '/'); + t.strictEqual(path.win32.dirname(''), '.'); + t.strictEqual(path.win32.dirname('/'), '/'); + t.strictEqual(path.win32.dirname('////'), '/'); + t.strictEqual(path.win32.dirname('foo'), '.'); + t.end(); +}); diff --git a/node_modules/path-browserify/test/test-path-extname.js b/node_modules/path-browserify/test/test-path-extname.js new file mode 100644 index 0000000000000000000000000000000000000000..dab29d8a024186790c0d1faf94972009eb08f11f --- /dev/null +++ b/node_modules/path-browserify/test/test-path-extname.js @@ -0,0 +1,96 @@ +'use strict'; +var tape = require('tape'); +var path = require('../'); + +var slashRE = /\//g; + +var pairs = [ + [__filename, '.js'], + ['', ''], + ['/path/to/file', ''], + ['/path/to/file.ext', '.ext'], + ['/path.to/file.ext', '.ext'], + ['/path.to/file', ''], + ['/path.to/.file', ''], + ['/path.to/.file.ext', '.ext'], + ['/path/to/f.ext', '.ext'], + ['/path/to/..ext', '.ext'], + ['/path/to/..', ''], + ['file', ''], + ['file.ext', '.ext'], + ['.file', ''], + ['.file.ext', '.ext'], + ['/file', ''], + ['/file.ext', '.ext'], + ['/.file', ''], + ['/.file.ext', '.ext'], + ['.path/file.ext', '.ext'], + ['file.ext.ext', '.ext'], + ['file.', '.'], + ['.', ''], + ['./', ''], + ['.file.ext', '.ext'], + ['.file', ''], + ['.file.', '.'], + ['.file..', '.'], + ['..', ''], + ['../', ''], + ['..file.ext', '.ext'], + ['..file', '.file'], + ['..file.', '.'], + ['..file..', '.'], + ['...', '.'], + ['...ext', '.ext'], + ['....', '.'], + ['file.ext/', '.ext'], + ['file.ext//', '.ext'], + ['file/', ''], + ['file//', ''], + ['file./', '.'], + ['file.//', '.'] ]; + +tape('path.posix.extname', function (t) { + pairs.forEach(function (p) { + var input = p[0]; + var expected = p[1]; + t.strictEqual(expected, path.posix.extname(input)); + }); + t.end(); +}); + +tape('path.win32.extname', { skip: true }, function (t) { + pairs.forEach(function (p) { + var input = p[0].replace(slashRE, '\\'); + var expected = p[1]; + t.strictEqual(expected, path.win32.extname(input)); + t.strictEqual(expected, path.win32.extname("C:" + input)); + }); + t.end(); +}); + +tape('path.win32.extname backslash', { skip: true }, function (t) { + // On Windows, backslash is a path separator. + t.strictEqual(path.win32.extname('.\\'), ''); + t.strictEqual(path.win32.extname('..\\'), ''); + t.strictEqual(path.win32.extname('file.ext\\'), '.ext'); + t.strictEqual(path.win32.extname('file.ext\\\\'), '.ext'); + t.strictEqual(path.win32.extname('file\\'), ''); + t.strictEqual(path.win32.extname('file\\\\'), ''); + t.strictEqual(path.win32.extname('file.\\'), '.'); + t.strictEqual(path.win32.extname('file.\\\\'), '.'); + t.end(); +}); + +tape('path.posix.extname backslash', function (t) { + // On *nix, backslash is a valid name component like any other character. + t.strictEqual(path.posix.extname('.\\'), ''); + t.strictEqual(path.posix.extname('..\\'), '.\\'); + t.strictEqual(path.posix.extname('file.ext\\'), '.ext\\'); + t.strictEqual(path.posix.extname('file.ext\\\\'), '.ext\\\\'); + t.strictEqual(path.posix.extname('file\\'), ''); + t.strictEqual(path.posix.extname('file\\\\'), ''); + t.strictEqual(path.posix.extname('file.\\'), '.\\'); + t.strictEqual(path.posix.extname('file.\\\\'), '.\\\\'); + t.end(); +}); + diff --git a/node_modules/path-browserify/test/test-path-isabsolute.js b/node_modules/path-browserify/test/test-path-isabsolute.js new file mode 100644 index 0000000000000000000000000000000000000000..f7fe9e33d2001c921e81f7bb2b1ac85c16efec71 --- /dev/null +++ b/node_modules/path-browserify/test/test-path-isabsolute.js @@ -0,0 +1,33 @@ +'use strict'; +var tape = require('tape'); +var path = require('../'); + +tape('path.win32.isAbsolute', { skip: true }, function (t) { + t.strictEqual(path.win32.isAbsolute('/'), true); + t.strictEqual(path.win32.isAbsolute('//'), true); + t.strictEqual(path.win32.isAbsolute('//server'), true); + t.strictEqual(path.win32.isAbsolute('//server/file'), true); + t.strictEqual(path.win32.isAbsolute('\\\\server\\file'), true); + t.strictEqual(path.win32.isAbsolute('\\\\server'), true); + t.strictEqual(path.win32.isAbsolute('\\\\'), true); + t.strictEqual(path.win32.isAbsolute('c'), false); + t.strictEqual(path.win32.isAbsolute('c:'), false); + t.strictEqual(path.win32.isAbsolute('c:\\'), true); + t.strictEqual(path.win32.isAbsolute('c:/'), true); + t.strictEqual(path.win32.isAbsolute('c://'), true); + t.strictEqual(path.win32.isAbsolute('C:/Users/'), true); + t.strictEqual(path.win32.isAbsolute('C:\\Users\\'), true); + t.strictEqual(path.win32.isAbsolute('C:cwd/another'), false); + t.strictEqual(path.win32.isAbsolute('C:cwd\\another'), false); + t.strictEqual(path.win32.isAbsolute('directory/directory'), false); + t.strictEqual(path.win32.isAbsolute('directory\\directory'), false); + t.end(); +}); + +tape('path.posix.isAbsolute', function (t) { + t.strictEqual(path.posix.isAbsolute('/home/foo'), true); + t.strictEqual(path.posix.isAbsolute('/home/foo/..'), true); + t.strictEqual(path.posix.isAbsolute('bar/'), false); + t.strictEqual(path.posix.isAbsolute('./baz'), false); + t.end(); +}); diff --git a/node_modules/path-browserify/test/test-path-join.js b/node_modules/path-browserify/test/test-path-join.js new file mode 100644 index 0000000000000000000000000000000000000000..086e4a97a22e1eca0ab54c27f41dd4730665ead5 --- /dev/null +++ b/node_modules/path-browserify/test/test-path-join.js @@ -0,0 +1,126 @@ +'use strict'; +var tape = require('tape'); +var path = require('../'); + +var backslashRE = /\\/g; + +var joinTests = + // arguments result + [[['.', 'x/b', '..', '/b/c.js'], 'x/b/c.js'], + [[], '.'], + [['/.', 'x/b', '..', '/b/c.js'], '/x/b/c.js'], + [['/foo', '../../../bar'], '/bar'], + [['foo', '../../../bar'], '../../bar'], + [['foo/', '../../../bar'], '../../bar'], + [['foo/x', '../../../bar'], '../bar'], + [['foo/x', './bar'], 'foo/x/bar'], + [['foo/x/', './bar'], 'foo/x/bar'], + [['foo/x/', '.', 'bar'], 'foo/x/bar'], + [['./'], './'], + [['.', './'], './'], + [['.', '.', '.'], '.'], + [['.', './', '.'], '.'], + [['.', '/./', '.'], '.'], + [['.', '/////./', '.'], '.'], + [['.'], '.'], + [['', '.'], '.'], + [['', 'foo'], 'foo'], + [['foo', '/bar'], 'foo/bar'], + [['', '/foo'], '/foo'], + [['', '', '/foo'], '/foo'], + [['', '', 'foo'], 'foo'], + [['foo', ''], 'foo'], + [['foo/', ''], 'foo/'], + [['foo', '', '/bar'], 'foo/bar'], + [['./', '..', '/foo'], '../foo'], + [['./', '..', '..', '/foo'], '../../foo'], + [['.', '..', '..', '/foo'], '../../foo'], + [['', '..', '..', '/foo'], '../../foo'], + [['/'], '/'], + [['/', '.'], '/'], + [['/', '..'], '/'], + [['/', '..', '..'], '/'], + [[''], '.'], + [['', ''], '.'], + [[' /foo'], ' /foo'], + [[' ', 'foo'], ' /foo'], + [[' ', '.'], ' '], + [[' ', '/'], ' /'], + [[' ', ''], ' '], + [['/', 'foo'], '/foo'], + [['/', '/foo'], '/foo'], + [['/', '//foo'], '/foo'], + [['/', '', '/foo'], '/foo'], + [['', '/', 'foo'], '/foo'], + [['', '/', '/foo'], '/foo'] + ]; + +// Windows-specific join tests +var windowsJoinTests = + [// arguments result + // UNC path expected + [['//foo/bar'], '\\\\foo\\bar\\'], + [['\\/foo/bar'], '\\\\foo\\bar\\'], + [['\\\\foo/bar'], '\\\\foo\\bar\\'], + // UNC path expected - server and share separate + [['//foo', 'bar'], '\\\\foo\\bar\\'], + [['//foo/', 'bar'], '\\\\foo\\bar\\'], + [['//foo', '/bar'], '\\\\foo\\bar\\'], + // UNC path expected - questionable + [['//foo', '', 'bar'], '\\\\foo\\bar\\'], + [['//foo/', '', 'bar'], '\\\\foo\\bar\\'], + [['//foo/', '', '/bar'], '\\\\foo\\bar\\'], + // UNC path expected - even more questionable + [['', '//foo', 'bar'], '\\\\foo\\bar\\'], + [['', '//foo/', 'bar'], '\\\\foo\\bar\\'], + [['', '//foo/', '/bar'], '\\\\foo\\bar\\'], + // No UNC path expected (no double slash in first component) + [['\\', 'foo/bar'], '\\foo\\bar'], + [['\\', '/foo/bar'], '\\foo\\bar'], + [['', '/', '/foo/bar'], '\\foo\\bar'], + // No UNC path expected (no non-slashes in first component - + // questionable) + [['//', 'foo/bar'], '\\foo\\bar'], + [['//', '/foo/bar'], '\\foo\\bar'], + [['\\\\', '/', '/foo/bar'], '\\foo\\bar'], + [['//'], '/'], + // No UNC path expected (share name missing - questionable). + [['//foo'], '\\foo'], + [['//foo/'], '\\foo\\'], + [['//foo', '/'], '\\foo\\'], + [['//foo', '', '/'], '\\foo\\'], + // No UNC path expected (too many leading slashes - questionable) + [['///foo/bar'], '\\foo\\bar'], + [['////foo', 'bar'], '\\foo\\bar'], + [['\\\\\\/foo/bar'], '\\foo\\bar'], + // Drive-relative vs drive-absolute paths. This merely describes the + // status quo, rather than being obviously right + [['c:'], 'c:.'], + [['c:.'], 'c:.'], + [['c:', ''], 'c:.'], + [['', 'c:'], 'c:.'], + [['c:.', '/'], 'c:.\\'], + [['c:.', 'file'], 'c:file'], + [['c:', '/'], 'c:\\'], + [['c:', 'file'], 'c:\\file'] + ]; + +tape('path.posix.join', function (t) { + joinTests.forEach(function (p) { + var actual = path.posix.join.apply(null, p[0]); + t.strictEqual(actual, p[1]); + }); + t.end(); +}); + +tape('path.win32.join', { skip: true }, function (t) { + joinTests.forEach(function (p) { + var actual = path.win32.join.apply(null, p[0]).replace(backslashRE, '/'); + t.strictEqual(actual, p[1]); + }); + windowsJoinTests.forEach(function (p) { + var actual = path.win32.join.apply(null, p[0]); + t.strictEqual(actual, p[1]); + }); + t.end(); +}); diff --git a/node_modules/path-browserify/test/test-path-parse-format.js b/node_modules/path-browserify/test/test-path-parse-format.js new file mode 100644 index 0000000000000000000000000000000000000000..aea48b2fbf0e8f6f0d63b273ae6674e62ccd5857 --- /dev/null +++ b/node_modules/path-browserify/test/test-path-parse-format.js @@ -0,0 +1,235 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; +var tape = require('tape'); +var path = require('../'); + +var winPaths = [ + // [path, root] + ['C:\\path\\dir\\index.html', 'C:\\'], + ['C:\\another_path\\DIR\\1\\2\\33\\\\index', 'C:\\'], + ['another_path\\DIR with spaces\\1\\2\\33\\index', ''], + ['\\', '\\'], + ['\\foo\\C:', '\\'], + ['file', ''], + ['file:stream', ''], + ['.\\file', ''], + ['C:', 'C:'], + ['C:.', 'C:'], + ['C:..', 'C:'], + ['C:abc', 'C:'], + ['C:\\', 'C:\\'], + ['C:\\abc', 'C:\\' ], + ['', ''], + + // unc + ['\\\\server\\share\\file_path', '\\\\server\\share\\'], + ['\\\\server two\\shared folder\\file path.zip', + '\\\\server two\\shared folder\\'], + ['\\\\teela\\admin$\\system32', '\\\\teela\\admin$\\'], + ['\\\\?\\UNC\\server\\share', '\\\\?\\UNC\\'] +]; + +var winSpecialCaseParseTests = [ + ['/foo/bar', { root: '/' }], +]; + +var winSpecialCaseFormatTests = [ + [{ dir: 'some\\dir' }, 'some\\dir\\'], + [{ base: 'index.html' }, 'index.html'], + [{ root: 'C:\\' }, 'C:\\'], + [{ name: 'index', ext: '.html' }, 'index.html'], + [{ dir: 'some\\dir', name: 'index', ext: '.html' }, 'some\\dir\\index.html'], + [{ root: 'C:\\', name: 'index', ext: '.html' }, 'C:\\index.html'], + [{}, ''] +]; + +var unixPaths = [ + // [path, root] + ['/home/user/dir/file.txt', '/'], + ['/home/user/a dir/another File.zip', '/'], + ['/home/user/a dir//another&File.', '/'], + ['/home/user/a$$$dir//another File.zip', '/'], + ['user/dir/another File.zip', ''], + ['file', ''], + ['.\\file', ''], + ['./file', ''], + ['C:\\foo', ''], + ['/', '/'], + ['', ''], + ['.', ''], + ['..', ''], + ['/foo', '/'], + ['/foo.', '/'], + ['/foo.bar', '/'], + ['/.', '/'], + ['/.foo', '/'], + ['/.foo.bar', '/'], + ['/foo/bar.baz', '/'] +]; + +var unixSpecialCaseFormatTests = [ + [{ dir: 'some/dir' }, 'some/dir/'], + [{ base: 'index.html' }, 'index.html'], + [{ root: '/' }, '/'], + [{ name: 'index', ext: '.html' }, 'index.html'], + [{ dir: 'some/dir', name: 'index', ext: '.html' }, 'some/dir/index.html'], + [{ root: '/', name: 'index', ext: '.html' }, '/index.html'], + [{}, ''] +]; + +var errors = [ + { method: 'parse', input: [null], message: TypeError }, + { method: 'parse', input: [{}], message: TypeError }, + { method: 'parse', input: [true], message: TypeError }, + { method: 'parse', input: [1], message: TypeError }, + { method: 'parse', input: [], message: TypeError }, + { method: 'format', input: [null], message: TypeError }, + { method: 'format', input: [''], message: TypeError }, + { method: 'format', input: [true], message: TypeError }, + { method: 'format', input: [1], message: TypeError }, +]; + +tape('path.win32.parse', { skip: true }, function (t) { + checkParseFormat(t, path.win32, winPaths); + checkSpecialCaseParseFormat(t, path.win32, winSpecialCaseParseTests); + t.end(); +}); + +tape('path.posix.parse', function (t) { + checkParseFormat(t, path.posix, unixPaths); + t.end(); +}); + +tape('path.win32.parse errors', { skip: true }, function (t) { + checkErrors(t, path.win32); + t.end(); +}); + +tape('path.posix.parse errors', function (t) { + checkErrors(t, path.posix); + t.end(); +}); + +tape('path.win32.format', { skip: true }, function (t) { + checkFormat(t, path.win32, winSpecialCaseFormatTests); + t.end(); +}); + +tape('path.posix.format', function (t) { + checkFormat(t, path.posix, unixSpecialCaseFormatTests); + t.end(); +}); + +// Test removal of trailing path separators +var windowsTrailingTests = + [['.\\', { root: '', dir: '', base: '.', ext: '', name: '.' }], + ['\\\\', { root: '\\', dir: '\\', base: '', ext: '', name: '' }], + ['\\\\', { root: '\\', dir: '\\', base: '', ext: '', name: '' }], + ['c:\\foo\\\\\\', + { root: 'c:\\', dir: 'c:\\', base: 'foo', ext: '', name: 'foo' }], + ['D:\\foo\\\\\\bar.baz', + { root: 'D:\\', + dir: 'D:\\foo\\\\', + base: 'bar.baz', + ext: '.baz', + name: 'bar' + } + ] + ]; +var posixTrailingTests = + [['./', { root: '', dir: '', base: '.', ext: '', name: '.' }], + ['//', { root: '/', dir: '/', base: '', ext: '', name: '' }], + ['///', { root: '/', dir: '/', base: '', ext: '', name: '' }], + ['/foo///', { root: '/', dir: '/', base: 'foo', ext: '', name: 'foo' }], + ['/foo///bar.baz', + { root: '/', dir: '/foo//', base: 'bar.baz', ext: '.baz', name: 'bar' } + ] + ]; + +tape('path.win32.parse trailing', { skip: true }, function (t) { + windowsTrailingTests.forEach(function (p) { + var actual = path.win32.parse(p[0]); + var expected = p[1]; + t.deepEqual(actual, expected) + }); + t.end(); +}); + +tape('path.posix.parse trailing', function (t) { + posixTrailingTests.forEach(function (p) { + var actual = path.posix.parse(p[0]); + var expected = p[1]; + t.deepEqual(actual, expected) + }); + t.end(); +}); + +function checkErrors(t, path) { + errors.forEach(function(errorCase) { + t.throws(function () { + path[errorCase.method].apply(path, errorCase.input); + }, errorCase.message); + }); +} + +function checkParseFormat(t, path, paths) { + paths.forEach(function(p) { + var element = p[0]; + var root = p[1]; + var output = path.parse(element); + t.strictEqual(typeof output.root, 'string'); + t.strictEqual(typeof output.dir, 'string'); + t.strictEqual(typeof output.base, 'string'); + t.strictEqual(typeof output.ext, 'string'); + t.strictEqual(typeof output.name, 'string'); + t.strictEqual(path.format(output), element); + t.strictEqual(output.root, root); + t.ok(output.dir.startsWith(output.root)); + t.strictEqual(output.dir, output.dir ? path.dirname(element) : ''); + t.strictEqual(output.base, path.basename(element)); + t.strictEqual(output.ext, path.extname(element)); + }); +} + +function checkSpecialCaseParseFormat(t, path, testCases) { + testCases.forEach(function(testCase) { + var element = testCase[0]; + var expect = testCase[1]; + var output = path.parse(element); + Object.keys(expect).forEach(function(key) { + t.strictEqual(output[key], expect[key]); + }); + }); +} + +function checkFormat(t, path, testCases) { + testCases.forEach(function(testCase) { + t.strictEqual(path.format(testCase[0]), testCase[1]); + }); + + [null, undefined, 1, true, false, 'string'].forEach(function (pathObject) { + t.throws(function() { + path.format(pathObject); + }, /The "pathObject" argument must be of type Object. Received type (\w+)/); + }); +} diff --git a/node_modules/path-browserify/test/test-path-relative.js b/node_modules/path-browserify/test/test-path-relative.js new file mode 100644 index 0000000000000000000000000000000000000000..44841f679c1040f1b50574dea47c59ac0af997a2 --- /dev/null +++ b/node_modules/path-browserify/test/test-path-relative.js @@ -0,0 +1,66 @@ +'use strict'; +var tape = require('tape'); +var path = require('../'); + +var relativeTests = { + win32: + // arguments result + [['c:/blah\\blah', 'd:/games', 'd:\\games'], + ['c:/aaaa/bbbb', 'c:/aaaa', '..'], + ['c:/aaaa/bbbb', 'c:/cccc', '..\\..\\cccc'], + ['c:/aaaa/bbbb', 'c:/aaaa/bbbb', ''], + ['c:/aaaa/bbbb', 'c:/aaaa/cccc', '..\\cccc'], + ['c:/aaaa/', 'c:/aaaa/cccc', 'cccc'], + ['c:/', 'c:\\aaaa\\bbbb', 'aaaa\\bbbb'], + ['c:/aaaa/bbbb', 'd:\\', 'd:\\'], + ['c:/AaAa/bbbb', 'c:/aaaa/bbbb', ''], + ['c:/aaaaa/', 'c:/aaaa/cccc', '..\\aaaa\\cccc'], + ['C:\\foo\\bar\\baz\\quux', 'C:\\', '..\\..\\..\\..'], + ['C:\\foo\\test', 'C:\\foo\\test\\bar\\package.json', 'bar\\package.json'], + ['C:\\foo\\bar\\baz-quux', 'C:\\foo\\bar\\baz', '..\\baz'], + ['C:\\foo\\bar\\baz', 'C:\\foo\\bar\\baz-quux', '..\\baz-quux'], + ['\\\\foo\\bar', '\\\\foo\\bar\\baz', 'baz'], + ['\\\\foo\\bar\\baz', '\\\\foo\\bar', '..'], + ['\\\\foo\\bar\\baz-quux', '\\\\foo\\bar\\baz', '..\\baz'], + ['\\\\foo\\bar\\baz', '\\\\foo\\bar\\baz-quux', '..\\baz-quux'], + ['C:\\baz-quux', 'C:\\baz', '..\\baz'], + ['C:\\baz', 'C:\\baz-quux', '..\\baz-quux'], + ['\\\\foo\\baz-quux', '\\\\foo\\baz', '..\\baz'], + ['\\\\foo\\baz', '\\\\foo\\baz-quux', '..\\baz-quux'], + ['C:\\baz', '\\\\foo\\bar\\baz', '\\\\foo\\bar\\baz'], + ['\\\\foo\\bar\\baz', 'C:\\baz', 'C:\\baz'] + ], + posix: + // arguments result + [['/var/lib', '/var', '..'], + ['/var/lib', '/bin', '../../bin'], + ['/var/lib', '/var/lib', ''], + ['/var/lib', '/var/apache', '../apache'], + ['/var/', '/var/lib', 'lib'], + ['/', '/var/lib', 'var/lib'], + ['/foo/test', '/foo/test/bar/package.json', 'bar/package.json'], + ['/Users/a/web/b/test/mails', '/Users/a/web/b', '../..'], + ['/foo/bar/baz-quux', '/foo/bar/baz', '../baz'], + ['/foo/bar/baz', '/foo/bar/baz-quux', '../baz-quux'], + ['/baz-quux', '/baz', '../baz'], + ['/baz', '/baz-quux', '../baz-quux'] + ] +}; + +tape('path.posix.relative', function (t) { + relativeTests.posix.forEach(function (p) { + var expected = p[2]; + var actual = path.posix.relative(p[0], p[1]); + t.strictEqual(actual, expected); + }); + t.end(); +}); + +tape('path.win32.relative', { skip: true }, function (t) { + relativeTests.win32.forEach(function (p) { + var expected = p[2]; + var actual = path.win32.relative(p[0], p[1]); + t.strictEqual(actual, expected); + }); + t.end(); +}); diff --git a/node_modules/path-browserify/test/test-path-resolve.js b/node_modules/path-browserify/test/test-path-resolve.js new file mode 100644 index 0000000000000000000000000000000000000000..520fdb8c0ce0682a2b2359149733ab07ce0b313e --- /dev/null +++ b/node_modules/path-browserify/test/test-path-resolve.js @@ -0,0 +1,45 @@ +'use strict'; +var tape = require('tape'); +var path = require('../'); + +var windowsTests = + // arguments result + [[['c:/blah\\blah', 'd:/games', 'c:../a'], 'c:\\blah\\a'], + [['c:/ignore', 'd:\\a/b\\c/d', '\\e.exe'], 'd:\\e.exe'], + [['c:/ignore', 'c:/some/file'], 'c:\\some\\file'], + [['d:/ignore', 'd:some/dir//'], 'd:\\ignore\\some\\dir'], + [['.'], process.cwd()], + [['//server/share', '..', 'relative\\'], '\\\\server\\share\\relative'], + [['c:/', '//'], 'c:\\'], + [['c:/', '//dir'], 'c:\\dir'], + [['c:/', '//server/share'], '\\\\server\\share\\'], + [['c:/', '//server//share'], '\\\\server\\share\\'], + [['c:/', '///some//dir'], 'c:\\some\\dir'], + [['C:\\foo\\tmp.3\\', '..\\tmp.3\\cycles\\root.js'], + 'C:\\foo\\tmp.3\\cycles\\root.js'] + ]; +var posixTests = + // arguments result + [[['/var/lib', '../', 'file/'], '/var/file'], + [['/var/lib', '/../', 'file/'], '/file'], + [['a/b/c/', '../../..'], process.cwd()], + [['.'], process.cwd()], + [['/some/dir', '.', '/absolute/'], '/absolute'], + [['/foo/tmp.3/', '../tmp.3/cycles/root.js'], '/foo/tmp.3/cycles/root.js'] + ]; + +tape('path.posix.resolve', function (t) { + posixTests.forEach(function (p) { + var actual = path.posix.resolve.apply(null, p[0]); + t.strictEqual(actual, p[1]); + }); + t.end(); +}); + +tape('path.win32.resolve', { skip: true }, function (t) { + windowsTests.forEach(function (p) { + var actual = path.win32.resolve.apply(null, p[0]); + t.strictEqual(actual, p[1]); + }); + t.end(); +}); diff --git a/node_modules/path-browserify/test/test-path-zero-length-strings.js b/node_modules/path-browserify/test/test-path-zero-length-strings.js new file mode 100644 index 0000000000000000000000000000000000000000..7361b5c25fb70e9e100d5dda0b518a6c100ede0a --- /dev/null +++ b/node_modules/path-browserify/test/test-path-zero-length-strings.js @@ -0,0 +1,53 @@ +'use strict'; + +// These testcases are specific to one uncommon behavior in path module. Few +// of the functions in path module, treat '' strings as current working +// directory. This test makes sure that the behavior is intact between commits. +// See: https://github.com/nodejs/node/pull/2106 + +var tape = require('tape'); +var path = require('../'); +var pwd = process.cwd(); + +tape('path.join zero-length', function (t) { + // join will internally ignore all the zero-length strings and it will return + // '.' if the joined string is a zero-length string. + t.strictEqual(path.posix.join(''), '.'); + t.strictEqual(path.posix.join('', ''), '.'); + if (path.win32) t.strictEqual(path.win32.join(''), '.'); + if (path.win32) t.strictEqual(path.win32.join('', ''), '.'); + t.strictEqual(path.join(pwd), pwd); + t.strictEqual(path.join(pwd, ''), pwd); + t.end(); +}); + +tape('path.normalize zero-length', function (t) { + // normalize will return '.' if the input is a zero-length string + t.strictEqual(path.posix.normalize(''), '.'); + if (path.win32) t.strictEqual(path.win32.normalize(''), '.'); + t.strictEqual(path.normalize(pwd), pwd); + t.end(); +}); + +tape('path.isAbsolute zero-length', function (t) { + // Since '' is not a valid path in any of the common environments, return false + t.strictEqual(path.posix.isAbsolute(''), false); + if (path.win32) t.strictEqual(path.win32.isAbsolute(''), false); + t.end(); +}); + +tape('path.resolve zero-length', function (t) { + // resolve, internally ignores all the zero-length strings and returns the + // current working directory + t.strictEqual(path.resolve(''), pwd); + t.strictEqual(path.resolve('', ''), pwd); + t.end(); +}); + +tape('path.relative zero-length', function (t) { + // relative, internally calls resolve. So, '' is actually the current directory + t.strictEqual(path.relative('', pwd), ''); + t.strictEqual(path.relative(pwd, ''), ''); + t.strictEqual(path.relative(pwd, pwd), ''); + t.end(); +}); diff --git a/node_modules/path-browserify/test/test-path.js b/node_modules/path-browserify/test/test-path.js new file mode 100644 index 0000000000000000000000000000000000000000..7de12b4459cca7d222f0a7d5690f10ddd9e0e85e --- /dev/null +++ b/node_modules/path-browserify/test/test-path.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; +var tape = require('tape'); +var path = require('../'); + +// Test thrown TypeErrors +var typeErrorTests = [true, false, 7, null, {}, undefined, [], NaN]; + +function fail(t, fn) { + var args = [].slice.call(arguments, 1); + + t.throws(function () { + fn.apply(null, args); + }, TypeError); +} + +tape('path.posix TypeErrors', function (t) { + typeErrorTests.forEach(function (test) { + fail(t, path.posix.join, test); + fail(t, path.posix.resolve, test); + fail(t, path.posix.normalize, test); + fail(t, path.posix.isAbsolute, test); + fail(t, path.posix.relative, test, 'foo'); + fail(t, path.posix.relative, 'foo', test); + fail(t, path.posix.parse, test); + fail(t, path.posix.dirname, test); + fail(t, path.posix.basename, test); + fail(t, path.posix.extname, test); + + // undefined is a valid value as the second argument to basename + if (test !== undefined) { + fail(t, path.posix.basename, 'foo', test); + } + }); + t.end(); +}); + +tape('path.win32 TypeErrors', { skip: true }, function (t) { + typeErrorTests.forEach(function (test) { + fail(t, path.win32.join, test); + fail(t, path.win32.resolve, test); + fail(t, path.win32.normalize, test); + fail(t, path.win32.isAbsolute, test); + fail(t, path.win32.relative, test, 'foo'); + fail(t, path.win32.relative, 'foo', test); + fail(t, path.win32.parse, test); + fail(t, path.win32.dirname, test); + fail(t, path.win32.basename, test); + fail(t, path.win32.extname, test); + + // undefined is a valid value as the second argument to basename + if (test !== undefined) { + fail(t, path.win32.basename, 'foo', test); + } + }); + t.end(); +}); + +// path.sep tests +tape('path.win32.sep', { skip: true }, function (t) { + // windows + t.strictEqual(path.win32.sep, '\\'); + t.end(); +}); +tape('path.posix.sep', function (t) { + // posix + t.strictEqual(path.posix.sep, '/'); + t.end(); +}); + +// path.delimiter tests +tape('path.win32.delimiter', { skip: true }, function (t) { + // windows + t.strictEqual(path.win32.delimiter, ';'); + t.end(); +}); +tape('path.posix.delimiter', function (t) { + // posix + t.strictEqual(path.posix.delimiter, ':'); + t.end(); +}); + +tape('path', function (t) { + t.strictEqual(path, path.posix); + t.end(); +}); + diff --git a/node_modules/path-exists/index.d.ts b/node_modules/path-exists/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..54b7ab8f4ec50cb0180fe046d155f5116386641b --- /dev/null +++ b/node_modules/path-exists/index.d.ts @@ -0,0 +1,28 @@ +declare const pathExists: { + /** + Check if a path exists. + + @returns Whether the path exists. + + @example + ``` + // foo.ts + import pathExists = require('path-exists'); + + (async () => { + console.log(await pathExists('foo.ts')); + //=> true + })(); + ``` + */ + (path: string): Promise; + + /** + Synchronously check if a path exists. + + @returns Whether the path exists. + */ + sync(path: string): boolean; +}; + +export = pathExists; diff --git a/node_modules/path-exists/index.js b/node_modules/path-exists/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1943921b758505a03af8330fa28ef86f6dea9b3a --- /dev/null +++ b/node_modules/path-exists/index.js @@ -0,0 +1,23 @@ +'use strict'; +const fs = require('fs'); +const {promisify} = require('util'); + +const pAccess = promisify(fs.access); + +module.exports = async path => { + try { + await pAccess(path); + return true; + } catch (_) { + return false; + } +}; + +module.exports.sync = path => { + try { + fs.accessSync(path); + return true; + } catch (_) { + return false; + } +}; diff --git a/node_modules/path-exists/license b/node_modules/path-exists/license new file mode 100644 index 0000000000000000000000000000000000000000..e7af2f77107d73046421ef56c4684cbfdd3c1e89 --- /dev/null +++ b/node_modules/path-exists/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/path-exists/package.json b/node_modules/path-exists/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0755256a2b33fed98f241a398d341b1682967ca3 --- /dev/null +++ b/node_modules/path-exists/package.json @@ -0,0 +1,39 @@ +{ + "name": "path-exists", + "version": "4.0.0", + "description": "Check if a path exists", + "license": "MIT", + "repository": "sindresorhus/path-exists", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "path", + "exists", + "exist", + "file", + "filepath", + "fs", + "filesystem", + "file-system", + "access", + "stat" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/path-exists/readme.md b/node_modules/path-exists/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..81f98454567fbfcfcf9ced2ae50231ff99c547b1 --- /dev/null +++ b/node_modules/path-exists/readme.md @@ -0,0 +1,52 @@ +# path-exists [![Build Status](https://travis-ci.org/sindresorhus/path-exists.svg?branch=master)](https://travis-ci.org/sindresorhus/path-exists) + +> Check if a path exists + +NOTE: `fs.existsSync` has been un-deprecated in Node.js since 6.8.0. If you only need to check synchronously, this module is not needed. + +While [`fs.exists()`](https://nodejs.org/api/fs.html#fs_fs_exists_path_callback) is being [deprecated](https://github.com/iojs/io.js/issues/103), there's still a genuine use-case of being able to check if a path exists for other purposes than doing IO with it. + +Never use this before handling a file though: + +> In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to `fs.exists()` and `fs.open()`. Just open the file and handle the error when it's not there. + + +## Install + +``` +$ npm install path-exists +``` + + +## Usage + +```js +// foo.js +const pathExists = require('path-exists'); + +(async () => { + console.log(await pathExists('foo.js')); + //=> true +})(); +``` + + +## API + +### pathExists(path) + +Returns a `Promise` of whether the path exists. + +### pathExists.sync(path) + +Returns a `boolean` of whether the path exists. + + +## Related + +- [path-exists-cli](https://github.com/sindresorhus/path-exists-cli) - CLI for this module + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/path-parse/LICENSE b/node_modules/path-parse/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..810f3dbea83b538626b466a1aa3d60ed8cf27281 --- /dev/null +++ b/node_modules/path-parse/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Javier Blanco + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/path-parse/README.md b/node_modules/path-parse/README.md new file mode 100644 index 0000000000000000000000000000000000000000..05097f86aef364d88bab44fac2ce01c2d825ada9 --- /dev/null +++ b/node_modules/path-parse/README.md @@ -0,0 +1,42 @@ +# path-parse [![Build Status](https://travis-ci.org/jbgutierrez/path-parse.svg?branch=master)](https://travis-ci.org/jbgutierrez/path-parse) + +> Node.js [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) [ponyfill](https://ponyfill.com). + +## Install + +``` +$ npm install --save path-parse +``` + +## Usage + +```js +var pathParse = require('path-parse'); + +pathParse('/home/user/dir/file.txt'); +//=> { +// root : "/", +// dir : "/home/user/dir", +// base : "file.txt", +// ext : ".txt", +// name : "file" +// } +``` + +## API + +See [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) docs. + +### pathParse(path) + +### pathParse.posix(path) + +The Posix specific version. + +### pathParse.win32(path) + +The Windows specific version. + +## License + +MIT © [Javier Blanco](http://jbgutierrez.info) diff --git a/node_modules/path-parse/index.js b/node_modules/path-parse/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f062d0a23e6299b2eee1797c6c476159348f147c --- /dev/null +++ b/node_modules/path-parse/index.js @@ -0,0 +1,75 @@ +'use strict'; + +var isWindows = process.platform === 'win32'; + +// Regex to split a windows path into into [dir, root, basename, name, ext] +var splitWindowsRe = + /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/; + +var win32 = {}; + +function win32SplitPath(filename) { + return splitWindowsRe.exec(filename).slice(1); +} + +win32.parse = function(pathString) { + if (typeof pathString !== 'string') { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = win32SplitPath(pathString); + if (!allParts || allParts.length !== 5) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + return { + root: allParts[1], + dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1), + base: allParts[2], + ext: allParts[4], + name: allParts[3] + }; +}; + + + +// Split a filename into [dir, root, basename, name, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/; +var posix = {}; + + +function posixSplitPath(filename) { + return splitPathRe.exec(filename).slice(1); +} + + +posix.parse = function(pathString) { + if (typeof pathString !== 'string') { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = posixSplitPath(pathString); + if (!allParts || allParts.length !== 5) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + + return { + root: allParts[1], + dir: allParts[0].slice(0, -1), + base: allParts[2], + ext: allParts[4], + name: allParts[3], + }; +}; + + +if (isWindows) + module.exports = win32.parse; +else /* posix */ + module.exports = posix.parse; + +module.exports.posix = posix.parse; +module.exports.win32 = win32.parse; diff --git a/node_modules/path-parse/package.json b/node_modules/path-parse/package.json new file mode 100644 index 0000000000000000000000000000000000000000..36c23f84e7063cc7063844a278fe851afaa5da09 --- /dev/null +++ b/node_modules/path-parse/package.json @@ -0,0 +1,33 @@ +{ + "name": "path-parse", + "version": "1.0.7", + "description": "Node.js path.parse() ponyfill", + "main": "index.js", + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/jbgutierrez/path-parse.git" + }, + "keywords": [ + "path", + "paths", + "file", + "dir", + "parse", + "built-in", + "util", + "utils", + "core", + "ponyfill", + "polyfill", + "shim" + ], + "author": "Javier Blanco ", + "license": "MIT", + "bugs": { + "url": "https://github.com/jbgutierrez/path-parse/issues" + }, + "homepage": "https://github.com/jbgutierrez/path-parse#readme" +} diff --git a/node_modules/path-to-regexp/LICENSE b/node_modules/path-to-regexp/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..983fbe8aec3f4e2d4add592bb1083b00d7366f66 --- /dev/null +++ b/node_modules/path-to-regexp/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/path-to-regexp/Readme.md b/node_modules/path-to-regexp/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..f5df40a9adbcaaff172645e21defd845a0c21deb --- /dev/null +++ b/node_modules/path-to-regexp/Readme.md @@ -0,0 +1,224 @@ +# Path-to-RegExp + +> Turn a path string such as `/user/:name` into a regular expression. + +[![NPM version][npm-image]][npm-url] +[![NPM downloads][downloads-image]][downloads-url] +[![Build status][build-image]][build-url] +[![Build coverage][coverage-image]][coverage-url] +[![License][license-image]][license-url] + +## Installation + +``` +npm install path-to-regexp --save +``` + +## Usage + +```js +const { + match, + pathToRegexp, + compile, + parse, + stringify, +} = require("path-to-regexp"); +``` + +### Parameters + +Parameters match arbitrary strings in a path by matching up to the end of the segment, or up to any proceeding tokens. They are defined by prefixing a colon to the parameter name (`:foo`). Parameter names can use any valid JavaScript identifier, or be double quoted to use other characters (`:"param-name"`). + +```js +const fn = match("/:foo/:bar"); + +fn("/test/route"); +//=> { path: '/test/route', params: { foo: 'test', bar: 'route' } } +``` + +### Wildcard + +Wildcard parameters match one or more characters across multiple segments. They are defined the same way as regular parameters, but are prefixed with an asterisk (`*foo`). + +```js +const fn = match("/*splat"); + +fn("/bar/baz"); +//=> { path: '/bar/baz', params: { splat: [ 'bar', 'baz' ] } } +``` + +### Optional + +Braces can be used to define parts of the path that are optional. + +```js +const fn = match("/users{/:id}/delete"); + +fn("/users/delete"); +//=> { path: '/users/delete', params: {} } + +fn("/users/123/delete"); +//=> { path: '/users/123/delete', params: { id: '123' } } +``` + +## Match + +The `match` function returns a function for matching strings against a path: + +- **path** String, `TokenData` object, or array of strings and `TokenData` objects. +- **options** _(optional)_ (Extends [pathToRegexp](#pathToRegexp) options) + - **decode** Function for decoding strings to params, or `false` to disable all processing. (default: `decodeURIComponent`) + +```js +const fn = match("/foo/:bar"); +``` + +**Please note:** `path-to-regexp` is intended for ordered data (e.g. paths, hosts). It can not handle arbitrarily ordered data (e.g. query strings, URL fragments, JSON, etc). + +## PathToRegexp + +The `pathToRegexp` function returns the `regexp` for matching strings against paths, and an array of `keys` for understanding the `RegExp#exec` matches. + +- **path** String, `TokenData` object, or array of strings and `TokenData` objects. +- **options** _(optional)_ (See [parse](#parse) for more options) + - **sensitive** Regexp will be case sensitive. (default: `false`) + - **end** Validate the match reaches the end of the string. (default: `true`) + - **delimiter** The default delimiter for segments, e.g. `[^/]` for `:named` parameters. (default: `'/'`) + - **trailing** Allows optional trailing delimiter to match. (default: `true`) + +```js +const { regexp, keys } = pathToRegexp("/foo/:bar"); + +regexp.exec("/foo/123"); //=> ["/foo/123", "123"] +``` + +## Compile ("Reverse" Path-To-RegExp) + +The `compile` function will return a function for transforming parameters into a valid path: + +- **path** A string or `TokenData` object. +- **options** (See [parse](#parse) for more options) + - **delimiter** The default delimiter for segments, e.g. `[^/]` for `:named` parameters. (default: `'/'`) + - **encode** Function for encoding input strings for output into the path, or `false` to disable entirely. (default: `encodeURIComponent`) + +```js +const toPath = compile("/user/:id"); + +toPath({ id: "name" }); //=> "/user/name" +toPath({ id: "café" }); //=> "/user/caf%C3%A9" + +const toPathRepeated = compile("/*segment"); + +toPathRepeated({ segment: ["foo"] }); //=> "/foo" +toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c" + +// When disabling `encode`, you need to make sure inputs are encoded correctly. No arrays are accepted. +const toPathRaw = compile("/user/:id", { encode: false }); + +toPathRaw({ id: "%3A%2F" }); //=> "/user/%3A%2F" +``` + +## Stringify + +Transform a `TokenData` object to a Path-to-RegExp string. + +- **data** A `TokenData` object. + +```js +const data = { + tokens: [ + { type: "text", value: "/" }, + { type: "param", name: "foo" }, + ], +}; + +const path = stringify(data); //=> "/:foo" +``` + +## Developers + +- If you are rewriting paths with match and compile, consider using `encode: false` and `decode: false` to keep raw paths passed around. +- To ensure matches work on paths containing characters usually encoded, such as emoji, consider using [encodeurl](https://github.com/pillarjs/encodeurl) for `encodePath`. + +### Parse + +The `parse` function accepts a string and returns `TokenData`, which can be used with `match` and `compile`. + +- **path** A string. +- **options** _(optional)_ + - **encodePath** A function for encoding input strings. (default: `x => x`, recommended: [`encodeurl`](https://github.com/pillarjs/encodeurl)) + +### Tokens + +`TokenData` has two properties: + +- **tokens** A sequence of tokens, currently of types `text`, `parameter`, `wildcard`, or `group`. +- **originalPath** The original path used with `parse`, shown in error messages to assist debugging. + +### Custom path + +In some applications you may not be able to use the `path-to-regexp` syntax, but you still want to use this library for `match` and `compile`. For example: + +```js +import { match } from "path-to-regexp"; + +const tokens = [ + { type: "text", value: "/" }, + { type: "parameter", name: "foo" }, +]; +const originalPath = "/[foo]"; // To help debug error messages. +const path = { tokens, originalPath }; +const fn = match(path); + +fn("/test"); //=> { path: '/test', index: 0, params: { foo: 'test' } } +``` + +## Errors + +An effort has been made to ensure ambiguous paths from previous releases throw an error. This means you might be seeing an error when things worked before. + +### Missing parameter name + +Parameter names must be provided after `:` or `*`, for example `/*path`. They can be valid JavaScript identifiers (e.g. `:myName`) or JSON strings (`:"my-name"`). + +### Unexpected `?` or `+` + +In past releases, `?`, `*`, and `+` were used to denote optional or repeating parameters. As an alternative, try these: + +- For optional (`?`), use braces: `/file{.:ext}`. +- For one or more (`+`), use a wildcard: `/*path`. +- For zero or more (`*`), use both: `/files{/*path}`. + +### Unexpected `(`, `)`, `[`, `]`, etc. + +Previous versions of Path-to-RegExp used these for RegExp features. This version no longer supports them so they've been reserved to avoid ambiguity. To match these characters literally, escape them with a backslash, e.g. `"\\("`. + +### Unterminated quote + +Parameter names can be wrapped in double quote characters, and this error means you forgot to close the quote character. For example, `:"foo`. + +### Express <= 4.x + +Path-To-RegExp breaks compatibility with Express <= `4.x` in the following ways: + +- The wildcard `*` must have a name and matches the behavior of parameters `:`. +- The optional character `?` is no longer supported, use braces instead: `/:file{.:ext}`. +- Regexp characters are not supported. +- Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`). +- Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`. + +## License + +MIT + +[npm-image]: https://img.shields.io/npm/v/path-to-regexp +[npm-url]: https://npmjs.org/package/path-to-regexp +[downloads-image]: https://img.shields.io/npm/dm/path-to-regexp +[downloads-url]: https://npmjs.org/package/path-to-regexp +[build-image]: https://img.shields.io/github/actions/workflow/status/pillarjs/path-to-regexp/ci.yml?branch=master +[build-url]: https://github.com/pillarjs/path-to-regexp/actions/workflows/ci.yml?query=branch%3Amaster +[coverage-image]: https://img.shields.io/codecov/c/gh/pillarjs/path-to-regexp +[coverage-url]: https://codecov.io/gh/pillarjs/path-to-regexp +[license-image]: http://img.shields.io/npm/l/path-to-regexp.svg?style=flat +[license-url]: LICENSE.md diff --git a/node_modules/path-to-regexp/dist/index.d.ts b/node_modules/path-to-regexp/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b59dff0e2901335e6b36a901b13b2d080d8619b1 --- /dev/null +++ b/node_modules/path-to-regexp/dist/index.d.ts @@ -0,0 +1,144 @@ +/** + * Encode a string into another string. + */ +export type Encode = (value: string) => string; +/** + * Decode a string into another string. + */ +export type Decode = (value: string) => string; +export interface ParseOptions { + /** + * A function for encoding input strings. + */ + encodePath?: Encode; +} +export interface PathToRegexpOptions { + /** + * Matches the path completely without trailing characters. (default: `true`) + */ + end?: boolean; + /** + * Allows optional trailing delimiter to match. (default: `true`) + */ + trailing?: boolean; + /** + * Match will be case sensitive. (default: `false`) + */ + sensitive?: boolean; + /** + * The default delimiter for segments. (default: `'/'`) + */ + delimiter?: string; +} +export interface MatchOptions extends PathToRegexpOptions { + /** + * Function for decoding strings for params, or `false` to disable entirely. (default: `decodeURIComponent`) + */ + decode?: Decode | false; +} +export interface CompileOptions { + /** + * Function for encoding input strings for output into the path, or `false` to disable entirely. (default: `encodeURIComponent`) + */ + encode?: Encode | false; + /** + * The default delimiter for segments. (default: `'/'`) + */ + delimiter?: string; +} +/** + * Plain text. + */ +export interface Text { + type: "text"; + value: string; +} +/** + * A parameter designed to match arbitrary text within a segment. + */ +export interface Parameter { + type: "param"; + name: string; +} +/** + * A wildcard parameter designed to match multiple segments. + */ +export interface Wildcard { + type: "wildcard"; + name: string; +} +/** + * A set of possible tokens to expand when matching. + */ +export interface Group { + type: "group"; + tokens: Token[]; +} +/** + * A token that corresponds with a regexp capture. + */ +export type Key = Parameter | Wildcard; +/** + * A sequence of `path-to-regexp` keys that match capturing groups. + */ +export type Keys = Array; +/** + * A sequence of path match characters. + */ +export type Token = Text | Parameter | Wildcard | Group; +/** + * Tokenized path instance. + */ +export declare class TokenData { + readonly tokens: Token[]; + readonly originalPath?: string | undefined; + constructor(tokens: Token[], originalPath?: string | undefined); +} +/** + * ParseError is thrown when there is an error processing the path. + */ +export declare class PathError extends TypeError { + readonly originalPath: string | undefined; + constructor(message: string, originalPath: string | undefined); +} +/** + * Parse a string for the raw tokens. + */ +export declare function parse(str: string, options?: ParseOptions): TokenData; +/** + * Compile a string to a template function for the path. + */ +export declare function compile

(path: Path, options?: CompileOptions & ParseOptions): (params?: P) => string; +export type ParamData = Partial>; +export type PathFunction

= (data?: P) => string; +/** + * A match result contains data about the path match. + */ +export interface MatchResult

{ + path: string; + params: P; +} +/** + * A match is either `false` (no match) or a match result. + */ +export type Match

= false | MatchResult

; +/** + * The match function takes a string and returns whether it matched the path. + */ +export type MatchFunction

= (path: string) => Match

; +/** + * Supported path types. + */ +export type Path = string | TokenData; +/** + * Transform a path into a match function. + */ +export declare function match

(path: Path | Path[], options?: MatchOptions & ParseOptions): MatchFunction

; +export declare function pathToRegexp(path: Path | Path[], options?: PathToRegexpOptions & ParseOptions): { + regexp: RegExp; + keys: Keys; +}; +/** + * Stringify token data into a path string. + */ +export declare function stringify(data: TokenData): string; diff --git a/node_modules/path-to-regexp/dist/index.js b/node_modules/path-to-regexp/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9331ae06722aa7c9642620135b1f71520bde8d63 --- /dev/null +++ b/node_modules/path-to-regexp/dist/index.js @@ -0,0 +1,409 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PathError = exports.TokenData = void 0; +exports.parse = parse; +exports.compile = compile; +exports.match = match; +exports.pathToRegexp = pathToRegexp; +exports.stringify = stringify; +const DEFAULT_DELIMITER = "/"; +const NOOP_VALUE = (value) => value; +const ID_START = /^[$_\p{ID_Start}]$/u; +const ID_CONTINUE = /^[$\u200c\u200d\p{ID_Continue}]$/u; +const SIMPLE_TOKENS = { + // Groups. + "{": "{", + "}": "}", + // Reserved. + "(": "(", + ")": ")", + "[": "[", + "]": "]", + "+": "+", + "?": "?", + "!": "!", +}; +/** + * Escape text for stringify to path. + */ +function escapeText(str) { + return str.replace(/[{}()\[\]+?!:*\\]/g, "\\$&"); +} +/** + * Escape a regular expression string. + */ +function escape(str) { + return str.replace(/[.+*?^${}()[\]|/\\]/g, "\\$&"); +} +/** + * Tokenized path instance. + */ +class TokenData { + constructor(tokens, originalPath) { + this.tokens = tokens; + this.originalPath = originalPath; + } +} +exports.TokenData = TokenData; +/** + * ParseError is thrown when there is an error processing the path. + */ +class PathError extends TypeError { + constructor(message, originalPath) { + let text = message; + if (originalPath) + text += `: ${originalPath}`; + text += `; visit https://git.new/pathToRegexpError for info`; + super(text); + this.originalPath = originalPath; + } +} +exports.PathError = PathError; +/** + * Parse a string for the raw tokens. + */ +function parse(str, options = {}) { + const { encodePath = NOOP_VALUE } = options; + const chars = [...str]; + const tokens = []; + let index = 0; + let pos = 0; + function name() { + let value = ""; + if (ID_START.test(chars[index])) { + do { + value += chars[index++]; + } while (ID_CONTINUE.test(chars[index])); + } + else if (chars[index] === '"') { + let quoteStart = index; + while (index++ < chars.length) { + if (chars[index] === '"') { + index++; + quoteStart = 0; + break; + } + // Increment over escape characters. + if (chars[index] === "\\") + index++; + value += chars[index]; + } + if (quoteStart) { + throw new PathError(`Unterminated quote at index ${quoteStart}`, str); + } + } + if (!value) { + throw new PathError(`Missing parameter name at index ${index}`, str); + } + return value; + } + while (index < chars.length) { + const value = chars[index]; + const type = SIMPLE_TOKENS[value]; + if (type) { + tokens.push({ type, index: index++, value }); + } + else if (value === "\\") { + tokens.push({ type: "escape", index: index++, value: chars[index++] }); + } + else if (value === ":") { + tokens.push({ type: "param", index: index++, value: name() }); + } + else if (value === "*") { + tokens.push({ type: "wildcard", index: index++, value: name() }); + } + else { + tokens.push({ type: "char", index: index++, value }); + } + } + tokens.push({ type: "end", index, value: "" }); + function consumeUntil(endType) { + const output = []; + while (true) { + const token = tokens[pos++]; + if (token.type === endType) + break; + if (token.type === "char" || token.type === "escape") { + let path = token.value; + let cur = tokens[pos]; + while (cur.type === "char" || cur.type === "escape") { + path += cur.value; + cur = tokens[++pos]; + } + output.push({ + type: "text", + value: encodePath(path), + }); + continue; + } + if (token.type === "param" || token.type === "wildcard") { + output.push({ + type: token.type, + name: token.value, + }); + continue; + } + if (token.type === "{") { + output.push({ + type: "group", + tokens: consumeUntil("}"), + }); + continue; + } + throw new PathError(`Unexpected ${token.type} at index ${token.index}, expected ${endType}`, str); + } + return output; + } + return new TokenData(consumeUntil("end"), str); +} +/** + * Compile a string to a template function for the path. + */ +function compile(path, options = {}) { + const { encode = encodeURIComponent, delimiter = DEFAULT_DELIMITER } = options; + const data = typeof path === "object" ? path : parse(path, options); + const fn = tokensToFunction(data.tokens, delimiter, encode); + return function path(params = {}) { + const [path, ...missing] = fn(params); + if (missing.length) { + throw new TypeError(`Missing parameters: ${missing.join(", ")}`); + } + return path; + }; +} +function tokensToFunction(tokens, delimiter, encode) { + const encoders = tokens.map((token) => tokenToFunction(token, delimiter, encode)); + return (data) => { + const result = [""]; + for (const encoder of encoders) { + const [value, ...extras] = encoder(data); + result[0] += value; + result.push(...extras); + } + return result; + }; +} +/** + * Convert a single token into a path building function. + */ +function tokenToFunction(token, delimiter, encode) { + if (token.type === "text") + return () => [token.value]; + if (token.type === "group") { + const fn = tokensToFunction(token.tokens, delimiter, encode); + return (data) => { + const [value, ...missing] = fn(data); + if (!missing.length) + return [value]; + return [""]; + }; + } + const encodeValue = encode || NOOP_VALUE; + if (token.type === "wildcard" && encode !== false) { + return (data) => { + const value = data[token.name]; + if (value == null) + return ["", token.name]; + if (!Array.isArray(value) || value.length === 0) { + throw new TypeError(`Expected "${token.name}" to be a non-empty array`); + } + return [ + value + .map((value, index) => { + if (typeof value !== "string") { + throw new TypeError(`Expected "${token.name}/${index}" to be a string`); + } + return encodeValue(value); + }) + .join(delimiter), + ]; + }; + } + return (data) => { + const value = data[token.name]; + if (value == null) + return ["", token.name]; + if (typeof value !== "string") { + throw new TypeError(`Expected "${token.name}" to be a string`); + } + return [encodeValue(value)]; + }; +} +/** + * Transform a path into a match function. + */ +function match(path, options = {}) { + const { decode = decodeURIComponent, delimiter = DEFAULT_DELIMITER } = options; + const { regexp, keys } = pathToRegexp(path, options); + const decoders = keys.map((key) => { + if (decode === false) + return NOOP_VALUE; + if (key.type === "param") + return decode; + return (value) => value.split(delimiter).map(decode); + }); + return function match(input) { + const m = regexp.exec(input); + if (!m) + return false; + const path = m[0]; + const params = Object.create(null); + for (let i = 1; i < m.length; i++) { + if (m[i] === undefined) + continue; + const key = keys[i - 1]; + const decoder = decoders[i - 1]; + params[key.name] = decoder(m[i]); + } + return { path, params }; + }; +} +function pathToRegexp(path, options = {}) { + const { delimiter = DEFAULT_DELIMITER, end = true, sensitive = false, trailing = true, } = options; + const keys = []; + const flags = sensitive ? "" : "i"; + const sources = []; + for (const input of pathsToArray(path, [])) { + const data = typeof input === "object" ? input : parse(input, options); + for (const tokens of flatten(data.tokens, 0, [])) { + sources.push(toRegExpSource(tokens, delimiter, keys, data.originalPath)); + } + } + let pattern = `^(?:${sources.join("|")})`; + if (trailing) + pattern += `(?:${escape(delimiter)}$)?`; + pattern += end ? "$" : `(?=${escape(delimiter)}|$)`; + const regexp = new RegExp(pattern, flags); + return { regexp, keys }; +} +/** + * Convert a path or array of paths into a flat array. + */ +function pathsToArray(paths, init) { + if (Array.isArray(paths)) { + for (const p of paths) + pathsToArray(p, init); + } + else { + init.push(paths); + } + return init; +} +/** + * Generate a flat list of sequence tokens from the given tokens. + */ +function* flatten(tokens, index, init) { + if (index === tokens.length) { + return yield init; + } + const token = tokens[index]; + if (token.type === "group") { + for (const seq of flatten(token.tokens, 0, init.slice())) { + yield* flatten(tokens, index + 1, seq); + } + } + else { + init.push(token); + } + yield* flatten(tokens, index + 1, init); +} +/** + * Transform a flat sequence of tokens into a regular expression. + */ +function toRegExpSource(tokens, delimiter, keys, originalPath) { + let result = ""; + let backtrack = ""; + let isSafeSegmentParam = true; + for (const token of tokens) { + if (token.type === "text") { + result += escape(token.value); + backtrack += token.value; + isSafeSegmentParam || (isSafeSegmentParam = token.value.includes(delimiter)); + continue; + } + if (token.type === "param" || token.type === "wildcard") { + if (!isSafeSegmentParam && !backtrack) { + throw new PathError(`Missing text before "${token.name}" ${token.type}`, originalPath); + } + if (token.type === "param") { + result += `(${negate(delimiter, isSafeSegmentParam ? "" : backtrack)}+)`; + } + else { + result += `([\\s\\S]+)`; + } + keys.push(token); + backtrack = ""; + isSafeSegmentParam = false; + continue; + } + } + return result; +} +/** + * Block backtracking on previous text and ignore delimiter string. + */ +function negate(delimiter, backtrack) { + if (backtrack.length < 2) { + if (delimiter.length < 2) + return `[^${escape(delimiter + backtrack)}]`; + return `(?:(?!${escape(delimiter)})[^${escape(backtrack)}])`; + } + if (delimiter.length < 2) { + return `(?:(?!${escape(backtrack)})[^${escape(delimiter)}])`; + } + return `(?:(?!${escape(backtrack)}|${escape(delimiter)})[\\s\\S])`; +} +/** + * Stringify an array of tokens into a path string. + */ +function stringifyTokens(tokens) { + let value = ""; + let i = 0; + function name(value) { + const isSafe = isNameSafe(value) && isNextNameSafe(tokens[i]); + return isSafe ? value : JSON.stringify(value); + } + while (i < tokens.length) { + const token = tokens[i++]; + if (token.type === "text") { + value += escapeText(token.value); + continue; + } + if (token.type === "group") { + value += `{${stringifyTokens(token.tokens)}}`; + continue; + } + if (token.type === "param") { + value += `:${name(token.name)}`; + continue; + } + if (token.type === "wildcard") { + value += `*${name(token.name)}`; + continue; + } + throw new TypeError(`Unknown token type: ${token.type}`); + } + return value; +} +/** + * Stringify token data into a path string. + */ +function stringify(data) { + return stringifyTokens(data.tokens); +} +/** + * Validate the parameter name contains valid ID characters. + */ +function isNameSafe(name) { + const [first, ...rest] = name; + return ID_START.test(first) && rest.every((char) => ID_CONTINUE.test(char)); +} +/** + * Validate the next token does not interfere with the current param name. + */ +function isNextNameSafe(token) { + if (token && token.type === "text") + return !ID_CONTINUE.test(token.value[0]); + return true; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/path-to-regexp/dist/index.js.map b/node_modules/path-to-regexp/dist/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ec14c730a6dc131a198d6d7c0de206dddbc6b5f6 --- /dev/null +++ b/node_modules/path-to-regexp/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AA4LA,sBA8GC;AAKD,0BAgBC;AAgHD,sBA+BC;AAED,oCA2BC;AAmJD,8BAEC;AAhoBD,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,UAAU,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,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M,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;IAC9B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AAC9E,CAAC;AAED;;GAEG;AACH,SAAS,cAAc,CAAC,KAAwB;IAC9C,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC7E,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["const DEFAULT_DELIMITER = \"/\";\nconst NOOP_VALUE = (value: string) => value;\nconst ID_START = /^[$_\\p{ID_Start}]$/u;\nconst ID_CONTINUE = /^[$\\u200c\\u200d\\p{ID_Continue}]$/u;\n\n/**\n * Encode a string into another string.\n */\nexport type Encode = (value: string) => string;\n\n/**\n * Decode a string into another string.\n */\nexport type Decode = (value: string) => string;\n\nexport interface ParseOptions {\n /**\n * A function for encoding input strings.\n */\n encodePath?: Encode;\n}\n\nexport interface PathToRegexpOptions {\n /**\n * Matches the path completely without trailing characters. (default: `true`)\n */\n end?: boolean;\n /**\n * Allows optional trailing delimiter to match. (default: `true`)\n */\n trailing?: boolean;\n /**\n * Match will be case sensitive. (default: `false`)\n */\n sensitive?: boolean;\n /**\n * The default delimiter for segments. (default: `'/'`)\n */\n delimiter?: string;\n}\n\nexport interface MatchOptions extends PathToRegexpOptions {\n /**\n * Function for decoding strings for params, or `false` to disable entirely. (default: `decodeURIComponent`)\n */\n decode?: Decode | false;\n}\n\nexport interface CompileOptions {\n /**\n * Function for encoding input strings for output into the path, or `false` to disable entirely. (default: `encodeURIComponent`)\n */\n encode?: Encode | false;\n /**\n * The default delimiter for segments. (default: `'/'`)\n */\n delimiter?: string;\n}\n\ntype TokenType =\n | \"{\"\n | \"}\"\n | \"wildcard\"\n | \"param\"\n | \"char\"\n | \"escape\"\n | \"end\"\n // Reserved for use or ambiguous due to past use.\n | \"(\"\n | \")\"\n | \"[\"\n | \"]\"\n | \"+\"\n | \"?\"\n | \"!\";\n\n/**\n * Tokenizer results.\n */\ninterface LexToken {\n type: TokenType;\n index: number;\n value: string;\n}\n\nconst SIMPLE_TOKENS: Record = {\n // Groups.\n \"{\": \"{\",\n \"}\": \"}\",\n // Reserved.\n \"(\": \"(\",\n \")\": \")\",\n \"[\": \"[\",\n \"]\": \"]\",\n \"+\": \"+\",\n \"?\": \"?\",\n \"!\": \"!\",\n};\n\n/**\n * Escape text for stringify to path.\n */\nfunction escapeText(str: string) {\n return str.replace(/[{}()\\[\\]+?!:*\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Escape a regular expression string.\n */\nfunction escape(str: string) {\n return str.replace(/[.+*?^${}()[\\]|/\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Plain text.\n */\nexport interface Text {\n type: \"text\";\n value: string;\n}\n\n/**\n * A parameter designed to match arbitrary text within a segment.\n */\nexport interface Parameter {\n type: \"param\";\n name: string;\n}\n\n/**\n * A wildcard parameter designed to match multiple segments.\n */\nexport interface Wildcard {\n type: \"wildcard\";\n name: string;\n}\n\n/**\n * A set of possible tokens to expand when matching.\n */\nexport interface Group {\n type: \"group\";\n tokens: Token[];\n}\n\n/**\n * A token that corresponds with a regexp capture.\n */\nexport type Key = Parameter | Wildcard;\n\n/**\n * A sequence of `path-to-regexp` keys that match capturing groups.\n */\nexport type Keys = Array;\n\n/**\n * A sequence of path match characters.\n */\nexport type Token = Text | Parameter | Wildcard | Group;\n\n/**\n * Tokenized path instance.\n */\nexport class TokenData {\n constructor(\n public readonly tokens: Token[],\n public readonly originalPath?: string,\n ) {}\n}\n\n/**\n * ParseError is thrown when there is an error processing the path.\n */\nexport class PathError extends TypeError {\n constructor(\n message: string,\n public readonly originalPath: string | undefined,\n ) {\n let text = message;\n if (originalPath) text += `: ${originalPath}`;\n text += `; visit https://git.new/pathToRegexpError for info`;\n super(text);\n }\n}\n\n/**\n * Parse a string for the raw tokens.\n */\nexport function parse(str: string, options: ParseOptions = {}): TokenData {\n const { encodePath = NOOP_VALUE } = options;\n const chars = [...str];\n const tokens: Array = [];\n let index = 0;\n let pos = 0;\n\n function name() {\n let value = \"\";\n\n if (ID_START.test(chars[index])) {\n do {\n value += chars[index++];\n } while (ID_CONTINUE.test(chars[index]));\n } else if (chars[index] === '\"') {\n let quoteStart = index;\n\n while (index++ < chars.length) {\n if (chars[index] === '\"') {\n index++;\n quoteStart = 0;\n break;\n }\n\n // Increment over escape characters.\n if (chars[index] === \"\\\\\") index++;\n\n value += chars[index];\n }\n\n if (quoteStart) {\n throw new PathError(`Unterminated quote at index ${quoteStart}`, str);\n }\n }\n\n if (!value) {\n throw new PathError(`Missing parameter name at index ${index}`, str);\n }\n\n return value;\n }\n\n while (index < chars.length) {\n const value = chars[index];\n const type = SIMPLE_TOKENS[value];\n\n if (type) {\n tokens.push({ type, index: index++, value });\n } else if (value === \"\\\\\") {\n tokens.push({ type: \"escape\", index: index++, value: chars[index++] });\n } else if (value === \":\") {\n tokens.push({ type: \"param\", index: index++, value: name() });\n } else if (value === \"*\") {\n tokens.push({ type: \"wildcard\", index: index++, value: name() });\n } else {\n tokens.push({ type: \"char\", index: index++, value });\n }\n }\n\n tokens.push({ type: \"end\", index, value: \"\" });\n\n function consumeUntil(endType: TokenType): Token[] {\n const output: Token[] = [];\n\n while (true) {\n const token = tokens[pos++];\n if (token.type === endType) break;\n\n if (token.type === \"char\" || token.type === \"escape\") {\n let path = token.value;\n let cur = tokens[pos];\n\n while (cur.type === \"char\" || cur.type === \"escape\") {\n path += cur.value;\n cur = tokens[++pos];\n }\n\n output.push({\n type: \"text\",\n value: encodePath(path),\n });\n continue;\n }\n\n if (token.type === \"param\" || token.type === \"wildcard\") {\n output.push({\n type: token.type,\n name: token.value,\n });\n continue;\n }\n\n if (token.type === \"{\") {\n output.push({\n type: \"group\",\n tokens: consumeUntil(\"}\"),\n });\n continue;\n }\n\n throw new PathError(\n `Unexpected ${token.type} at index ${token.index}, expected ${endType}`,\n str,\n );\n }\n\n return output;\n }\n\n return new TokenData(consumeUntil(\"end\"), str);\n}\n\n/**\n * Compile a string to a template function for the path.\n */\nexport function compile

(\n path: Path,\n options: CompileOptions & ParseOptions = {},\n) {\n const { encode = encodeURIComponent, delimiter = DEFAULT_DELIMITER } =\n options;\n const data = typeof path === \"object\" ? path : parse(path, options);\n const fn = tokensToFunction(data.tokens, delimiter, encode);\n\n return function path(params: P = {} as P) {\n const [path, ...missing] = fn(params);\n if (missing.length) {\n throw new TypeError(`Missing parameters: ${missing.join(\", \")}`);\n }\n return path;\n };\n}\n\nexport type ParamData = Partial>;\nexport type PathFunction

= (data?: P) => string;\n\nfunction tokensToFunction(\n tokens: Token[],\n delimiter: string,\n encode: Encode | false,\n) {\n const encoders = tokens.map((token) =>\n tokenToFunction(token, delimiter, encode),\n );\n\n return (data: ParamData) => {\n const result: string[] = [\"\"];\n\n for (const encoder of encoders) {\n const [value, ...extras] = encoder(data);\n result[0] += value;\n result.push(...extras);\n }\n\n return result;\n };\n}\n\n/**\n * Convert a single token into a path building function.\n */\nfunction tokenToFunction(\n token: Token,\n delimiter: string,\n encode: Encode | false,\n): (data: ParamData) => string[] {\n if (token.type === \"text\") return () => [token.value];\n\n if (token.type === \"group\") {\n const fn = tokensToFunction(token.tokens, delimiter, encode);\n\n return (data) => {\n const [value, ...missing] = fn(data);\n if (!missing.length) return [value];\n return [\"\"];\n };\n }\n\n const encodeValue = encode || NOOP_VALUE;\n\n if (token.type === \"wildcard\" && encode !== false) {\n return (data) => {\n const value = data[token.name];\n if (value == null) return [\"\", token.name];\n\n if (!Array.isArray(value) || value.length === 0) {\n throw new TypeError(`Expected \"${token.name}\" to be a non-empty array`);\n }\n\n return [\n value\n .map((value, index) => {\n if (typeof value !== \"string\") {\n throw new TypeError(\n `Expected \"${token.name}/${index}\" to be a string`,\n );\n }\n\n return encodeValue(value);\n })\n .join(delimiter),\n ];\n };\n }\n\n return (data) => {\n const value = data[token.name];\n if (value == null) return [\"\", token.name];\n\n if (typeof value !== \"string\") {\n throw new TypeError(`Expected \"${token.name}\" to be a string`);\n }\n\n return [encodeValue(value)];\n };\n}\n\n/**\n * A match result contains data about the path match.\n */\nexport interface MatchResult

{\n path: string;\n params: P;\n}\n\n/**\n * A match is either `false` (no match) or a match result.\n */\nexport type Match

= false | MatchResult

;\n\n/**\n * The match function takes a string and returns whether it matched the path.\n */\nexport type MatchFunction

= (path: string) => Match

;\n\n/**\n * Supported path types.\n */\nexport type Path = string | TokenData;\n\n/**\n * Transform a path into a match function.\n */\nexport function match

(\n path: Path | Path[],\n options: MatchOptions & ParseOptions = {},\n): MatchFunction

{\n const { decode = decodeURIComponent, delimiter = DEFAULT_DELIMITER } =\n options;\n const { regexp, keys } = pathToRegexp(path, options);\n\n const decoders = keys.map((key) => {\n if (decode === false) return NOOP_VALUE;\n if (key.type === \"param\") return decode;\n return (value: string) => value.split(delimiter).map(decode);\n });\n\n return function match(input: string) {\n const m = regexp.exec(input);\n if (!m) return false;\n\n const path = m[0];\n const params = Object.create(null);\n\n for (let i = 1; i < m.length; i++) {\n if (m[i] === undefined) continue;\n\n const key = keys[i - 1];\n const decoder = decoders[i - 1];\n params[key.name] = decoder(m[i]);\n }\n\n return { path, params };\n };\n}\n\nexport function pathToRegexp(\n path: Path | Path[],\n options: PathToRegexpOptions & ParseOptions = {},\n) {\n const {\n delimiter = DEFAULT_DELIMITER,\n end = true,\n sensitive = false,\n trailing = true,\n } = options;\n const keys: Keys = [];\n const flags = sensitive ? \"\" : \"i\";\n const sources: string[] = [];\n\n for (const input of pathsToArray(path, [])) {\n const data = typeof input === \"object\" ? input : parse(input, options);\n for (const tokens of flatten(data.tokens, 0, [])) {\n sources.push(toRegExpSource(tokens, delimiter, keys, data.originalPath));\n }\n }\n\n let pattern = `^(?:${sources.join(\"|\")})`;\n if (trailing) pattern += `(?:${escape(delimiter)}$)?`;\n pattern += end ? \"$\" : `(?=${escape(delimiter)}|$)`;\n\n const regexp = new RegExp(pattern, flags);\n return { regexp, keys };\n}\n\n/**\n * Convert a path or array of paths into a flat array.\n */\nfunction pathsToArray(paths: Path | Path[], init: Path[]): Path[] {\n if (Array.isArray(paths)) {\n for (const p of paths) pathsToArray(p, init);\n } else {\n init.push(paths);\n }\n return init;\n}\n\n/**\n * Flattened token set.\n */\ntype FlatToken = Text | Parameter | Wildcard;\n\n/**\n * Generate a flat list of sequence tokens from the given tokens.\n */\nfunction* flatten(\n tokens: Token[],\n index: number,\n init: FlatToken[],\n): Generator {\n if (index === tokens.length) {\n return yield init;\n }\n\n const token = tokens[index];\n\n if (token.type === \"group\") {\n for (const seq of flatten(token.tokens, 0, init.slice())) {\n yield* flatten(tokens, index + 1, seq);\n }\n } else {\n init.push(token);\n }\n\n yield* flatten(tokens, index + 1, init);\n}\n\n/**\n * Transform a flat sequence of tokens into a regular expression.\n */\nfunction toRegExpSource(\n tokens: FlatToken[],\n delimiter: string,\n keys: Keys,\n originalPath: string | undefined,\n): string {\n let result = \"\";\n let backtrack = \"\";\n let isSafeSegmentParam = true;\n\n for (const token of tokens) {\n if (token.type === \"text\") {\n result += escape(token.value);\n backtrack += token.value;\n isSafeSegmentParam ||= token.value.includes(delimiter);\n continue;\n }\n\n if (token.type === \"param\" || token.type === \"wildcard\") {\n if (!isSafeSegmentParam && !backtrack) {\n throw new PathError(\n `Missing text before \"${token.name}\" ${token.type}`,\n originalPath,\n );\n }\n\n if (token.type === \"param\") {\n result += `(${negate(delimiter, isSafeSegmentParam ? \"\" : backtrack)}+)`;\n } else {\n result += `([\\\\s\\\\S]+)`;\n }\n\n keys.push(token);\n backtrack = \"\";\n isSafeSegmentParam = false;\n continue;\n }\n }\n\n return result;\n}\n\n/**\n * Block backtracking on previous text and ignore delimiter string.\n */\nfunction negate(delimiter: string, backtrack: string): string {\n if (backtrack.length < 2) {\n if (delimiter.length < 2) return `[^${escape(delimiter + backtrack)}]`;\n return `(?:(?!${escape(delimiter)})[^${escape(backtrack)}])`;\n }\n if (delimiter.length < 2) {\n return `(?:(?!${escape(backtrack)})[^${escape(delimiter)}])`;\n }\n return `(?:(?!${escape(backtrack)}|${escape(delimiter)})[\\\\s\\\\S])`;\n}\n\n/**\n * Stringify an array of tokens into a path string.\n */\nfunction stringifyTokens(tokens: Token[]): string {\n let value = \"\";\n let i = 0;\n\n function name(value: string) {\n const isSafe = isNameSafe(value) && isNextNameSafe(tokens[i]);\n return isSafe ? value : JSON.stringify(value);\n }\n\n while (i < tokens.length) {\n const token = tokens[i++];\n\n if (token.type === \"text\") {\n value += escapeText(token.value);\n continue;\n }\n\n if (token.type === \"group\") {\n value += `{${stringifyTokens(token.tokens)}}`;\n continue;\n }\n\n if (token.type === \"param\") {\n value += `:${name(token.name)}`;\n continue;\n }\n\n if (token.type === \"wildcard\") {\n value += `*${name(token.name)}`;\n continue;\n }\n\n throw new TypeError(`Unknown token type: ${(token as any).type}`);\n }\n\n return value;\n}\n\n/**\n * Stringify token data into a path string.\n */\nexport function stringify(data: TokenData): string {\n return stringifyTokens(data.tokens);\n}\n\n/**\n * Validate the parameter name contains valid ID characters.\n */\nfunction isNameSafe(name: string): boolean {\n const [first, ...rest] = name;\n return ID_START.test(first) && rest.every((char) => ID_CONTINUE.test(char));\n}\n\n/**\n * Validate the next token does not interfere with the current param name.\n */\nfunction isNextNameSafe(token: Token | undefined): boolean {\n if (token && token.type === \"text\") return !ID_CONTINUE.test(token.value[0]);\n return true;\n}\n"]} \ No newline at end of file diff --git a/node_modules/path-to-regexp/package.json b/node_modules/path-to-regexp/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7ae266ef77f77e7341bfc43d6624a7f80848369e --- /dev/null +++ b/node_modules/path-to-regexp/package.json @@ -0,0 +1,64 @@ +{ + "name": "path-to-regexp", + "version": "8.3.0", + "description": "Express style path to RegExp utility", + "keywords": [ + "express", + "regexp", + "route", + "routing" + ], + "repository": { + "type": "git", + "url": "https://github.com/pillarjs/path-to-regexp.git" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + }, + "license": "MIT", + "exports": "./dist/index.js", + "main": "dist/index.js", + "typings": "dist/index.d.ts", + "files": [ + "dist/" + ], + "scripts": { + "bench": "vitest bench", + "build": "ts-scripts build", + "format": "ts-scripts format", + "lint": "ts-scripts lint", + "prepare": "ts-scripts install && npm run build", + "size": "size-limit", + "specs": "ts-scripts specs", + "test": "ts-scripts test && npm run size" + }, + "devDependencies": { + "@borderless/ts-scripts": "^0.15.0", + "@size-limit/preset-small-lib": "^11.1.2", + "@types/node": "^22.7.2", + "@types/semver": "^7.3.1", + "@vitest/coverage-v8": "^3.0.5", + "recheck": "^4.4.5", + "size-limit": "^11.1.2", + "typescript": "^5.7.3", + "vitest": "^3.0.5" + }, + "publishConfig": { + "access": "public" + }, + "size-limit": [ + { + "path": "dist/index.js", + "limit": "2 kB" + } + ], + "ts-scripts": { + "dist": [ + "dist" + ], + "project": [ + "tsconfig.build.json" + ] + } +} diff --git a/node_modules/pbf/LICENSE b/node_modules/pbf/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7245151df81a0489401451248329a6a491d44f08 --- /dev/null +++ b/node_modules/pbf/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2017, Mapbox +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of pbf nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/pbf/README.md b/node_modules/pbf/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f2bbd0600a84480d721f6a6045e7ee80caa689e9 --- /dev/null +++ b/node_modules/pbf/README.md @@ -0,0 +1,453 @@ +# pbf + +[![Node](https://github.com/mapbox/pbf/actions/workflows/node.yml/badge.svg)](https://github.com/mapbox/pbf/actions/workflows/node.yml) +![Bundle size](https://img.shields.io/bundlephobia/minzip/pbf) + +A low-level, fast, ultra-lightweight (3KB gzipped) JavaScript library for decoding and encoding [protocol buffers](https://developers.google.com/protocol-buffers), a compact binary format for structured data serialization. Works both in Node and the browser. Supports lazy decoding and detailed customization of the reading/writing code. + +## Performance + +This library is extremely fast — much faster than native `JSON.parse`/`JSON.stringify` +and the [protocol-buffers](https://github.com/mafintosh/protocol-buffers) module. +Here's a result from running a real-world benchmark on Node v6.5 +(decoding and encoding a sample of 439 vector tiles, 22.6 MB total): + +- **pbf** decode: 387ms, or 57 MB/s +- **pbf** encode: 396ms, or 56 MB/s +- **protocol-buffers** decode: 837ms, or 26 MB/s +- **protocol-buffers** encode: 4197ms, or 5 MB/s +- **JSON.parse**: 1540ms, or 125 MB/s (parsing an equivalent 77.5 MB JSON file) +- **JSON.stringify**: 607ms, or 49 MB/s + +## Examples + +#### Using Compiled Code + +Install `pbf` and compile a JavaScript module from a `.proto` file: + +```bash +$ npm install -g pbf +$ pbf example.proto > example.js +``` + +Then read and write objects using the module like this: + +```js +var Pbf = require('pbf'); +var Example = require('./example.js').Example; + +// read +var pbf = new Pbf(buffer); +var obj = Example.read(pbf); + +// write +var pbf = new Pbf(); +Example.write(obj, pbf); +var buffer = pbf.finish(); +``` + +Alternatively, you can compile a module directly in the code: + +```js +var compile = require('pbf/compile'); +var schema = require('protocol-buffers-schema'); + +var proto = schema.parse(fs.readFileSync('example.proto')); +var Test = compile(proto).Test; +``` + +If you use `webpack` as your module bundler, you can use [pbf-loader](https://github.com/trivago/pbf-loader) +to load .proto files directly. It returns a compiled module ready to be used. + +Given you already configured your `webpack.config.js`, the code above would look like: +```js +var Pbf = require('pbf'); +var proto = require('./example.proto'); + +var Test = proto.Test; +``` + +#### Custom Reading + +```js +var data = new Pbf(buffer).readFields(readData, {}); + +function readData(tag, data, pbf) { + if (tag === 1) data.name = pbf.readString(); + else if (tag === 2) data.version = pbf.readVarint(); + else if (tag === 3) data.layer = pbf.readMessage(readLayer, {}); +} +function readLayer(tag, layer, pbf) { + if (tag === 1) layer.name = pbf.readString(); + else if (tag === 3) layer.size = pbf.readVarint(); +} +``` + +#### Custom Writing + +```js +var pbf = new Pbf(); +writeData(data, pbf); +var buffer = pbf.finish(); + +function writeData(data, pbf) { + pbf.writeStringField(1, data.name); + pbf.writeVarintField(2, data.version); + pbf.writeMessage(3, writeLayer, data.layer); +} +function writeLayer(layer, pbf) { + pbf.writeStringField(1, layer.name); + pbf.writeVarintField(2, layer.size); +} +``` + +## Install + +Node and Browserify: + +```bash +npm install pbf +``` + +Making a browser build: + +```bash +npm install +npm run build-dev # dist/pbf-dev.js (development build) +npm run build-min # dist/pbf.js (minified production build) +``` + +CDN link: https://unpkg.com/pbf@3.0.5/dist/pbf.js + +## API + +Create a `Pbf` object, optionally given a `Buffer` or `Uint8Array` as input data: + +```js +// parse a pbf file from disk in Node +var pbf = new Pbf(fs.readFileSync('data.pbf')); + +// parse a pbf file in a browser after an ajax request with responseType="arraybuffer" +var pbf = new Pbf(new Uint8Array(xhr.response)); +``` + +`Pbf` object properties: + +```js +pbf.length; // length of the underlying buffer +pbf.pos; // current offset for reading or writing +``` + +#### Reading + +Read a sequence of fields: + +```js +pbf.readFields(function (tag) { + if (tag === 1) pbf.readVarint(); + else if (tag === 2) pbf.readString(); + else ... +}); +``` + +It optionally accepts an object that will be passed to the reading function for easier construction of decoded data, +and also passes the `Pbf` object as a third argument: + +```js +var result = pbf.readFields(callback, {}) + +function callback(tag, result, pbf) { + if (tag === 1) result.id = pbf.readVarint(); +} +``` + +To read an embedded message, use `pbf.readMessage(fn[, obj])` (in the same way as `read`). + +Read values: + +```js +var value = pbf.readVarint(); +var str = pbf.readString(); +var numbers = pbf.readPackedVarint(); +``` + +For lazy or partial decoding, simply save the position instead of reading a value, +then later set it back to the saved value and read: + +```js +var fooPos = -1; +pbf.readFields(function (tag) { + if (tag === 1) fooPos = pbf.pos; +}); +... +pbf.pos = fooPos; +pbf.readMessage(readFoo); +``` + +Scalar reading methods: + +* `readVarint(isSigned)` (pass `true` if you expect negative varints) +* `readSVarint()` +* `readFixed32()` +* `readFixed64()` +* `readSFixed32()` +* `readSFixed64()` +* `readBoolean()` +* `readFloat()` +* `readDouble()` +* `readString()` +* `readBytes()` +* `skip(value)` + +Packed reading methods: + +* `readPackedVarint(arr, isSigned)` (appends read items to `arr`) +* `readPackedSVarint(arr)` +* `readPackedFixed32(arr)` +* `readPackedFixed64(arr)` +* `readPackedSFixed32(arr)` +* `readPackedSFixed64(arr)` +* `readPackedBoolean(arr)` +* `readPackedFloat(arr)` +* `readPackedDouble(arr)` + +#### Writing + +Write values: + +```js +pbf.writeVarint(123); +pbf.writeString("Hello world"); +``` + +Write an embedded message: + +```js +pbf.writeMessage(1, writeObj, obj); + +function writeObj(obj, pbf) { + pbf.writeStringField(obj.name); + pbf.writeVarintField(obj.version); +} +``` + +Field writing methods: + +* `writeVarintField(tag, val)` +* `writeSVarintField(tag, val)` +* `writeFixed32Field(tag, val)` +* `writeFixed64Field(tag, val)` +* `writeSFixed32Field(tag, val)` +* `writeSFixed64Field(tag, val)` +* `writeBooleanField(tag, val)` +* `writeFloatField(tag, val)` +* `writeDoubleField(tag, val)` +* `writeStringField(tag, val)` +* `writeBytesField(tag, buffer)` + +Packed field writing methods: + +* `writePackedVarint(tag, val)` +* `writePackedSVarint(tag, val)` +* `writePackedSFixed32(tag, val)` +* `writePackedSFixed64(tag, val)` +* `writePackedBoolean(tag, val)` +* `writePackedFloat(tag, val)` +* `writePackedDouble(tag, val)` + +Scalar writing methods: + +* `writeVarint(val)` +* `writeSVarint(val)` +* `writeSFixed32(val)` +* `writeSFixed64(val)` +* `writeBoolean(val)` +* `writeFloat(val)` +* `writeDouble(val)` +* `writeString(val)` +* `writeBytes(buffer)` + +Message writing methods: + +* `writeMessage(tag, fn[, obj])` +* `writeRawMessage(fn[, obj])` + +Misc methods: + +* `realloc(minBytes)` - pad the underlying buffer size to accommodate the given number of bytes; + note that the size increases exponentially, so it won't necessarily equal the size of data written +* `finish()` - make the current buffer ready for reading and return the data as a buffer slice +* `destroy()` - dispose the buffer + +For an example of a real-world usage of the library, see [vector-tile-js](https://github.com/mapbox/vector-tile-js). + + +## Proto Schema to JavaScript + +If installed globally, `pbf` provides a binary that compiles `proto` files into JavaScript modules. Usage: + +```bash +$ pbf [--no-write] [--no-read] [--browser] +``` + +The `--no-write` and `--no-read` switches remove corresponding code in the output. +The `--browser` switch makes the module work in browsers instead of Node. + +The resulting module exports each message by name with the following methods: + +* `read(pbf)` - decodes an object from the given `Pbf` instance +* `write(obj, pbf)` - encodes an object into the given `Pbf` instance (usually empty) + +The resulting code is clean and simple, so feel free to customize it. + +## Changelog + +#### 3.2.1 (Oct 11, 2019) + +- Significantly improved performance when decoding large strings in the browser. + +#### 3.2.0 (Mar 11, 2019) + +- Improved decoding to be able to parse repeated fields even if they were specified as packed, and vise versa. +- Improved packed encoding to skip empty arrays (previously, it would write a tag). +- Fixed an off-by-one data corruption bug when writing a message larger than 0x10000000 bytes. + +#### 3.1.0 (Sep 27, 2017) + +- Added support for Protocol Buffer 3 [maps](https://developers.google.com/protocol-buffers/docs/proto3#maps) to proto compiler. + +#### 3.0.5 (Nov 30, 2016) + +- Fixed an error appearing in some versions of IE11 and old Android browsers. + +#### 3.0.4 (Nov 14, 2016) + +- Fixed compiling repeated packed enum fields. + +#### 3.0.3 (Nov 14, 2016) + +- Fixed a regression that broke compiling repeated enum fields with defaults. + +#### 3.0.2 (Sep 30, 2016) + +- Fixed a regression that broke decoding of packed fields with a tag that didn't fit into one byte. + +#### 3.0.1 (Sep 20, 2016) + +- Fixed a regression that broke encoding of long strings. + +#### 3.0.0 (Aug 30, 2016) + +This release include tons of compatibility/robustness fixes, and a more reliable Node implementation. Decoding performance is expected to get up to ~15% slower than v2.0 in Node (browsers are unaffected), but encoding got faster by ~15% in return. + +##### Encoder/decoder + +- **Breaking**: changed Node implementation to use `Uint8Array` instead of `Buffer` internally (and produce corresponding result on `finish()`), making it fully match the browser implementation for consistency and simplicity. +- Fixed `writeVarint` to write `0` when given `NaN` or other non-number to avoid producing a broken Protobuf message. +- Changed `readPacked*` methods signature to accept an optional `arr` argument to append the results to (to support messages with repeated fields that mix packed/non-packed encoding). +- Added an optional `isSigned` argument to `readVarint` that enables proper reading of negative varints. +- Deprecated `readVarint64()` (it still works, but it's recommended to be changed to `readVarint(true)`). +- Faster string encoding. + +##### Proto compiler + +- **Breaking:** Full support for defaults field values (both implicit and explicit); they're now included in the decoded JSON objects. +- Fixed reading of repeated fields with mixed packed/non-packed encoding for compatibility. +- Fixed proto3 compiler to use packed by default for repeated scalar fields. +- Fixed reading of negative varint types. +- Fixed packed fields to decode into `[]` if they're not present. +- Fixed nested message references handling. +- Fixed `packed=false` being interpreted as packed. +- Added a comment to generated code with pbf version number. + +#### 2.0.1 (May 28, 2016) + +- Fixed a regression with `writeVarint` that affected certain numbers. + +#### 2.0.0 (May 28, 2016) + +- Significantly improved the proto compiler, which now produces a much safer reading/writing code. +- Added the ability to compile a read/write module from a protobuf schema directly in the code. +- Proto compiler: fixed name resolutions and collisions in schemas with nested messages. +- Proto compiler: fixed broken top-level enums. + +#### 1.3.7 (May 28, 2016) + +- Fixed a regression with `writeVarint` that affected certain numbers. + +#### 1.3.6 (May 27, 2016) + +- Improved read and write performance (both ~15% faster). +- Improved generated code for default values. + +#### 1.3.5 (Oct 5, 2015) + +- Added support for `syntax` keyword proto files (by updating `resolve-protobuf-schema` dependency). + +#### 1.3.4 (Jul 31, 2015) + +- Added `writeRawMessage` method for writing a message without a tag, useful for creating pbfs with multiple top-level messages. + +#### 1.3.2 (Mar 5, 2015) + +- Added `readVarint64` method for proper decoding of negative `int64`-encoded values. + +#### 1.3.1 (Feb 20, 2015) + +- Fixed pbf proto compile tool generating broken writing code. + +#### 1.3.0 (Feb 5, 2015) + +- Added `pbf` binary that compiles `.proto` files into `Pbf`-based JavaScript modules. + +#### 1.2.0 (Jan 5, 2015) + +##### Breaking API changes + +- Changed `writeMessage` signature to `(tag, fn, obj)` (see example in the docs) + for a huge encoding performance improvement. +- Replaced `readPacked` and `writePacked` methods that accept type as a string + with `readPackedVarint`, etc. for each type (better performance and simpler API). + +##### Improvements + +- 5x faster encoding in Node (vector tile benchmark). +- 40x faster encoding and 3x faster decoding in the browser (vector tile benchmark). + +#### 1.1.4 (Jan 2, 2015) + +- Significantly improved `readPacked` and `writePacked` performance (the tile reading benchmark is now 70% faster). + +#### 1.1.3 (Dec 26, 2014) + +Brings tons of improvements and fixes over the previous version (`0.0.2`). +Basically makes the library complete. + +##### Improvements + +- Improved performance of both reading and writing. +- Made the browser build 3 times smaller. +- Added convenience `readFields` and `readMessage` methods for a much easier reading API. +- Added reading methods: `readFloat`, `readBoolean`, `readSFixed32`, `readSFixed64`. +- Added writing methods: `writeUInt64`, `writeSFixed32`, `writeSFixed64`. +- Improved `readDouble` and `readString` to use native Buffer methods under Node. +- Improved `readString` and `writeString` to use HTML5 `TextEncoder` and `TextDecoder` where available. +- Made `Pbf` `buffer` argument optional. +- Added extensive docs and examples in the readme. +- Added an extensive test suite that brings test coverage up to 100%. + +##### Breaking API changes + +- Renamed `readBuffer`/`writeBuffer` to `readBytes`/`writeBytes`. +- Renamed `readUInt32`/`writeUInt32` to `readFixed32`/`writeFixed32`, etc. +- Renamed `writeTaggedVarint` to `writeVarintField`, etc. +- Changed `writePacked` signature from `(type, tag, items)` to `(tag, type, items)`. + +##### Bugfixes + +- Fixed `readVarint` to handle varints bigger than 6 bytes. +- Fixed `readSVarint` to handle number bigger than `2^30`. +- Fixed `writeVarint` failing on some integers. +- Fixed `writeVarint` not throwing an error on numbers that are too big. +- Fixed `readUInt64` always failing. +- Fixed writing to an empty buffer always failing. diff --git a/node_modules/pbf/bin/pbf b/node_modules/pbf/bin/pbf new file mode 100644 index 0000000000000000000000000000000000000000..10645149f9ba0c1434170b9d5ac76db8b2d5f0cf --- /dev/null +++ b/node_modules/pbf/bin/pbf @@ -0,0 +1,19 @@ +#!/usr/bin/env node + +'use strict'; + +var resolve = require('resolve-protobuf-schema'); +var compile = require('../compile'); + +if (process.argv.length < 3) { + console.error('Usage: pbf [file.proto] [--browser] [--no-read] [--no-write]'); + return; +} + +var code = compile.raw(resolve.sync(process.argv[2]), { + exports: process.argv.indexOf('--browser') >= 0 ? 'self' : 'exports', + noRead: process.argv.indexOf('--no-read') >= 0, + noWrite: process.argv.indexOf('--no-write') >= 0 +}); + +process.stdout.write(code); diff --git a/node_modules/pbf/compile.js b/node_modules/pbf/compile.js new file mode 100644 index 0000000000000000000000000000000000000000..18d6bc8cf289b0615ebdc1006cea87008bbb51be --- /dev/null +++ b/node_modules/pbf/compile.js @@ -0,0 +1,435 @@ +'use strict'; + +module.exports = compile; + +var version = require('./package.json').version; + +function compile(proto) { + var code = 'var exports = {};\n'; + code += compileRaw(proto) + '\n'; + code += 'return exports;\n'; + return new Function(code)(); +} + +compile.raw = compileRaw; + +function compileRaw(proto, options) { + var pre = '\'use strict\'; // code generated by pbf v' + version + '\n'; + var context = buildDefaults(buildContext(proto, null), proto.syntax); + return pre + writeContext(context, options || {}); +} + +function writeContext(ctx, options) { + var code = ''; + if (ctx._proto.fields) code += writeMessage(ctx, options); + if (ctx._proto.values) code += writeEnum(ctx, options); + + for (var i = 0; i < ctx._children.length; i++) { + code += writeContext(ctx._children[i], options); + } + return code; +} + +function writeMessage(ctx, options) { + var name = ctx._name; + var fields = ctx._proto.fields; + var numRepeated = 0; + + var code = '\n// ' + name + ' ========================================\n\n'; + + if (!options.noRead || !options.noWrite) { + code += compileExport(ctx, options) + ' {};\n\n'; + } + + if (!options.noRead) { + code += name + '.read = function (pbf, end) {\n'; + code += ' return pbf.readFields(' + name + '._readField, ' + compileDest(ctx) + ', end);\n'; + code += '};\n'; + code += name + '._readField = function (tag, obj, pbf) {\n'; + + for (var i = 0; i < fields.length; i++) { + var field = fields[i]; + var readCode = compileFieldRead(ctx, field); + var packed = willSupportPacked(ctx, field); + code += ' ' + (i ? 'else if' : 'if') + + ' (tag === ' + field.tag + ') ' + + (field.type === 'map' ? ' { ' : '') + + ( + field.type === 'map' ? compileMapRead(readCode, field.name, numRepeated++) : + field.repeated && !packed ? 'obj.' + field.name + '.push(' + readCode + ')' : + field.repeated && packed ? readCode : 'obj.' + field.name + ' = ' + readCode + ); + + if (field.oneof) { + code += ', obj.' + field.oneof + ' = ' + JSON.stringify(field.name); + } + + code += ';' + (field.type === 'map' ? ' }' : '') + '\n'; + } + code += '};\n'; + } + + if (!options.noWrite) { + code += name + '.write = function (obj, pbf) {\n'; + numRepeated = 0; + for (i = 0; i < fields.length; i++) { + field = fields[i]; + var writeCode = field.repeated && !isPacked(field) ? + compileRepeatedWrite(ctx, field, numRepeated++) : + field.type === 'map' ? compileMapWrite(ctx, field, numRepeated++) : + compileFieldWrite(ctx, field, 'obj.' + field.name); + code += getDefaultWriteTest(ctx, field); + code += writeCode + ';\n'; + } + code += '};\n'; + } + return code; +} + +function getEnumValues(ctx) { + var enums = {}; + var ids = Object.keys(ctx._proto.values); + for (var i = 0; i < ids.length; i++) { + enums[ids[i]] = ctx._proto.values[ids[i]].value; + } + return enums; +} + +function writeEnum(ctx, options) { + return '\n' + compileExport(ctx, options) + ' ' + + JSON.stringify(getEnumValues(ctx), null, 4) + ';\n'; +} + +function compileExport(ctx, options) { + var exportsVar = options.exports || 'exports'; + return (ctx._root ? 'var ' + ctx._name + ' = ' + exportsVar + '.' : '') + ctx._name + ' ='; +} + +function compileDest(ctx) { + var props = {}; + for (var i = 0; i < ctx._proto.fields.length; i++) { + var field = ctx._proto.fields[i]; + props[field.name + ': ' + JSON.stringify(ctx._defaults[field.name])] = true; + if (field.oneof) props[field.oneof + ': undefined'] = true; + } + return '{' + Object.keys(props).join(', ') + '}'; +} + +function isEnum(type) { + return type && type._proto.values; +} + +function getType(ctx, field) { + if (field.type === 'map') { + return ctx[getMapMessageName(field.tag)]; + } + + var path = field.type.split('.'); + return path.reduce(function(ctx, name) { return ctx && ctx[name]; }, ctx); +} + +function fieldShouldUseStringAsNumber(field) { + if (field.options.jstype === 'JS_STRING') { + switch (field.type) { + case 'float': + case 'double': + case 'uint32': + case 'uint64': + case 'int32': + case 'int64': + case 'sint32': + case 'sint64': + case 'fixed32': + case 'fixed64': + case 'sfixed32': + case 'sfixed64': return true; + default: return false; + } + } + return false; +} + +function compileFieldRead(ctx, field) { + var type = getType(ctx, field); + if (type) { + if (type._proto.fields) return type._name + '.read(pbf, pbf.readVarint() + pbf.pos)'; + if (!isEnum(type)) throw new Error('Unexpected type: ' + type._name); + } + + var fieldType = isEnum(type) ? 'enum' : field.type; + + var prefix = 'pbf.read'; + var signed = fieldType === 'int32' || fieldType === 'int64' ? 'true' : ''; + var suffix = '(' + signed + ')'; + + if (willSupportPacked(ctx, field)) { + prefix += 'Packed'; + suffix = '(obj.' + field.name + (signed ? ', ' + signed : '') + ')'; + } + + if (fieldShouldUseStringAsNumber(field)) { + suffix += '.toString()'; + } + + switch (fieldType) { + case 'string': return prefix + 'String' + suffix; + case 'float': return prefix + 'Float' + suffix; + case 'double': return prefix + 'Double' + suffix; + case 'bool': return prefix + 'Boolean' + suffix; + case 'enum': + case 'uint32': + case 'uint64': + case 'int32': + case 'int64': return prefix + 'Varint' + suffix; + case 'sint32': + case 'sint64': return prefix + 'SVarint' + suffix; + case 'fixed32': return prefix + 'Fixed32' + suffix; + case 'fixed64': return prefix + 'Fixed64' + suffix; + case 'sfixed32': return prefix + 'SFixed32' + suffix; + case 'sfixed64': return prefix + 'SFixed64' + suffix; + case 'bytes': return prefix + 'Bytes' + suffix; + default: throw new Error('Unexpected type: ' + field.type); + } +} + +function compileFieldWrite(ctx, field, name) { + var prefix = 'pbf.write'; + if (isPacked(field)) prefix += 'Packed'; + + if (fieldShouldUseStringAsNumber(field)) { + if (field.type === 'float' || field.type === 'double') { + name = 'parseFloat(' + name + ')'; + } else { + name = 'parseInt(' + name + ', 10)'; + } + } + var postfix = (isPacked(field) ? '' : 'Field') + '(' + field.tag + ', ' + name + ')'; + + var type = getType(ctx, field); + if (type) { + if (type._proto.fields) return prefix + 'Message(' + field.tag + ', ' + type._name + '.write, ' + name + ')'; + if (type._proto.values) return prefix + 'Varint' + postfix; + throw new Error('Unexpected type: ' + type._name); + } + + switch (field.type) { + case 'string': return prefix + 'String' + postfix; + case 'float': return prefix + 'Float' + postfix; + case 'double': return prefix + 'Double' + postfix; + case 'bool': return prefix + 'Boolean' + postfix; + case 'enum': + case 'uint32': + case 'uint64': + case 'int32': + case 'int64': return prefix + 'Varint' + postfix; + case 'sint32': + case 'sint64': return prefix + 'SVarint' + postfix; + case 'fixed32': return prefix + 'Fixed32' + postfix; + case 'fixed64': return prefix + 'Fixed64' + postfix; + case 'sfixed32': return prefix + 'SFixed32' + postfix; + case 'sfixed64': return prefix + 'SFixed64' + postfix; + case 'bytes': return prefix + 'Bytes' + postfix; + default: throw new Error('Unexpected type: ' + field.type); + } +} + +function compileMapRead(readCode, name, numRepeated) { + return (numRepeated ? '' : 'var ') + 'entry = ' + readCode + '; obj.' + name + '[entry.key] = entry.value'; +} + +function compileRepeatedWrite(ctx, field, numRepeated) { + return 'for (' + (numRepeated ? '' : 'var ') + + 'i = 0; i < obj.' + field.name + '.length; i++) ' + + compileFieldWrite(ctx, field, 'obj.' + field.name + '[i]'); +} + +function compileMapWrite(ctx, field, numRepeated) { + var name = 'obj.' + field.name; + + return 'for (' + (numRepeated ? '' : 'var ') + + 'i in ' + name + ') if (Object.prototype.hasOwnProperty.call(' + name + ', i)) ' + + compileFieldWrite(ctx, field, '{ key: i, value: ' + name + '[i] }'); +} + +function getMapMessageName(tag) { + return '_FieldEntry' + tag; +} + +function getMapField(name, type, tag) { + return { + name: name, + type: type, + tag: tag, + map: null, + oneof: null, + required: false, + repeated: false, + options: {} + }; +} + +function getMapMessage(field) { + return { + name: getMapMessageName(field.tag), + enums: [], + messages: [], + extensions: null, + fields: [ + getMapField('key', field.map.from, 1), + getMapField('value', field.map.to, 2) + ] + }; +} + +function buildContext(proto, parent) { + var obj = Object.create(parent); + obj._proto = proto; + obj._children = []; + obj._defaults = {}; + + if (parent) { + parent[proto.name] = obj; + + if (parent._name) { + obj._root = false; + obj._name = parent._name + '.' + proto.name; + } else { + obj._root = true; + obj._name = proto.name; + } + } + + for (var i = 0; proto.enums && i < proto.enums.length; i++) { + obj._children.push(buildContext(proto.enums[i], obj)); + } + + for (i = 0; proto.messages && i < proto.messages.length; i++) { + obj._children.push(buildContext(proto.messages[i], obj)); + } + + for (i = 0; proto.fields && i < proto.fields.length; i++) { + if (proto.fields[i].type === 'map') { + obj._children.push(buildContext(getMapMessage(proto.fields[i]), obj)); + } + } + + return obj; +} + +function getDefaultValue(field, value) { + // Defaults not supported for repeated fields + if (field.repeated) return []; + var convertToStringIfNeeded = function(val) { return val; }; + if (fieldShouldUseStringAsNumber(field)) { + convertToStringIfNeeded = function(val) { return val.toString(); }; + } + + switch (field.type) { + case 'float': + case 'double': return convertToStringIfNeeded(value ? parseFloat(value) : 0); + case 'uint32': + case 'uint64': + case 'int32': + case 'int64': + case 'sint32': + case 'sint64': + case 'fixed32': + case 'fixed64': + case 'sfixed32': + case 'sfixed64': return convertToStringIfNeeded(value ? parseInt(value, 10) : 0); + case 'string': return value || ''; + case 'bool': return value === 'true'; + case 'map': return {}; + default: return undefined; + } +} + +function willSupportPacked(ctx, field) { + var fieldType = isEnum(getType(ctx, field)) ? 'enum' : field.type; + + switch (field.repeated && fieldType) { + case 'float': + case 'double': + case 'uint32': + case 'uint64': + case 'int32': + case 'int64': + case 'sint32': + case 'sint64': + case 'fixed32': + case 'fixed64': + case 'sfixed32': + case 'enum': + case 'bool': return true; + } + + return false; +} + +function setPackedOption(ctx, field, syntax) { + // No default packed in older protobuf versions + if (syntax < 3) return; + + // Packed option already set + if (field.options.packed !== undefined) return; + + // Not a packed field type + if (!willSupportPacked(ctx, field)) return; + + field.options.packed = 'true'; +} + +function setDefaultValue(ctx, field, syntax) { + var options = field.options; + var type = getType(ctx, field); + var enumValues = type && type._proto.values && getEnumValues(type); + + // Proto3 does not support overriding defaults + var explicitDefault = syntax < 3 ? options.default : undefined; + + // Set default for enum values + if (enumValues && !field.repeated) { + ctx._defaults[field.name] = enumValues[explicitDefault] || 0; + + } else { + ctx._defaults[field.name] = getDefaultValue(field, explicitDefault); + } +} + +function buildDefaults(ctx, syntax) { + var proto = ctx._proto; + + for (var i = 0; i < ctx._children.length; i++) { + buildDefaults(ctx._children[i], syntax); + } + + if (proto.fields) { + for (i = 0; i < proto.fields.length; i++) { + setPackedOption(ctx, proto.fields[i], syntax); + setDefaultValue(ctx, proto.fields[i], syntax); + } + } + + return ctx; +} + +function getDefaultWriteTest(ctx, field) { + var def = ctx._defaults[field.name]; + var type = getType(ctx, field); + var code = ' if (obj.' + field.name; + + if (!field.repeated && (!type || !type._proto.fields)) { + if (def === undefined || def) { + code += ' != undefined'; + } + if (def) { + code += ' && obj.' + field.name + ' !== ' + JSON.stringify(def); + } + } + + return code + ') '; +} + +function isPacked(field) { + return field.options.packed === 'true'; +} diff --git a/node_modules/pbf/dist/pbf-dev.js b/node_modules/pbf/dist/pbf-dev.js new file mode 100644 index 0000000000000000000000000000000000000000..b36fecb7928de297122a72b02cefcdd61470d4df --- /dev/null +++ b/node_modules/pbf/dist/pbf-dev.js @@ -0,0 +1,735 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Pbf = f()}})(function(){var define,module,exports;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;i> 3, + startPos = this.pos; + + this.type = val & 0x7; + readField(tag, result, this); + + if (this.pos === startPos) this.skip(val); + } + return result; + }, + + readMessage: function(readField, result) { + return this.readFields(readField, result, this.readVarint() + this.pos); + }, + + readFixed32: function() { + var val = readUInt32(this.buf, this.pos); + this.pos += 4; + return val; + }, + + readSFixed32: function() { + var val = readInt32(this.buf, this.pos); + this.pos += 4; + return val; + }, + + // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed) + + readFixed64: function() { + var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32; + this.pos += 8; + return val; + }, + + readSFixed64: function() { + var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32; + this.pos += 8; + return val; + }, + + readFloat: function() { + var val = ieee754.read(this.buf, this.pos, true, 23, 4); + this.pos += 4; + return val; + }, + + readDouble: function() { + var val = ieee754.read(this.buf, this.pos, true, 52, 8); + this.pos += 8; + return val; + }, + + readVarint: function(isSigned) { + var buf = this.buf, + val, b; + + b = buf[this.pos++]; val = b & 0x7f; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val; + b = buf[this.pos]; val |= (b & 0x0f) << 28; + + return readVarintRemainder(val, isSigned, this); + }, + + readVarint64: function() { // for compatibility with v2.0.1 + return this.readVarint(true); + }, + + readSVarint: function() { + var num = this.readVarint(); + return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding + }, + + readBoolean: function() { + return Boolean(this.readVarint()); + }, + + readString: function() { + var end = this.readVarint() + this.pos; + var pos = this.pos; + this.pos = end; + + if (end - pos >= TEXT_DECODER_MIN_LENGTH && utf8TextDecoder) { + // longer strings are fast with the built-in browser TextDecoder API + return readUtf8TextDecoder(this.buf, pos, end); + } + // short strings are fast with our custom implementation + return readUtf8(this.buf, pos, end); + }, + + readBytes: function() { + var end = this.readVarint() + this.pos, + buffer = this.buf.subarray(this.pos, end); + this.pos = end; + return buffer; + }, + + // verbose for performance reasons; doesn't affect gzipped size + + readPackedVarint: function(arr, isSigned) { + if (this.type !== Pbf.Bytes) return arr.push(this.readVarint(isSigned)); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readVarint(isSigned)); + return arr; + }, + readPackedSVarint: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSVarint()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSVarint()); + return arr; + }, + readPackedBoolean: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readBoolean()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readBoolean()); + return arr; + }, + readPackedFloat: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFloat()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFloat()); + return arr; + }, + readPackedDouble: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readDouble()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readDouble()); + return arr; + }, + readPackedFixed32: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFixed32()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFixed32()); + return arr; + }, + readPackedSFixed32: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed32()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSFixed32()); + return arr; + }, + readPackedFixed64: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFixed64()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFixed64()); + return arr; + }, + readPackedSFixed64: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed64()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSFixed64()); + return arr; + }, + + skip: function(val) { + var type = val & 0x7; + if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {} + else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos; + else if (type === Pbf.Fixed32) this.pos += 4; + else if (type === Pbf.Fixed64) this.pos += 8; + else throw new Error('Unimplemented type: ' + type); + }, + + // === WRITING ================================================================= + + writeTag: function(tag, type) { + this.writeVarint((tag << 3) | type); + }, + + realloc: function(min) { + var length = this.length || 16; + + while (length < this.pos + min) length *= 2; + + if (length !== this.length) { + var buf = new Uint8Array(length); + buf.set(this.buf); + this.buf = buf; + this.length = length; + } + }, + + finish: function() { + this.length = this.pos; + this.pos = 0; + return this.buf.subarray(0, this.length); + }, + + writeFixed32: function(val) { + this.realloc(4); + writeInt32(this.buf, val, this.pos); + this.pos += 4; + }, + + writeSFixed32: function(val) { + this.realloc(4); + writeInt32(this.buf, val, this.pos); + this.pos += 4; + }, + + writeFixed64: function(val) { + this.realloc(8); + writeInt32(this.buf, val & -1, this.pos); + writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4); + this.pos += 8; + }, + + writeSFixed64: function(val) { + this.realloc(8); + writeInt32(this.buf, val & -1, this.pos); + writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4); + this.pos += 8; + }, + + writeVarint: function(val) { + val = +val || 0; + + if (val > 0xfffffff || val < 0) { + writeBigVarint(val, this); + return; + } + + this.realloc(4); + + this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = (val >>> 7) & 0x7f; + }, + + writeSVarint: function(val) { + this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2); + }, + + writeBoolean: function(val) { + this.writeVarint(Boolean(val)); + }, + + writeString: function(str) { + str = String(str); + this.realloc(str.length * 4); + + this.pos++; // reserve 1 byte for short string length + + var startPos = this.pos; + // write the string directly to the buffer and see how much was written + this.pos = writeUtf8(this.buf, str, this.pos); + var len = this.pos - startPos; + + if (len >= 0x80) makeRoomForExtraLength(startPos, len, this); + + // finally, write the message length in the reserved place and restore the position + this.pos = startPos - 1; + this.writeVarint(len); + this.pos += len; + }, + + writeFloat: function(val) { + this.realloc(4); + ieee754.write(this.buf, val, this.pos, true, 23, 4); + this.pos += 4; + }, + + writeDouble: function(val) { + this.realloc(8); + ieee754.write(this.buf, val, this.pos, true, 52, 8); + this.pos += 8; + }, + + writeBytes: function(buffer) { + var len = buffer.length; + this.writeVarint(len); + this.realloc(len); + for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i]; + }, + + writeRawMessage: function(fn, obj) { + this.pos++; // reserve 1 byte for short message length + + // write the message directly to the buffer and see how much was written + var startPos = this.pos; + fn(obj, this); + var len = this.pos - startPos; + + if (len >= 0x80) makeRoomForExtraLength(startPos, len, this); + + // finally, write the message length in the reserved place and restore the position + this.pos = startPos - 1; + this.writeVarint(len); + this.pos += len; + }, + + writeMessage: function(tag, fn, obj) { + this.writeTag(tag, Pbf.Bytes); + this.writeRawMessage(fn, obj); + }, + + writePackedVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedVarint, arr); }, + writePackedSVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSVarint, arr); }, + writePackedBoolean: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedBoolean, arr); }, + writePackedFloat: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFloat, arr); }, + writePackedDouble: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedDouble, arr); }, + writePackedFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed32, arr); }, + writePackedSFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed32, arr); }, + writePackedFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed64, arr); }, + writePackedSFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed64, arr); }, + + writeBytesField: function(tag, buffer) { + this.writeTag(tag, Pbf.Bytes); + this.writeBytes(buffer); + }, + writeFixed32Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeFixed32(val); + }, + writeSFixed32Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeSFixed32(val); + }, + writeFixed64Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeFixed64(val); + }, + writeSFixed64Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeSFixed64(val); + }, + writeVarintField: function(tag, val) { + this.writeTag(tag, Pbf.Varint); + this.writeVarint(val); + }, + writeSVarintField: function(tag, val) { + this.writeTag(tag, Pbf.Varint); + this.writeSVarint(val); + }, + writeStringField: function(tag, str) { + this.writeTag(tag, Pbf.Bytes); + this.writeString(str); + }, + writeFloatField: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeFloat(val); + }, + writeDoubleField: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeDouble(val); + }, + writeBooleanField: function(tag, val) { + this.writeVarintField(tag, Boolean(val)); + } +}; + +function readVarintRemainder(l, s, p) { + var buf = p.buf, + h, b; + + b = buf[p.pos++]; h = (b & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s); + + throw new Error('Expected varint not more than 10 bytes'); +} + +function readPackedEnd(pbf) { + return pbf.type === Pbf.Bytes ? + pbf.readVarint() + pbf.pos : pbf.pos + 1; +} + +function toNum(low, high, isSigned) { + if (isSigned) { + return high * 0x100000000 + (low >>> 0); + } + + return ((high >>> 0) * 0x100000000) + (low >>> 0); +} + +function writeBigVarint(val, pbf) { + var low, high; + + if (val >= 0) { + low = (val % 0x100000000) | 0; + high = (val / 0x100000000) | 0; + } else { + low = ~(-val % 0x100000000); + high = ~(-val / 0x100000000); + + if (low ^ 0xffffffff) { + low = (low + 1) | 0; + } else { + low = 0; + high = (high + 1) | 0; + } + } + + if (val >= 0x10000000000000000 || val < -0x10000000000000000) { + throw new Error('Given varint doesn\'t fit into 10 bytes'); + } + + pbf.realloc(10); + + writeBigVarintLow(low, high, pbf); + writeBigVarintHigh(high, pbf); +} + +function writeBigVarintLow(low, high, pbf) { + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos] = low & 0x7f; +} + +function writeBigVarintHigh(high, pbf) { + var lsb = (high & 0x07) << 4; + + pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f; +} + +function makeRoomForExtraLength(startPos, len, pbf) { + var extraLen = + len <= 0x3fff ? 1 : + len <= 0x1fffff ? 2 : + len <= 0xfffffff ? 3 : Math.floor(Math.log(len) / (Math.LN2 * 7)); + + // if 1 byte isn't enough for encoding message length, shift the data to the right + pbf.realloc(extraLen); + for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i]; +} + +function writePackedVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]); } +function writePackedSVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]); } +function writePackedFloat(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]); } +function writePackedDouble(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]); } +function writePackedBoolean(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]); } +function writePackedFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]); } +function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); } +function writePackedFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]); } +function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); } + +// Buffer code below from https://github.com/feross/buffer, MIT-licensed + +function readUInt32(buf, pos) { + return ((buf[pos]) | + (buf[pos + 1] << 8) | + (buf[pos + 2] << 16)) + + (buf[pos + 3] * 0x1000000); +} + +function writeInt32(buf, val, pos) { + buf[pos] = val; + buf[pos + 1] = (val >>> 8); + buf[pos + 2] = (val >>> 16); + buf[pos + 3] = (val >>> 24); +} + +function readInt32(buf, pos) { + return ((buf[pos]) | + (buf[pos + 1] << 8) | + (buf[pos + 2] << 16)) + + (buf[pos + 3] << 24); +} + +function readUtf8(buf, pos, end) { + var str = ''; + var i = pos; + + while (i < end) { + var b0 = buf[i]; + var c = null; // codepoint + var bytesPerSequence = + b0 > 0xEF ? 4 : + b0 > 0xDF ? 3 : + b0 > 0xBF ? 2 : 1; + + if (i + bytesPerSequence > end) break; + + var b1, b2, b3; + + if (bytesPerSequence === 1) { + if (b0 < 0x80) { + c = b0; + } + } else if (bytesPerSequence === 2) { + b1 = buf[i + 1]; + if ((b1 & 0xC0) === 0x80) { + c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F); + if (c <= 0x7F) { + c = null; + } + } + } else if (bytesPerSequence === 3) { + b1 = buf[i + 1]; + b2 = buf[i + 2]; + if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) { + c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F); + if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) { + c = null; + } + } + } else if (bytesPerSequence === 4) { + b1 = buf[i + 1]; + b2 = buf[i + 2]; + b3 = buf[i + 3]; + if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) { + c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F); + if (c <= 0xFFFF || c >= 0x110000) { + c = null; + } + } + } + + if (c === null) { + c = 0xFFFD; + bytesPerSequence = 1; + + } else if (c > 0xFFFF) { + c -= 0x10000; + str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800); + c = 0xDC00 | c & 0x3FF; + } + + str += String.fromCharCode(c); + i += bytesPerSequence; + } + + return str; +} + +function readUtf8TextDecoder(buf, pos, end) { + return utf8TextDecoder.decode(buf.subarray(pos, end)); +} + +function writeUtf8(buf, str, pos) { + for (var i = 0, c, lead; i < str.length; i++) { + c = str.charCodeAt(i); // code point + + if (c > 0xD7FF && c < 0xE000) { + if (lead) { + if (c < 0xDC00) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + lead = c; + continue; + } else { + c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000; + lead = null; + } + } else { + if (c > 0xDBFF || (i + 1 === str.length)) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + } else { + lead = c; + } + continue; + } + } else if (lead) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + lead = null; + } + + if (c < 0x80) { + buf[pos++] = c; + } else { + if (c < 0x800) { + buf[pos++] = c >> 0x6 | 0xC0; + } else { + if (c < 0x10000) { + buf[pos++] = c >> 0xC | 0xE0; + } else { + buf[pos++] = c >> 0x12 | 0xF0; + buf[pos++] = c >> 0xC & 0x3F | 0x80; + } + buf[pos++] = c >> 0x6 & 0x3F | 0x80; + } + buf[pos++] = c & 0x3F | 0x80; + } + } + return pos; +} + +},{"ieee754":2}],2:[function(require,module,exports){ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}]},{},[1])(1) +}); + +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCJpbmRleC5qcyIsIm5vZGVfbW9kdWxlcy9pZWVlNzU0L2luZGV4LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FDQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTt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ICAgICAgKGJ1Zltwb3MgKyAyXSA8PCAxNikpICtcbiAgICAgICAgKGJ1Zltwb3MgKyAzXSA8PCAyNCk7XG59XG5cbmZ1bmN0aW9uIHJlYWRVdGY4KGJ1ZiwgcG9zLCBlbmQpIHtcbiAgICB2YXIgc3RyID0gJyc7XG4gICAgdmFyIGkgPSBwb3M7XG5cbiAgICB3aGlsZSAoaSA8IGVuZCkge1xuICAgICAgICB2YXIgYjAgPSBidWZbaV07XG4gICAgICAgIHZhciBjID0gbnVsbDsgLy8gY29kZXBvaW50XG4gICAgICAgIHZhciBieXRlc1BlclNlcXVlbmNlID1cbiAgICAgICAgICAgIGIwID4gMHhFRiA/IDQgOlxuICAgICAgICAgICAgYjAgPiAweERGID8gMyA6XG4gICAgICAgICAgICBiMCA+IDB4QkYgPyAyIDogMTtcblxuICAgICAgICBpZiAoaSArIGJ5dGVzUGVyU2VxdWVuY2UgPiBlbmQpIGJyZWFrO1xuXG4gICAgICAgIHZhciBiMSwgYjIsIGIzO1xuXG4gICAgICAgIGlmIChieXRlc1BlclNlcXVlbmNlID09PSAxKSB7XG4gICAgICAgICAgICBpZiAoYjAgPCAweDgwKSB7XG4gICAgICAgICAgICAgICAgYyA9IGIwO1xuICAgICAgICAgICAgfVxuICAgICAgICB9IGVsc2UgaWYgKGJ5dGVzUGVyU2VxdWVuY2UgPT09IDIpIHtcbiAgICAgICAgICAgIGIxID0gYnVmW2kgKyAxXTtcbiAgICAgICAgICAgIGlmICgoYjEgJiAweEMwKSA9PT0gMHg4MCkge1xuICAgICAgICAgICAgICAgIGMgPSAoYjAgJiAweDFGKSA8PCAweDYgfCAoYjEgJiAweDNGKTtcbiAgICAgICAgICAgICAgICBpZiAoYyA8PSAweDdGKSB7XG4gICAgICAgICAgICAgICAgICAgIGMgPSBudWxsO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgfSBlbHNlIGlmIChieXRlc1BlclNlcXVlbmNlID09PSAzKSB7XG4gICAgICAgICAgICBiMSA9IGJ1ZltpICsgMV07XG4gICAgICAgICAgICBiMiA9IGJ1ZltpICsgMl07XG4gICAgICAgICAgICBpZiAoKGIxICYgMHhDMCkgPT09IDB4ODAgJiYgKGIyICYgMHhDMCkgPT09IDB4ODApIHtcbiAgICAgICAgICAgICAgICBjID0gKGIwICYgMHhGKSA8PCAweEMgfCAoYjEgJiAweDNGKSA8PCAweDYgfCAoYjIgJiAweDNGKTtcbiAgICAgICAgICAgICAgICBpZiAoYyA8PSAweDdGRiB8fCAoYyA+PSAweEQ4MDAgJiYgYyA8PSAweERGRkYpKSB7XG4gICAgICAgICAgICAgICAgICAgIGMgPSBudWxsO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgfSBlbHNlIGlmIChieXRlc1BlclNlcXVlbmNlID09PSA0KSB7XG4gICAgICAgICAgICBiMSA9IGJ1ZltpICsgMV07XG4gICAgICAgICAgICBiMiA9IGJ1ZltpICsgMl07XG4gICAgICAgICAgICBiMyA9IGJ1ZltpICsgM107XG4gICAgICAgICAgICBpZiAoKGIxICYgMHhDMCkgPT09IDB4ODAgJiYgKGIyICYgMHhDMCkgPT09IDB4ODAgJiYgKGIzICYgMHhDMCkgPT09IDB4ODApIHtcbiAgICAgICAgICAgICAgICBjID0gKGIwICYgMHhGKSA8PCAweDEyIHwgKGIxICYgMHgzRikgPDwgMHhDIHwgKGIyICYgMHgzRikgPDwgMHg2IHwgKGIzICYgMHgzRik7XG4gICAgICAgICAgICAgICAgaWYgKGMgPD0gMHhGRkZGIHx8IGMgPj0gMHgxMTAwMDApIHtcbiAgICAgICAgICAgICAgICAgICAgYyA9IG51bGw7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfVxuICAgICAgICB9XG5cbiAgICAgICAgaWYgKGMgPT09IG51bGwpIHtcbiAgICAgICAgICAgIGMgPSAweEZGRkQ7XG4gICAgICAgICAgICBieXRlc1BlclNlcXVlbmNlID0gMTtcblxuICAgICAgICB9IGVsc2UgaWYgKGMgPiAweEZGRkYpIHtcbiAgICAgICAgICAgIGMgLT0gMHgxMDAwMDtcbiAgICAgICAgICAgIHN0ciArPSBTdHJpbmcuZnJvbUNoYXJDb2RlKGMgPj4+IDEwICYgMHgzRkYgfCAweEQ4MDApO1xuICAgICAgICAgICAgYyA9IDB4REMwMCB8IGMgJiAweDNGRjtcbiAgICAgICAgfVxuXG4gICAgICAgIHN0ciArPSBTdHJpbmcuZnJvbUNoYXJDb2RlKGMpO1xuICAgICAgICBpICs9IGJ5dGVzUGVyU2VxdWVuY2U7XG4gICAgfVxuXG4gICAgcmV0dXJuIHN0cjtcbn1cblxuZnVuY3Rpb24gcmVhZFV0ZjhUZXh0RGVjb2RlcihidWYsIHBvcywgZW5kKSB7XG4gICAgcmV0dXJuIHV0ZjhUZXh0RGVjb2Rlci5kZWNvZGUoYnVmLnN1YmFycmF5KHBvcywgZW5kKSk7XG59XG5cbmZ1bmN0aW9uIHdyaXRlVXRmOChidWYsIHN0ciwgcG9zKSB7XG4gICAgZm9yICh2YXIgaSA9IDAsIGMsIGxlYWQ7IGkgPCBzdHIubGVuZ3RoOyBpKyspIHtcbiAgICAgICAgYyA9IHN0ci5jaGFyQ29kZUF0KGkpOyAvLyBjb2RlIHBvaW50XG5cbiAgICAgICAgaWYgKGMgPiAweEQ3RkYgJiYgYyA8IDB4RTAwMCkge1xuICAgICAgICAgICAgaWYgKGxlYWQpIHtcbiAgICAgICAgICAgICAgICBpZiAoYyA8IDB4REMwMCkge1xuICAgICAgICAgICAgICAgICAgICBidWZbcG9zKytdID0gMHhFRjtcbiAgICAgICAgICAgICAgICAgICAgYnVmW3BvcysrXSA9IDB4QkY7XG4gICAgICAgICAgICAgICAgICAgIGJ1Zltwb3MrK10gPSAweEJEO1xuICAgICAgICAgICAgICAgICAgICBsZWFkID0gYztcbiAgICAgICAgICAgICAgICAgICAgY29udGludWU7XG4gICAgICAgICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgICAgICAgICAgYyA9IGxlYWQgLSAweEQ4MDAgPDwgMTAgfCBjIC0gMHhEQzAwIHwgMHgxMDAwMDtcbiAgICAgICAgICAgICAgICAgICAgbGVhZCA9IG51bGw7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgICAgICBpZiAoYyA+IDB4REJGRiB8fCAoaSArIDEgPT09IHN0ci5sZW5ndGgpKSB7XG4gICAgICAgICAgICAgICAgICAgIGJ1Zltwb3MrK10gPSAweEVGO1xuICAgICAgICAgICAgICAgICAgICBidWZbcG9zKytdID0gMHhCRjtcbiAgICAgICAgICAgICAgICAgICAgYnVmW3BvcysrXSA9IDB4QkQ7XG4gICAgICAgICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgICAgICAgICAgbGVhZCA9IGM7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIGNvbnRpbnVlO1xuICAgICAgICAgICAgfVxuICAgICAgICB9IGVsc2UgaWYgKGxlYWQpIHtcbiAgICAgICAgICAgIGJ1Zltwb3MrK10gPSAweEVGO1xuICAgICAgICAgICAgYnVmW3BvcysrXSA9IDB4QkY7XG4gICAgICAgICAgICBidWZbcG9zKytdID0gMHhCRDtcbiAgICAgICAgICAgIGxlYWQgPSBudWxsO1xuICAgICAgICB9XG5cbiAgICAgICAgaWYgKGMgPCAweDgwKSB7XG4gICAgICAgICAgICBidWZbcG9zKytdID0gYztcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIGlmIChjIDwgMHg4MDApIHtcbiAgICAgICAgICAgICAgICBidWZbcG9zKytdID0gYyA+PiAweDYgfCAweEMwO1xuICAgICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgICAgICBpZiAoYyA8IDB4MTAwMDApIHtcbiAgICAgICAgICAgICAgICAgICAgYnVmW3BvcysrXSA9IGMgPj4gMHhDIHwgMHhFMDtcbiAgICAgICAgICAgICAgICB9IGVsc2Uge1x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blxuICBidWZmZXJbb2Zmc2V0ICsgaSAtIGRdIHw9IHMgKiAxMjhcbn1cbiJdfQ== diff --git a/node_modules/pbf/dist/pbf.js b/node_modules/pbf/dist/pbf.js new file mode 100644 index 0000000000000000000000000000000000000000..3753a73caf23ef83f92e6e2de3ca4dbcdd2820eb --- /dev/null +++ b/node_modules/pbf/dist/pbf.js @@ -0,0 +1 @@ +!function(t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Pbf=t()}(function(){return function r(s,n,o){function h(i,t){if(!n[i]){if(!s[i]){var e="function"==typeof require&&require;if(!t&&e)return e(i,!0);if(a)return a(i,!0);throw(t=new Error("Cannot find module '"+i+"'")).code="MODULE_NOT_FOUND",t}e=n[i]={exports:{}},s[i][0].call(e.exports,function(t){return h(s[i][1][t]||t)},e,e.exports,r,s,n,o)}return n[i].exports}for(var a="function"==typeof require&&require,t=0;t>>0):4294967296*(i>>>0)+(t>>>0)}function u(t,i,e){var r=i<=16383?1:i<=2097151?2:i<=268435455?3:Math.floor(Math.log(i)/(7*Math.LN2));e.realloc(r);for(var s=e.pos-1;t<=s;s--)e.buf[s+r]=e.buf[s]}function f(t,i){for(var e=0;e>>8,t[e+2]=i>>>16,t[e+3]=i>>>24}function V(t,i){return(t[i]|t[i+1]<<8|t[i+2]<<16)+(t[i+3]<<24)}s.prototype={destroy:function(){this.buf=null},readFields:function(t,i,e){for(e=e||this.length;this.pos>3,n=this.pos;this.type=7&r,t(s,i,this),this.pos===n&&this.skip(r)}return i},readMessage:function(t,i){return this.readFields(t,i,this.readVarint()+this.pos)},readFixed32:function(){var t=y(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=V(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=y(this.buf,this.pos)+y(this.buf,this.pos+4)*n;return this.pos+=8,t},readSFixed64:function(){var t=y(this.buf,this.pos)+V(this.buf,this.pos+4)*n;return this.pos+=8,t},readFloat:function(){var t=r.read(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=r.read(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var i=this.buf,e=i[this.pos++],r=127&e;if(e<128)return r;if(r|=(127&(e=i[this.pos++]))<<7,e<128)return r;if(r|=(127&(e=i[this.pos++]))<<14,e<128)return r;if(r|=(127&(e=i[this.pos++]))<<21,e<128)return r;var s,n,e=r|=(15&i[this.pos])<<28,i=t,r=this,t=r.buf;if(n=t[r.pos++],s=(112&n)>>4,n<128)return a(e,s,i);if(n=t[r.pos++],s|=(127&n)<<3,n<128)return a(e,s,i);if(n=t[r.pos++],s|=(127&n)<<10,n<128)return a(e,s,i);if(n=t[r.pos++],s|=(127&n)<<17,n<128)return a(e,s,i);if(n=t[r.pos++],s|=(127&n)<<24,n<128)return a(e,s,i);if(n=t[r.pos++],s|=(1&n)<<31,n<128)return a(e,s,i);throw new Error("Expected varint not more than 10 bytes")},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,i=this.pos;if(12<=(this.pos=t)-i&&l)return e=this.buf,l.decode(e.subarray(i,t));for(var e,r,s,n,o=this.buf,h=t,a="",u=i;u>>10&1023|55296),d=56320|1023&d),a+=String.fromCharCode(d),u+=p}return a},readBytes:function(){var t=this.readVarint()+this.pos,i=this.buf.subarray(this.pos,t);return this.pos=t,i},readPackedVarint:function(t,i){if(this.type!==s.Bytes)return t.push(this.readVarint(i));var e=h(this);for(t=t||[];this.pos>>=7,r.buf[r.pos++]=127&i|128,i>>>=7,r.buf[r.pos++]=127&i|128,i>>>=7,r.buf[r.pos++]=127&i|128,i>>>=7,r.buf[r.pos]=127&i,s),s=e,e=(7&i)<<4;s.buf[s.pos++]|=e|((i>>>=3)?128:0),i&&(s.buf[s.pos++]=127&i|((i>>>=7)?128:0),i)&&(s.buf[s.pos++]=127&i|((i>>>=7)?128:0),i)&&(s.buf[s.pos++]=127&i|((i>>>=7)?128:0),i)&&(s.buf[s.pos++]=127&i|((i>>>=7)?128:0),i)&&(s.buf[s.pos++]=127&i)}else this.realloc(4),this.buf[this.pos++]=127&t|(127>>=7)|(127>>=7)|(127>>7&127)},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t)},writeBoolean:function(t){this.writeVarint(Boolean(t))},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var i=this.pos,t=(this.pos=function(t,i,e){for(var r,s,n=0;n>6|192:(r<65536?t[e++]=r>>12|224:(t[e++]=r>>18|240,t[e++]=r>>12&63|128),t[e++]=r>>6&63|128),t[e++]=63&r|128)}return e}(this.buf,t,this.pos),this.pos-i);128<=t&&u(i,t,this),this.pos=i-1,this.writeVarint(t),this.pos+=t},writeFloat:function(t){this.realloc(4),r.write(this.buf,t,this.pos,!0,23,4),this.pos+=4},writeDouble:function(t){this.realloc(8),r.write(this.buf,t,this.pos,!0,52,8),this.pos+=8},writeBytes:function(t){var i=t.length;this.writeVarint(i),this.realloc(i);for(var e=0;e>1,f=-7,d=e?s-1:0,p=e?-1:1,s=t[i+d];for(d+=p,n=s&(1<<-f)-1,s>>=-f,f+=h;0>=-f,f+=r;0>1,d=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:n-1,l=r?1:-1,n=i<0||0===i&&1/i<0?1:0;for(i=Math.abs(i),isNaN(i)||i===1/0?(h=isNaN(i)?1:0,o=u):(o=Math.floor(Math.log(i)/Math.LN2),i*(r=Math.pow(2,-o))<1&&(o--,r*=2),2<=(i+=1<=o+f?d/r:d*Math.pow(2,1-f))*r&&(o++,r/=2),u<=o+f?(h=0,o=u):1<=o+f?(h=(i*r-1)*Math.pow(2,s),o+=f):(h=i*Math.pow(2,f-1)*Math.pow(2,s),o=0));8<=s;t[e+p]=255&h,p+=l,h/=256,s-=8);for(o=o<> 3, + startPos = this.pos; + + this.type = val & 0x7; + readField(tag, result, this); + + if (this.pos === startPos) this.skip(val); + } + return result; + }, + + readMessage: function(readField, result) { + return this.readFields(readField, result, this.readVarint() + this.pos); + }, + + readFixed32: function() { + var val = readUInt32(this.buf, this.pos); + this.pos += 4; + return val; + }, + + readSFixed32: function() { + var val = readInt32(this.buf, this.pos); + this.pos += 4; + return val; + }, + + // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed) + + readFixed64: function() { + var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32; + this.pos += 8; + return val; + }, + + readSFixed64: function() { + var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32; + this.pos += 8; + return val; + }, + + readFloat: function() { + var val = ieee754.read(this.buf, this.pos, true, 23, 4); + this.pos += 4; + return val; + }, + + readDouble: function() { + var val = ieee754.read(this.buf, this.pos, true, 52, 8); + this.pos += 8; + return val; + }, + + readVarint: function(isSigned) { + var buf = this.buf, + val, b; + + b = buf[this.pos++]; val = b & 0x7f; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val; + b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val; + b = buf[this.pos]; val |= (b & 0x0f) << 28; + + return readVarintRemainder(val, isSigned, this); + }, + + readVarint64: function() { // for compatibility with v2.0.1 + return this.readVarint(true); + }, + + readSVarint: function() { + var num = this.readVarint(); + return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding + }, + + readBoolean: function() { + return Boolean(this.readVarint()); + }, + + readString: function() { + var end = this.readVarint() + this.pos; + var pos = this.pos; + this.pos = end; + + if (end - pos >= TEXT_DECODER_MIN_LENGTH && utf8TextDecoder) { + // longer strings are fast with the built-in browser TextDecoder API + return readUtf8TextDecoder(this.buf, pos, end); + } + // short strings are fast with our custom implementation + return readUtf8(this.buf, pos, end); + }, + + readBytes: function() { + var end = this.readVarint() + this.pos, + buffer = this.buf.subarray(this.pos, end); + this.pos = end; + return buffer; + }, + + // verbose for performance reasons; doesn't affect gzipped size + + readPackedVarint: function(arr, isSigned) { + if (this.type !== Pbf.Bytes) return arr.push(this.readVarint(isSigned)); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readVarint(isSigned)); + return arr; + }, + readPackedSVarint: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSVarint()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSVarint()); + return arr; + }, + readPackedBoolean: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readBoolean()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readBoolean()); + return arr; + }, + readPackedFloat: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFloat()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFloat()); + return arr; + }, + readPackedDouble: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readDouble()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readDouble()); + return arr; + }, + readPackedFixed32: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFixed32()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFixed32()); + return arr; + }, + readPackedSFixed32: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed32()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSFixed32()); + return arr; + }, + readPackedFixed64: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readFixed64()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readFixed64()); + return arr; + }, + readPackedSFixed64: function(arr) { + if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed64()); + var end = readPackedEnd(this); + arr = arr || []; + while (this.pos < end) arr.push(this.readSFixed64()); + return arr; + }, + + skip: function(val) { + var type = val & 0x7; + if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {} + else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos; + else if (type === Pbf.Fixed32) this.pos += 4; + else if (type === Pbf.Fixed64) this.pos += 8; + else throw new Error('Unimplemented type: ' + type); + }, + + // === WRITING ================================================================= + + writeTag: function(tag, type) { + this.writeVarint((tag << 3) | type); + }, + + realloc: function(min) { + var length = this.length || 16; + + while (length < this.pos + min) length *= 2; + + if (length !== this.length) { + var buf = new Uint8Array(length); + buf.set(this.buf); + this.buf = buf; + this.length = length; + } + }, + + finish: function() { + this.length = this.pos; + this.pos = 0; + return this.buf.subarray(0, this.length); + }, + + writeFixed32: function(val) { + this.realloc(4); + writeInt32(this.buf, val, this.pos); + this.pos += 4; + }, + + writeSFixed32: function(val) { + this.realloc(4); + writeInt32(this.buf, val, this.pos); + this.pos += 4; + }, + + writeFixed64: function(val) { + this.realloc(8); + writeInt32(this.buf, val & -1, this.pos); + writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4); + this.pos += 8; + }, + + writeSFixed64: function(val) { + this.realloc(8); + writeInt32(this.buf, val & -1, this.pos); + writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4); + this.pos += 8; + }, + + writeVarint: function(val) { + val = +val || 0; + + if (val > 0xfffffff || val < 0) { + writeBigVarint(val, this); + return; + } + + this.realloc(4); + + this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return; + this.buf[this.pos++] = (val >>> 7) & 0x7f; + }, + + writeSVarint: function(val) { + this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2); + }, + + writeBoolean: function(val) { + this.writeVarint(Boolean(val)); + }, + + writeString: function(str) { + str = String(str); + this.realloc(str.length * 4); + + this.pos++; // reserve 1 byte for short string length + + var startPos = this.pos; + // write the string directly to the buffer and see how much was written + this.pos = writeUtf8(this.buf, str, this.pos); + var len = this.pos - startPos; + + if (len >= 0x80) makeRoomForExtraLength(startPos, len, this); + + // finally, write the message length in the reserved place and restore the position + this.pos = startPos - 1; + this.writeVarint(len); + this.pos += len; + }, + + writeFloat: function(val) { + this.realloc(4); + ieee754.write(this.buf, val, this.pos, true, 23, 4); + this.pos += 4; + }, + + writeDouble: function(val) { + this.realloc(8); + ieee754.write(this.buf, val, this.pos, true, 52, 8); + this.pos += 8; + }, + + writeBytes: function(buffer) { + var len = buffer.length; + this.writeVarint(len); + this.realloc(len); + for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i]; + }, + + writeRawMessage: function(fn, obj) { + this.pos++; // reserve 1 byte for short message length + + // write the message directly to the buffer and see how much was written + var startPos = this.pos; + fn(obj, this); + var len = this.pos - startPos; + + if (len >= 0x80) makeRoomForExtraLength(startPos, len, this); + + // finally, write the message length in the reserved place and restore the position + this.pos = startPos - 1; + this.writeVarint(len); + this.pos += len; + }, + + writeMessage: function(tag, fn, obj) { + this.writeTag(tag, Pbf.Bytes); + this.writeRawMessage(fn, obj); + }, + + writePackedVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedVarint, arr); }, + writePackedSVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSVarint, arr); }, + writePackedBoolean: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedBoolean, arr); }, + writePackedFloat: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFloat, arr); }, + writePackedDouble: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedDouble, arr); }, + writePackedFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed32, arr); }, + writePackedSFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed32, arr); }, + writePackedFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed64, arr); }, + writePackedSFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed64, arr); }, + + writeBytesField: function(tag, buffer) { + this.writeTag(tag, Pbf.Bytes); + this.writeBytes(buffer); + }, + writeFixed32Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeFixed32(val); + }, + writeSFixed32Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeSFixed32(val); + }, + writeFixed64Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeFixed64(val); + }, + writeSFixed64Field: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeSFixed64(val); + }, + writeVarintField: function(tag, val) { + this.writeTag(tag, Pbf.Varint); + this.writeVarint(val); + }, + writeSVarintField: function(tag, val) { + this.writeTag(tag, Pbf.Varint); + this.writeSVarint(val); + }, + writeStringField: function(tag, str) { + this.writeTag(tag, Pbf.Bytes); + this.writeString(str); + }, + writeFloatField: function(tag, val) { + this.writeTag(tag, Pbf.Fixed32); + this.writeFloat(val); + }, + writeDoubleField: function(tag, val) { + this.writeTag(tag, Pbf.Fixed64); + this.writeDouble(val); + }, + writeBooleanField: function(tag, val) { + this.writeVarintField(tag, Boolean(val)); + } +}; + +function readVarintRemainder(l, s, p) { + var buf = p.buf, + h, b; + + b = buf[p.pos++]; h = (b & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s); + b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s); + + throw new Error('Expected varint not more than 10 bytes'); +} + +function readPackedEnd(pbf) { + return pbf.type === Pbf.Bytes ? + pbf.readVarint() + pbf.pos : pbf.pos + 1; +} + +function toNum(low, high, isSigned) { + if (isSigned) { + return high * 0x100000000 + (low >>> 0); + } + + return ((high >>> 0) * 0x100000000) + (low >>> 0); +} + +function writeBigVarint(val, pbf) { + var low, high; + + if (val >= 0) { + low = (val % 0x100000000) | 0; + high = (val / 0x100000000) | 0; + } else { + low = ~(-val % 0x100000000); + high = ~(-val / 0x100000000); + + if (low ^ 0xffffffff) { + low = (low + 1) | 0; + } else { + low = 0; + high = (high + 1) | 0; + } + } + + if (val >= 0x10000000000000000 || val < -0x10000000000000000) { + throw new Error('Given varint doesn\'t fit into 10 bytes'); + } + + pbf.realloc(10); + + writeBigVarintLow(low, high, pbf); + writeBigVarintHigh(high, pbf); +} + +function writeBigVarintLow(low, high, pbf) { + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7; + pbf.buf[pbf.pos] = low & 0x7f; +} + +function writeBigVarintHigh(high, pbf) { + var lsb = (high & 0x07) << 4; + + pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return; + pbf.buf[pbf.pos++] = high & 0x7f; +} + +function makeRoomForExtraLength(startPos, len, pbf) { + var extraLen = + len <= 0x3fff ? 1 : + len <= 0x1fffff ? 2 : + len <= 0xfffffff ? 3 : Math.floor(Math.log(len) / (Math.LN2 * 7)); + + // if 1 byte isn't enough for encoding message length, shift the data to the right + pbf.realloc(extraLen); + for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i]; +} + +function writePackedVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]); } +function writePackedSVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]); } +function writePackedFloat(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]); } +function writePackedDouble(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]); } +function writePackedBoolean(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]); } +function writePackedFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]); } +function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); } +function writePackedFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]); } +function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); } + +// Buffer code below from https://github.com/feross/buffer, MIT-licensed + +function readUInt32(buf, pos) { + return ((buf[pos]) | + (buf[pos + 1] << 8) | + (buf[pos + 2] << 16)) + + (buf[pos + 3] * 0x1000000); +} + +function writeInt32(buf, val, pos) { + buf[pos] = val; + buf[pos + 1] = (val >>> 8); + buf[pos + 2] = (val >>> 16); + buf[pos + 3] = (val >>> 24); +} + +function readInt32(buf, pos) { + return ((buf[pos]) | + (buf[pos + 1] << 8) | + (buf[pos + 2] << 16)) + + (buf[pos + 3] << 24); +} + +function readUtf8(buf, pos, end) { + var str = ''; + var i = pos; + + while (i < end) { + var b0 = buf[i]; + var c = null; // codepoint + var bytesPerSequence = + b0 > 0xEF ? 4 : + b0 > 0xDF ? 3 : + b0 > 0xBF ? 2 : 1; + + if (i + bytesPerSequence > end) break; + + var b1, b2, b3; + + if (bytesPerSequence === 1) { + if (b0 < 0x80) { + c = b0; + } + } else if (bytesPerSequence === 2) { + b1 = buf[i + 1]; + if ((b1 & 0xC0) === 0x80) { + c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F); + if (c <= 0x7F) { + c = null; + } + } + } else if (bytesPerSequence === 3) { + b1 = buf[i + 1]; + b2 = buf[i + 2]; + if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) { + c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F); + if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) { + c = null; + } + } + } else if (bytesPerSequence === 4) { + b1 = buf[i + 1]; + b2 = buf[i + 2]; + b3 = buf[i + 3]; + if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) { + c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F); + if (c <= 0xFFFF || c >= 0x110000) { + c = null; + } + } + } + + if (c === null) { + c = 0xFFFD; + bytesPerSequence = 1; + + } else if (c > 0xFFFF) { + c -= 0x10000; + str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800); + c = 0xDC00 | c & 0x3FF; + } + + str += String.fromCharCode(c); + i += bytesPerSequence; + } + + return str; +} + +function readUtf8TextDecoder(buf, pos, end) { + return utf8TextDecoder.decode(buf.subarray(pos, end)); +} + +function writeUtf8(buf, str, pos) { + for (var i = 0, c, lead; i < str.length; i++) { + c = str.charCodeAt(i); // code point + + if (c > 0xD7FF && c < 0xE000) { + if (lead) { + if (c < 0xDC00) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + lead = c; + continue; + } else { + c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000; + lead = null; + } + } else { + if (c > 0xDBFF || (i + 1 === str.length)) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + } else { + lead = c; + } + continue; + } + } else if (lead) { + buf[pos++] = 0xEF; + buf[pos++] = 0xBF; + buf[pos++] = 0xBD; + lead = null; + } + + if (c < 0x80) { + buf[pos++] = c; + } else { + if (c < 0x800) { + buf[pos++] = c >> 0x6 | 0xC0; + } else { + if (c < 0x10000) { + buf[pos++] = c >> 0xC | 0xE0; + } else { + buf[pos++] = c >> 0x12 | 0xF0; + buf[pos++] = c >> 0xC & 0x3F | 0x80; + } + buf[pos++] = c >> 0x6 & 0x3F | 0x80; + } + buf[pos++] = c & 0x3F | 0x80; + } + } + return pos; +} diff --git a/node_modules/pbf/package.json b/node_modules/pbf/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c6c921d137c8e72747a045ad9c94166ebe75ce3e --- /dev/null +++ b/node_modules/pbf/package.json @@ -0,0 +1,81 @@ +{ + "name": "pbf", + "version": "3.3.0", + "description": "a low-level, lightweight protocol buffers implementation in JavaScript", + "main": "index.js", + "unpkg": "dist/pbf.js", + "jsdelivr": "dist/pbf.js", + "scripts": { + "bench": "node bench/bench.js", + "pretest": "eslint index.js compile.js test/*.js bench/bench-tiles.js bin/pbf", + "test": "node --test", + "cov": "node --test --experimental-test-covetage", + "build-min": "mkdirp dist && browserify index.js -s Pbf | uglifyjs -c -m > dist/pbf.js", + "build-dev": "mkdirp dist && browserify index.js -d -s Pbf > dist/pbf-dev.js", + "prepublishOnly": "npm run build-dev && npm run build-min" + }, + "files": [ + "bin", + "dist", + "compile.js" + ], + "bin": { + "pbf": "bin/pbf" + }, + "repository": { + "type": "git", + "url": "git@github.com:mapbox/pbf.git" + }, + "keywords": [ + "protocol", + "buffer", + "pbf", + "protobuf", + "binary", + "format", + "serialization", + "encoder", + "decoder" + ], + "author": "Konstantin Kaefer", + "license": "BSD-3-Clause", + "bugs": { + "url": "https://github.com/mapbox/pbf/issues" + }, + "homepage": "https://github.com/mapbox/pbf", + "dependencies": { + "ieee754": "^1.1.12", + "resolve-protobuf-schema": "^2.1.0" + }, + "devDependencies": { + "benchmark": "^2.1.4", + "browserify": "^17.0.0", + "eslint": "^8.57.0", + "eslint-config-mourner": "^2.0.3", + "mkdirp": "^3.0.1", + "protobufjs": "^7.3.2", + "protocol-buffers": "^5.0.0", + "tile-stats-runner": "^1.0.0", + "uglify-js": "^3.18.0" + }, + "eslintConfig": { + "extends": "mourner", + "rules": { + "space-before-function-paren": [ + 2, + "never" + ], + "key-spacing": 0, + "no-empty": 0, + "global-require": 0, + "no-cond-assign": 0, + "indent": [ + 2, + 4, + { + "flatTernaryExpressions": true + } + ] + } + } +} diff --git a/node_modules/pbkdf2/.eslintrc b/node_modules/pbkdf2/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..9788295079c3c5e97931b791dfcd72301e86ae58 --- /dev/null +++ b/node_modules/pbkdf2/.eslintrc @@ -0,0 +1,46 @@ +{ + "root": true, + + "extends": "@ljharb", + + "globals": { + "Uint8Array": "readonly", + "Uint16Array": "readonly", + "Uint32Array": "readonly", + "Int8Array": "readonly", + "Int16Array": "readonly", + "Int32Array": "readonly", + "Float32Array": "readonly", + "Float64Array": "readonly", + "BigInt64Array": "readonly", + "BigUint64Array": "readonly", + }, + + "rules": { + "complexity": "off", + "func-style": "warn", + "max-params": "warn", + "multiline-comment-style": "off", + "no-param-reassign": "warn", + "sort-keys": "warn", + }, + + "ignorePatterns": [ + "test/bundle.js", + ], + + "overrides": [ + { + "files": "bench/*", + "extends": "@ljharb/eslint-config/node/4", + "rules": { + "func-style": "warn", + "max-params": "warn", + "no-param-reassign": "warn", + "no-var": "off", + "prefer-arrow-callback": "off", + "prefer-template": "off", + }, + }, + ], +} diff --git a/node_modules/pbkdf2/.github/FUNDING.yml b/node_modules/pbkdf2/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..ca4853ac3631075e297e59733816d06874c369bc --- /dev/null +++ b/node_modules/pbkdf2/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/pbkdf2 +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/pbkdf2/.nycrc b/node_modules/pbkdf2/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..d37607e060ddd54892e13944ee5d387b39a4f385 --- /dev/null +++ b/node_modules/pbkdf2/.nycrc @@ -0,0 +1,10 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "bench", + "coverage", + "test" + ] +} diff --git a/node_modules/pbkdf2/CHANGELOG.md b/node_modules/pbkdf2/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..3fd6d8f9a9516700634296b9b51a9b3f440bcdc2 --- /dev/null +++ b/node_modules/pbkdf2/CHANGELOG.md @@ -0,0 +1,361 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v3.1.5](https://github.com/browserify/pbkdf2/compare/v3.1.4...v3.1.5) - 2025-09-23 + +### Commits + +- [Fix] only allow finite iterations [`67bd94d`](https://github.com/browserify/pbkdf2/commit/67bd94dbbf21b93f5e282ee910728945c8ef2827) +- [Fix] restore node 0.10 support [`8f59d96`](https://github.com/browserify/pbkdf2/commit/8f59d962f71dcb2cc14067d7f514ff96e3406f81) +- [Fix] check parameters before the "no Promise" bailout [`d2dc5f0`](https://github.com/browserify/pbkdf2/commit/d2dc5f052cacadf3d4a09d87164158da875ca740) + +## [v3.1.4](https://github.com/browserify/pbkdf2/compare/v3.1.3...v3.1.4) - 2025-09-22 + +### Commits + +- [Deps] update `create-hash`, `ripemd160`, `sha.js`, `to-buffer` [`8dbf49b`](https://github.com/browserify/pbkdf2/commit/8dbf49b38235066c565a92eaf3722720a1333a2d) +- [meta] update repo URLs [`d15bc35`](https://github.com/browserify/pbkdf2/commit/d15bc351de0edbed394d2a6189176960aaa0d050) +- [Dev Deps] update `@ljharb/eslint-config` [`aaf870b`](https://github.com/browserify/pbkdf2/commit/aaf870b1d1855e6a381af05021f304294a79f7c9) + +## [v3.1.3](https://github.com/browserify/pbkdf2/compare/v3.1.2...v3.1.3) - 2025-06-20 + +### Commits + +- Only apps should have lockfiles [`8b06730`](https://github.com/browserify/pbkdf2/commit/8b067308eedcc3b7da3e06202d437ff532de75bd) +- [lint] fix whitespace [`9a76e2f`](https://github.com/browserify/pbkdf2/commit/9a76e2f37ef4541aeff92d97b7335b7fa6e989a8) +- [lint] fix parens/curlies/semis/etc [`6fd84bf`](https://github.com/browserify/pbkdf2/commit/6fd84bf64a423d207d9e665f3e9fd88b148c4480) +- [meta] add `auto-changelog` [`796c38d`](https://github.com/browserify/pbkdf2/commit/796c38d428ed9546e7ddfbb38322faa99921d716) +- [Tests] fix tests in node 17 [`3661fb0`](https://github.com/browserify/pbkdf2/commit/3661fb0156177bfe380c7bcc133917e7ee501bc7) +- Revert "[Tests] fix tests in node < 3" [`7431b57`](https://github.com/browserify/pbkdf2/commit/7431b5766805cbf880c1b3d0f38d484357844ff7) +- [Tests] fix tests in node < 3 [`eb9f97a`](https://github.com/browserify/pbkdf2/commit/eb9f97a66ed83836bebc4ff563a1588248708501) +- [Fix] ensure unknown algorithms throw + known ones match node [`26d4fd3`](https://github.com/browserify/pbkdf2/commit/26d4fd391e00ed806840ea1ef7341937985f4ba8) +- [Tests] add GHA, always run nyc [`513906a`](https://github.com/browserify/pbkdf2/commit/513906a735e80a0e125e1a3363c5dbe90bb34bb7) +- [lint] fix a few more rules [`ab04da8`](https://github.com/browserify/pbkdf2/commit/ab04da834a0342cb3779486314fa67ebc1e3f035) +- [lint] switch to eslint [`89694cf`](https://github.com/browserify/pbkdf2/commit/89694cf7e4062a8c924fbe74ad2b2d3cf78f1715) +- [Tests] add coverage [`d0d534b`](https://github.com/browserify/pbkdf2/commit/d0d534bfdc4db6d6ea9f719606ad18a78db6c124) +- [Refactor] use `to-buffer` [`e3102a8`](https://github.com/browserify/pbkdf2/commit/e3102a8cd4830a3ac85cd0dd011cc002fdde33bb) +- [readme] improve badges [`fca0c9d`](https://github.com/browserify/pbkdf2/commit/fca0c9d4c5b053d911315a3607367d1db9f9f605) +- [Tests] remove unused travis file [`a2c7d93`](https://github.com/browserify/pbkdf2/commit/a2c7d93bbcad73c49dad0c18fef6b8a4af8c3310) +- [meta] switch from `files` to `npmignore` [`7f31fbc`](https://github.com/browserify/pbkdf2/commit/7f31fbca528fa5af3b7d3910daf09a7e5ed8adb4) +- [Tests] use .nycrc [`8d628e8`](https://github.com/browserify/pbkdf2/commit/8d628e8d5559b4acd4d4a714afb04a2990f901b7) +- [Refactor] minor tweaks [`fc61005`](https://github.com/browserify/pbkdf2/commit/fc61005c8cbd480e24ee103ac39a45f0d90ac636) +- [Deps] update `create-hmac`, `safe-buffer`, `sha.js` [`ae2a7d0`](https://github.com/browserify/pbkdf2/commit/ae2a7d051c9133c25d5212ba4f46747c0ed4c190) +- [Fix] pin `create-hash`, `ripemd160` due to breaking changes [`e079968`](https://github.com/browserify/pbkdf2/commit/e07996890af79296f1913431fb3b252e25df2f0e) +- [Tests] fix tests in node 3 [`45fbcf3`](https://github.com/browserify/pbkdf2/commit/45fbcf30431f9585ae3b61f2207c0a16c1953915) +- [meta] skip publishing benchmarks [`19ea57b`](https://github.com/browserify/pbkdf2/commit/19ea57bf11d055ddcd97d2556cd3097663b050b9) +- [Dev Deps] add missing peer dep [`645e252`](https://github.com/browserify/pbkdf2/commit/645e252375087e97beb95e518038b99eb5724c5b) + +## [v3.1.2](https://github.com/browserify/pbkdf2/compare/v3.1.1...v3.1.2) - 2021-04-09 + +### Commits + +- handle nextTick [`36457b9`](https://github.com/browserify/pbkdf2/commit/36457b9fecfd1e128c8e9884a57e277649679832) +- Check for process before accessing [`449e510`](https://github.com/browserify/pbkdf2/commit/449e510f861f56ed673613d8102f6b1a3e680ced) +- handle different returns [`fb82137`](https://github.com/browserify/pbkdf2/commit/fb82137ecefb56b5e93b70686e0dc0b4bb591b7c) + +## [v3.1.1](https://github.com/browserify/pbkdf2/compare/v3.1.0...v3.1.1) - 2020-06-04 + +### Commits + +- style nit [`6d994f2`](https://github.com/browserify/pbkdf2/commit/6d994f2e71934c26f96791bde440e86d9d93ff2b) +- remove arrow [`70ea270`](https://github.com/browserify/pbkdf2/commit/70ea2709b761b8fbb0551f4411feb52efb9c8690) + +## [v3.1.0](https://github.com/browserify/pbkdf2/compare/v3.0.17...v3.1.0) - 2020-06-03 + +### Merged + +- check if process.version is available [`#85`](https://github.com/browserify/pbkdf2/pull/85) + +### Commits + +- fix style [`1674cbd`](https://github.com/browserify/pbkdf2/commit/1674cbdb359ae166e6c99733e0af40e92ebb3cd4) +- add support for all ArrayBuffers [`b888820`](https://github.com/browserify/pbkdf2/commit/b88882005853ad5d8ecbc00a56e101c336b5ea04) +- Build type check into toBuffer [`0b77ea9`](https://github.com/browserify/pbkdf2/commit/0b77ea96191a374fa6774ebaa4fe89be86c3d1af) +- fix fixtures [`6af65e7`](https://github.com/browserify/pbkdf2/commit/6af65e797f5c0738fd9f4e9dfa9b00ae0885f5d7) +- Add tests for Uint8Array [`bca4182`](https://github.com/browserify/pbkdf2/commit/bca4182a30ce5d73ed527fa254c6d3a62e07e8f8) +- fix encodings [`b1c669b`](https://github.com/browserify/pbkdf2/commit/b1c669b6dfa9a0f82cecdec7bd4a14a042d9a070) +- minor fixes for Uint8Array support [`f61abc7`](https://github.com/browserify/pbkdf2/commit/f61abc7596d40540d5d759bc583044082c52badc) +- fix tests [`ab62504`](https://github.com/browserify/pbkdf2/commit/ab6250458dac29f4f9d7144e903e18726bed8535) +- Add Uint8Array support [`3fbb793`](https://github.com/browserify/pbkdf2/commit/3fbb7935e2aa810a5ed861ef32c44092fb3fafbb) +- adjust node versions [`a572cbc`](https://github.com/browserify/pbkdf2/commit/a572cbc655a1cc626ae72ccf8bb29f25418d394e) +- update travis [`4a4deed`](https://github.com/browserify/pbkdf2/commit/4a4deed4d115d55a698cf1292abef4f38cdbe922) +- fix standard typo (that was not caught locally for some reason) [`47c59ad`](https://github.com/browserify/pbkdf2/commit/47c59ad879f5fcce529a69ed902ca9b664813020) + +## [v3.0.17](https://github.com/browserify/pbkdf2/compare/v3.0.16...v3.0.17) - 2018-09-25 + +### Commits + +- Add ripemd160 test [`9da9d9c`](https://github.com/browserify/pbkdf2/commit/9da9d9c4f426237e72b8f189ae14e3e473c84c69) +- Do not inline rmd160Func [`b498c9b`](https://github.com/browserify/pbkdf2/commit/b498c9b779c40823fc504764c9a333fd44c79f31) +- Fix RIPEMD160 support [`68729a6`](https://github.com/browserify/pbkdf2/commit/68729a6b54e1438e1960931fd6aa3bb343fcc173) + +## [v3.0.16](https://github.com/browserify/pbkdf2/compare/v3.0.15...v3.0.16) - 2018-04-20 + +### Merged + +- default to SHA1 for native [`#76`](https://github.com/browserify/pbkdf2/pull/76) + +### Commits + +- fix standard indentation [`740d93e`](https://github.com/browserify/pbkdf2/commit/740d93e2f5798bc66d32d3a648ec2d96f7254c12) +- tests: fix JS/sync tests not being run [`1416637`](https://github.com/browserify/pbkdf2/commit/1416637d82848494bd427a38643a58795213191f) +- increase sync.js internal coverage [`4e07660`](https://github.com/browserify/pbkdf2/commit/4e076601b82e518cac6179ea62cc4f3c4553e43b) +- travis: add 8 and 9 [`d82c51b`](https://github.com/browserify/pbkdf2/commit/d82c51bb04897f099512b3add9f892a36a71cedc) + +## [v3.0.15](https://github.com/browserify/pbkdf2/compare/v3.0.14...v3.0.15) - 2018-04-01 + +### Merged + +- Throw if password / salt is not a buffer or string [`#77`](https://github.com/browserify/pbkdf2/pull/77) +- Update README.md for async recommendation [`#75`](https://github.com/browserify/pbkdf2/pull/75) + +### Commits + +- throw if password / salt is not a buffer or string [`2410eb0`](https://github.com/browserify/pbkdf2/commit/2410eb0ee1f41da47d1ba2e53411b489d88838ce) +- typos [`9dae437`](https://github.com/browserify/pbkdf2/commit/9dae437df90f5940eb332a5c6f86f78309f79f06) +- Update README.md [`ad85843`](https://github.com/browserify/pbkdf2/commit/ad8584337742d4cf83d9244a73abce2a7af90ff2) + +## [v3.0.14](https://github.com/browserify/pbkdf2/compare/v3.0.13...v3.0.14) - 2017-09-08 + +### Merged + +- use the local implementations if crypto.bpkdf2Sync [`#72`](https://github.com/browserify/pbkdf2/pull/72) + +### Commits + +- use the local implementations if *either* crypto.bpkdf2Sync doesn't exist OR it doesn't contain the marker string [`9132b7a`](https://github.com/browserify/pbkdf2/commit/9132b7a81540a5743ece086bea87ada10028e05f) + +## [v3.0.13](https://github.com/browserify/pbkdf2/compare/v3.0.12...v3.0.13) - 2017-08-02 + +### Merged + +- fail better when node version loaded in browser [`#71`](https://github.com/browserify/pbkdf2/pull/71) +- remove unnecessary r, T values [`#68`](https://github.com/browserify/pbkdf2/pull/68) + +### Commits + +- tests: add dkLen < and > [`c3d2998`](https://github.com/browserify/pbkdf2/commit/c3d29981a600cd30fa57849ce12bf95d45bb4b8f) +- align definitions with assignment, formatting [`5c50528`](https://github.com/browserify/pbkdf2/commit/5c5052859b7ea4dba9484ce4ad0c1edfb507790b) +- lib/sync*: avoid inner-loop T copy [`74b80d3`](https://github.com/browserify/pbkdf2/commit/74b80d32640d1c90a4a6a90d99784dadc9d2d880) +- sync: align definitions with assignment [`c818cf1`](https://github.com/browserify/pbkdf2/commit/c818cf1bf6b7c23278ebd8196ebddc6b54c92c8c) +- remove unused r variable [`9e0d168`](https://github.com/browserify/pbkdf2/commit/9e0d1684abca98e08a1334b0ead141ebf6c91806) +- travis: drop 0.12 [`0985c3e`](https://github.com/browserify/pbkdf2/commit/0985c3e03cb4392a5f931c4a62869257f3feaeba) +- sync-browser: consistent exports [`90ac748`](https://github.com/browserify/pbkdf2/commit/90ac7488016ad97023d3b42795dc1da00b310490) +- just remove microtime [`0fa9638`](https://github.com/browserify/pbkdf2/commit/0fa9638dad5384d7afb8943c1e22d2e4a16957d4) +- standard --fix [`8281fc6`](https://github.com/browserify/pbkdf2/commit/8281fc64b281bacab50f4b735aa768474eaaadcd) + +## [v3.0.12](https://github.com/browserify/pbkdf2/compare/v3.0.11...v3.0.12) - 2017-05-11 + +### Merged + +- fix #60 - use browser.js in the browser, instead of index.js; include lib folder in the published package [`#62`](https://github.com/browserify/pbkdf2/pull/62) + +### Fixed + +- fix #60 - use browser.js in the browser, instead of index.js; include lib folder in the published package (#62) [`#60`](https://github.com/browserify/pbkdf2/issues/60) + +### Commits + +- switch to optional dep #63, 65 [`7d246e9`](https://github.com/browserify/pbkdf2/commit/7d246e91bbdaedbb55fa0c323306cbcc58d9ec73) + +## [v3.0.11](https://github.com/browserify/pbkdf2/compare/v3.0.10...v3.0.11) - 2017-05-11 + +### Commits + +- update files [`3313867`](https://github.com/browserify/pbkdf2/commit/3313867fd5dd5fcce716b4c195556f5c329cbdd5) + +## [v3.0.10](https://github.com/browserify/pbkdf2/compare/v3.0.9...v3.0.10) - 2017-05-11 + +### Merged + +- node for the node, js for the browser [`#59`](https://github.com/browserify/pbkdf2/pull/59) +- real optimizations [`#57`](https://github.com/browserify/pbkdf2/pull/57) +- benchmark [`#56`](https://github.com/browserify/pbkdf2/pull/56) +- do our own hmacing [`#54`](https://github.com/browserify/pbkdf2/pull/54) + +### Commits + +- use native crypto when available [`cdaf5c0`](https://github.com/browserify/pbkdf2/commit/cdaf5c0da8502c47a40d2b2caaafb497836e3b42) +- actually add bench [`fa2e0a1`](https://github.com/browserify/pbkdf2/commit/fa2e0a106adf8f2b2529bb9912f16d07f061cb17) +- passing tests [`216a6a7`](https://github.com/browserify/pbkdf2/commit/216a6a7d137ba5a363d1be9c3a7a42d47398429e) +- hmac ourselves [`9699045`](https://github.com/browserify/pbkdf2/commit/9699045c37a07f8319cfb8d44e2ff4252d7a7078) +- use hashes directly [`89e0e80`](https://github.com/browserify/pbkdf2/commit/89e0e80dbce67e16b8946deb38dc755aeea78222) +- correctly test both [`fb56873`](https://github.com/browserify/pbkdf2/commit/fb56873fa885059a8c17410eba0b544e5932cd28) +- avoid Buffer.concat [`96518aa`](https://github.com/browserify/pbkdf2/commit/96518aac66af803a0040e3bd1ca48b2828f38881) +- formatting [`dd3467c`](https://github.com/browserify/pbkdf2/commit/dd3467c75abd0136fc93f2acdbf1df94af10924f) +- some fixes [`15b2cbf`](https://github.com/browserify/pbkdf2/commit/15b2cbfd9c3575593fc147dbd170e23c293a6f12) +- cleanup [`fec6652`](https://github.com/browserify/pbkdf2/commit/fec66520e38de3b2fccaf924dd61807bf500ad36) +- formating [`dc2e15a`](https://github.com/browserify/pbkdf2/commit/dc2e15aa0f25b091a94fd575eb0edbd41c2300b0) +- fix coverage [`ae3f2a5`](https://github.com/browserify/pbkdf2/commit/ae3f2a5d0b475d0f4fb5a38b7ce6c9206a4a0c9b) +- move stuff around [`52c3960`](https://github.com/browserify/pbkdf2/commit/52c3960b217a9933e8ef8a833b9a60141ddbd70a) +- 100% [`ef38b2b`](https://github.com/browserify/pbkdf2/commit/ef38b2b9bb02bb4167689ab8955a0b323c03d644) +- trailing space [`03832fb`](https://github.com/browserify/pbkdf2/commit/03832fbdd47fb354329bdbb51c463ed60033e2ea) +- reduce coverage [`2f720b4`](https://github.com/browserify/pbkdf2/commit/2f720b4b4d3441f743d1637a479cda596c39b4a9) +- switch to optional dep [`8423738`](https://github.com/browserify/pbkdf2/commit/8423738759f67929760c828cadd88c5867d4e5f2) +- fix style [`5b33204`](https://github.com/browserify/pbkdf2/commit/5b33204d0172b06d7d93238ef72a1240b3e3f3c6) + +## [v3.0.9](https://github.com/browserify/pbkdf2/compare/v3.0.8...v3.0.9) - 2016-10-05 + +### Merged + +- protect 0.10 users by throwing [`#47`](https://github.com/browserify/pbkdf2/pull/47) + +### Commits + +- warn 0.10 users by throwing [`5e63f63`](https://github.com/browserify/pbkdf2/commit/5e63f63c149182f617b209d0419c408691b918d7) + +## [v3.0.8](https://github.com/browserify/pbkdf2/compare/v3.0.7...v3.0.8) - 2016-09-22 + +### Fixed + +- package: add engines [`#46`](https://github.com/browserify/pbkdf2/issues/46) + +### Commits + +- package: 1 too many indentations [`bffd057`](https://github.com/browserify/pbkdf2/commit/bffd0578fd2eb892a36cfd830fadc535deae9a49) +- package: 90% branch coverage is fine for now [`c3d57f9`](https://github.com/browserify/pbkdf2/commit/c3d57f96666f556034b8b59839b28b7fa7c342e9) + +## [v3.0.7](https://github.com/browserify/pbkdf2/compare/v3.0.6...v3.0.7) - 2016-09-16 + +### Merged + +- browser: avoid process.version split before process.browser [`#44`](https://github.com/browserify/pbkdf2/pull/44) + +## [v3.0.6](https://github.com/browserify/pbkdf2/compare/v3.0.5...v3.0.6) - 2016-09-14 + +### Merged + +- tests: fix UTF-8 encoding [`#42`](https://github.com/browserify/pbkdf2/pull/42) +- Add browserify dependency, rename index.html to bundle.html [`#41`](https://github.com/browserify/pbkdf2/pull/41) +- package: add browser.js [`#39`](https://github.com/browserify/pbkdf2/pull/39) + +### Commits + +- add browserify and remove mocha from test/index.html [`f28965d`](https://github.com/browserify/pbkdf2/commit/f28965d0a494e9f6f95f616bb3f608d3a15bff9c) +- rename index.html to bundle.html [`7d850d2`](https://github.com/browserify/pbkdf2/commit/7d850d247a93122a5e1b60fabddf64f7958cfeeb) + +## [v3.0.5](https://github.com/browserify/pbkdf2/compare/3.0.4...v3.0.5) - 2016-09-12 + +### Merged + +- use tape instead of mocha [`#35`](https://github.com/browserify/pbkdf2/pull/35) +- tests: remove binary assumption, fixes #34 [`#36`](https://github.com/browserify/pbkdf2/pull/36) +- README: add documentation, close #31 [`#33`](https://github.com/browserify/pbkdf2/pull/33) +- fix coverage [`#32`](https://github.com/browserify/pbkdf2/pull/32) +- [trivial] update README.md [`#28`](https://github.com/browserify/pbkdf2/pull/28) +- [trivial] rename async-shim.js to node-shim-async.js [`#29`](https://github.com/browserify/pbkdf2/pull/29) +- update travis & standard [`#24`](https://github.com/browserify/pbkdf2/pull/24) +- browser: delay async computation, fixes #13 [`#14`](https://github.com/browserify/pbkdf2/pull/14) + +### Fixed + +- Merge pull request #36 from crypto-browserify/testfix [`#34`](https://github.com/browserify/pbkdf2/issues/34) +- tests: remove binary assumption, fixes #34 [`#34`](https://github.com/browserify/pbkdf2/issues/34) +- Merge pull request #33 from crypto-browserify/dcousens-patch-1 [`#31`](https://github.com/browserify/pbkdf2/issues/31) +- README: add documentation, close #31 [`#31`](https://github.com/browserify/pbkdf2/issues/31) +- README: fix pbkdf2 spelling, resolves #20 [`#20`](https://github.com/browserify/pbkdf2/issues/20) +- Merge pull request #14 from crypto-browserify/dcousens-patch-1 [`#13`](https://github.com/browserify/pbkdf2/issues/13) +- browser: delay async computation, fixes #13 [`#13`](https://github.com/browserify/pbkdf2/issues/13) + +### Commits + +- add node-shim.js [`5eaa6ba`](https://github.com/browserify/pbkdf2/commit/5eaa6baa87564ab46775d1b8d547dd0f4ca8515b) +- browser: default the encoding [`94e7979`](https://github.com/browserify/pbkdf2/commit/94e79791fcab6c91cc5cb773857e2d51783edada) +- update tests [`931b7d5`](https://github.com/browserify/pbkdf2/commit/931b7d527a7a46e7518506680a1d431e6eb24dd3) +- package: update standard [`dd02315`](https://github.com/browserify/pbkdf2/commit/dd02315c41b8339d14c656c7e70ba433c893b36f) +- move checkParameters to separate file [`93ffd51`](https://github.com/browserify/pbkdf2/commit/93ffd519878f22d881a36eadcde4ad3e710caecc) +- tests: merge to avoid double up of code [`59f6577`](https://github.com/browserify/pbkdf2/commit/59f6577f8783d6e71a99988397c3a1e0811ed6d5) +- travis: update config [`7ab61b4`](https://github.com/browserify/pbkdf2/commit/7ab61b401c7c3d40bcb16d98bab97143c89d97e1) +- update README.md [`8bf4958`](https://github.com/browserify/pbkdf2/commit/8bf4958da1da9a8a5d13cbe91aff0fe9e632371c) +- pull out type checking [`e6b815f`](https://github.com/browserify/pbkdf2/commit/e6b815fa4c0b2edf222c663c7b5d761dddf23d57) +- browser: s/testParams/checkParameters/ [`7730a55`](https://github.com/browserify/pbkdf2/commit/7730a552e89e09da0d8a42b56f8a376c851b2c11) +- package: add files field to package.json [`3ee45ed`](https://github.com/browserify/pbkdf2/commit/3ee45ed1bd6b751d7918075b2a76d166eb61ae8a) +- rename async-shim.js to node-shim-async.js [`2268e11`](https://github.com/browserify/pbkdf2/commit/2268e11ad301ebf377a1f859e05214bdf3622919) +- browser: return null for error [`c470de1`](https://github.com/browserify/pbkdf2/commit/c470de18779fcb0f998d8c542bad5787dfb5f5f1) +- .travis: test node 6 [`9f949d4`](https://github.com/browserify/pbkdf2/commit/9f949d46d9392be9e937e2916df7863ac17f2815) + +## [3.0.4](https://github.com/browserify/pbkdf2/compare/v3.0.3...3.0.4) - 2015-03-27 + +### Merged + +- Fix shim encoding and more reliably close child process [`#12`](https://github.com/browserify/pbkdf2/pull/12) + +### Commits + +- async errors and exiting [`2bcfba8`](https://github.com/browserify/pbkdf2/commit/2bcfba85216694c10663540b34a4e3b400c205ed) +- tests: add failing utf8 test [`ea1ddaf`](https://github.com/browserify/pbkdf2/commit/ea1ddaf28d06a288a955ae41b717011c1596fb0b) +- fix 2 types of errors [`0cbba29`](https://github.com/browserify/pbkdf2/commit/0cbba29b0a81a7acf2619fd49ab5b9f40c47bfa8) +- fix standard formatting issues [`93b06d3`](https://github.com/browserify/pbkdf2/commit/93b06d3762fdb850d5532e0f63b8051515db666f) +- fix shim encoding [`a57d9c6`](https://github.com/browserify/pbkdf2/commit/a57d9c6b37fba515eb6a83cf8239bcd67356a203) +- index/browser: rename MAX_INT to MAX_ALLOC [`9f6fb05`](https://github.com/browserify/pbkdf2/commit/9f6fb05b7284bc0fc72cde6e37524deffdc2d3a8) +- package: use standard 3.0.0 [`941b46b`](https://github.com/browserify/pbkdf2/commit/941b46ba580918ec44bc0072b6ae0ecfa9fde277) + +## [v3.0.3](https://github.com/browserify/pbkdf2/compare/3.0.2...v3.0.3) - 2015-02-15 + +### Commits + +- repo name [`a6516d9`](https://github.com/browserify/pbkdf2/commit/a6516d9fa34bb250c2ef6e0d75ef7e47b7c1b1a4) +- change name [`471fb83`](https://github.com/browserify/pbkdf2/commit/471fb83c50fb1019b099fe9926fc28d3d25900e1) + +## [3.0.2](https://github.com/browserify/pbkdf2/compare/3.0.1...3.0.2) - 2015-02-15 + +### Merged + +- fix bug in encoding [`#10`](https://github.com/browserify/pbkdf2/pull/10) + +### Commits + +- tests: add non-printable fixture handling and example fixture [`040707d`](https://github.com/browserify/pbkdf2/commit/040707da888f4eb7737dd671a3e0c71875b94b2b) +- add 0.12 and iojs to travis [`45165c4`](https://github.com/browserify/pbkdf2/commit/45165c45bf2c1938431eed592eef5c087a43aa20) + +## [3.0.1](https://github.com/browserify/pbkdf2/compare/2.0.1...3.0.1) - 2015-01-29 + +### Commits + +- modularize [`68c6c36`](https://github.com/browserify/pbkdf2/commit/68c6c36e4a0af2862274d0a8effc82d0650a546d) +- all: standard cmpliance [`2f5ff3b`](https://github.com/browserify/pbkdf2/commit/2f5ff3ba739f84b2e51335c5f3cfacbf856bc587) +- add shim [`386d4af`](https://github.com/browserify/pbkdf2/commit/386d4afd32b1ea3384cc175d3993ada757836e01) +- add browser tests [`b88ad8d`](https://github.com/browserify/pbkdf2/commit/b88ad8d14ee02fefddb99f3b89c89ca51e90122f) +- package: add coveralls and re-order [`5834697`](https://github.com/browserify/pbkdf2/commit/58346973b7d2e45b9bb313e159b43e05ab5024ae) +- package: add standard test suite [`e504eed`](https://github.com/browserify/pbkdf2/commit/e504eed0a6e38846a752f9f49aa1b38ceb8dbd67) +- package: update repository URL [`b217d1a`](https://github.com/browserify/pbkdf2/commit/b217d1ab6c153e9899cbd96b29653f7da308d444) +- tests: remove unnecessary semicolon/vars [`24f8ab3`](https://github.com/browserify/pbkdf2/commit/24f8ab3b5d1928f5b87f50aa357475cd5855b03d) +- package: add coveralls [`c5b6d51`](https://github.com/browserify/pbkdf2/commit/c5b6d510bdbd5792b98e4d27daf94849c70b9d57) +- index: remove unnecessary __pbkdf2Export [`e51121f`](https://github.com/browserify/pbkdf2/commit/e51121f46887e545fedd817ac8624e0d68c9ace5) +- index: fix digest algorithm typo [`558b3dd`](https://github.com/browserify/pbkdf2/commit/558b3dd06bb17b782ee0c1994c5aed19624d4c3b) +- README: update repository URL [`f1fc7b4`](https://github.com/browserify/pbkdf2/commit/f1fc7b448f93e21a23bfe40f39670129f2ff31d6) +- package: latest devDependencies [`9624836`](https://github.com/browserify/pbkdf2/commit/9624836014c4976f8907273a4a77020b51a4fe8c) +- package: use latest create-hmac [`ffd5b94`](https://github.com/browserify/pbkdf2/commit/ffd5b943434dc78a36858f0bd61399aba6176617) +- package: update description [`7fbec99`](https://github.com/browserify/pbkdf2/commit/7fbec99bfc993d01161aae4c4b00c3718a8737f4) + +## [2.0.1](https://github.com/browserify/pbkdf2/compare/2.0.0...2.0.1) - 2014-09-25 + +### Merged + +- move istanbul to dev dependencies [`#1`](https://github.com/browserify/pbkdf2/pull/1) + +## [2.0.0](https://github.com/browserify/pbkdf2/compare/1.0.1...2.0.0) - 2014-09-24 + +### Commits + +- pbkdf2: add async impl. and invalid tests [`16d209e`](https://github.com/browserify/pbkdf2/commit/16d209ecd2e997ca775f32b47b8c2318a55ecdd8) +- README: update to latest API [`c2f01cf`](https://github.com/browserify/pbkdf2/commit/c2f01cf719063975dd943d8f6c280896f1c0958d) +- index: re-order var declarations [`8ad010d`](https://github.com/browserify/pbkdf2/commit/8ad010d6ad5869b06ec9a8c0d80650c9b517da7f) + +## 1.0.1 - 2014-09-17 + +### Commits + +- index: adds implementation [`1792996`](https://github.com/browserify/pbkdf2/commit/1792996f8f967ff5297990c498338b6790fc8a8b) +- fixtures: adds test fixtures [`33e999e`](https://github.com/browserify/pbkdf2/commit/33e999e8630ce967adc28f64462bdc98b5ab5a47) +- Initial commit [`f17b827`](https://github.com/browserify/pbkdf2/commit/f17b827efadd65634ab2f98de538b05ec526d959) +- package: adds package.json [`2782f71`](https://github.com/browserify/pbkdf2/commit/2782f7152d283c709e4700bf473f15069adcd5c5) +- README: add badges + usage instructions [`51ac17d`](https://github.com/browserify/pbkdf2/commit/51ac17db44d4b7e0b1bfc5995123dc5b2d031bc6) +- index: adhere to node.js spec [`98ec635`](https://github.com/browserify/pbkdf2/commit/98ec635aa4d0d4909048483de4080a19b86b45f4) +- travis: adds yml [`965f37f`](https://github.com/browserify/pbkdf2/commit/965f37fb409f1daffd01fad353bd923ed0aa2b2d) +- README: add credits [`aa9ac2f`](https://github.com/browserify/pbkdf2/commit/aa9ac2f38e74a834500ec1fdaa7fe14ca976b26d) +- README: no need for there [`0f6c37f`](https://github.com/browserify/pbkdf2/commit/0f6c37f10924fc3ceb8b2bf4074508e559454feb) diff --git a/node_modules/pbkdf2/LICENSE b/node_modules/pbkdf2/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a115b524273d9f160d142069ca51ec0d0f658ff5 --- /dev/null +++ b/node_modules/pbkdf2/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Daniel Cousens + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/pbkdf2/README.md b/node_modules/pbkdf2/README.md new file mode 100644 index 0000000000000000000000000000000000000000..230bab645b02dda72d2d19635cb0f456c8dd3bf5 --- /dev/null +++ b/node_modules/pbkdf2/README.md @@ -0,0 +1,48 @@ +# pbkdf2 [![Version Badge][2]][1] + +This library provides the functionality of PBKDF2 with the ability to use any supported hashing algorithm returned from `crypto.getHashes()` + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +## Usage + +```js +var pbkdf2 = require('pbkdf2') +var derivedKey = pbkdf2.pbkdf2Sync('password', 'salt', 1, 32, 'sha512') + +... +``` + +For more information on the API, please see the relevant [Node documentation](https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback). + +For high performance, use the `async` variant (`pbkdf2.pbkdf2`), not `pbkdf2.pbkdf2Sync`; this variant has the oppurtunity to use `window.crypto.subtle` when browserified. + + +## Credits + +This module is a derivative of [cryptocoinjs/pbkdf2-sha256](https://github.com/cryptocoinjs/pbkdf2-sha256/), so thanks to [JP Richardson](https://github.com/jprichardson/) for laying the ground work. + +Thank you to [FangDun Cai](https://github.com/fundon) for donating the package name on npm, if you're looking for his previous module it is located at [fundon/pbkdf2](https://github.com/fundon/pbkdf2). + +[1]: https://npmjs.org/package/pbkdf2 +[2]: https://versionbadg.es/browserify/pbkdf2.svg +[5]: https://david-dm.org/browserify/pbkdf2.svg +[6]: https://david-dm.org/browserify/pbkdf2 +[7]: https://david-dm.org/browserify/pbkdf2/dev-status.svg +[8]: https://david-dm.org/browserify/pbkdf2#info=devDependencies +[11]: https://nodei.co/npm/pbkdf2.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/pbkdf2.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/pbkdf2.svg +[downloads-url]: https://npm-stat.com/charts.html?package=pbkdf2 +[codecov-image]: https://codecov.io/gh/browserify/pbkdf2/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/browserify/pbkdf2/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/browserify/pbkdf2 +[actions-url]: https://github.com/browserify/pbkdf2/actions diff --git a/node_modules/pbkdf2/browser.js b/node_modules/pbkdf2/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..9ac8ba077a8a41a18ec67b0327f0011bea6ede26 --- /dev/null +++ b/node_modules/pbkdf2/browser.js @@ -0,0 +1,4 @@ +'use strict'; + +exports.pbkdf2 = require('./lib/async'); +exports.pbkdf2Sync = require('./lib/sync'); diff --git a/node_modules/pbkdf2/index.js b/node_modules/pbkdf2/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5b6c0bb0cf508be8abcdadc464e28bf12d1e2203 --- /dev/null +++ b/node_modules/pbkdf2/index.js @@ -0,0 +1,43 @@ +'use strict'; + +var nativeImpl = require('crypto'); + +var checkParameters = require('./lib/precondition'); +var defaultEncoding = require('./lib/default-encoding'); +var toBuffer = require('./lib/to-buffer'); + +function nativePBKDF2(password, salt, iterations, keylen, digest, callback) { + checkParameters(iterations, keylen); + password = toBuffer(password, defaultEncoding, 'Password'); + salt = toBuffer(salt, defaultEncoding, 'Salt'); + + if (typeof digest === 'function') { + callback = digest; + digest = 'sha1'; + } + if (typeof callback !== 'function') { + throw new Error('No callback provided to pbkdf2'); + } + + return nativeImpl.pbkdf2(password, salt, iterations, keylen, digest, callback); +} + +function nativePBKDF2Sync(password, salt, iterations, keylen, digest) { + checkParameters(iterations, keylen); + password = toBuffer(password, defaultEncoding, 'Password'); + salt = toBuffer(salt, defaultEncoding, 'Salt'); + digest = digest || 'sha1'; + return nativeImpl.pbkdf2Sync(password, salt, iterations, keylen, digest); +} + +/* istanbul ignore next */ +if (!nativeImpl.pbkdf2Sync || nativeImpl.pbkdf2Sync.toString().indexOf('keylen, digest') === -1) { + /* eslint global-require: 0 */ + exports.pbkdf2Sync = require('./lib/sync'); + exports.pbkdf2 = require('./lib/async'); + +// native +} else { + exports.pbkdf2Sync = nativePBKDF2Sync; + exports.pbkdf2 = nativePBKDF2; +} diff --git a/node_modules/pbkdf2/lib/async.js b/node_modules/pbkdf2/lib/async.js new file mode 100644 index 0000000000000000000000000000000000000000..21aee16a4ec35f2ab1badfdb98c1ea2acd956616 --- /dev/null +++ b/node_modules/pbkdf2/lib/async.js @@ -0,0 +1,122 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer; + +var checkParameters = require('./precondition'); +var defaultEncoding = require('./default-encoding'); +var sync = require('./sync'); +var toBuffer = require('./to-buffer'); + +var ZERO_BUF; +var subtle = global.crypto && global.crypto.subtle; +var toBrowser = { + sha: 'SHA-1', + 'sha-1': 'SHA-1', + sha1: 'SHA-1', + sha256: 'SHA-256', + 'sha-256': 'SHA-256', + sha384: 'SHA-384', + 'sha-384': 'SHA-384', + 'sha-512': 'SHA-512', + sha512: 'SHA-512' +}; +var checks = []; +var nextTick; +function getNextTick() { + if (nextTick) { + return nextTick; + } + if (global.process && global.process.nextTick) { + nextTick = global.process.nextTick; + } else if (global.queueMicrotask) { + nextTick = global.queueMicrotask; + } else if (global.setImmediate) { + nextTick = global.setImmediate; + } else { + nextTick = global.setTimeout; + } + return nextTick; +} +function browserPbkdf2(password, salt, iterations, length, algo) { + return subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveBits']).then(function (key) { + return subtle.deriveBits({ + name: 'PBKDF2', + salt: salt, + iterations: iterations, + hash: { + name: algo + } + }, key, length << 3); + }).then(function (res) { + return Buffer.from(res); + }); +} +function checkNative(algo) { + if (global.process && !global.process.browser) { + return Promise.resolve(false); + } + if (!subtle || !subtle.importKey || !subtle.deriveBits) { + return Promise.resolve(false); + } + if (checks[algo] !== undefined) { + return checks[algo]; + } + ZERO_BUF = ZERO_BUF || Buffer.alloc(8); + var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo) + .then( + function () { return true; }, + function () { return false; } + ); + checks[algo] = prom; + return prom; +} + +function resolvePromise(promise, callback) { + promise.then(function (out) { + getNextTick()(function () { + callback(null, out); + }); + }, function (e) { + getNextTick()(function () { + callback(e); + }); + }); +} +module.exports = function (password, salt, iterations, keylen, digest, callback) { + if (typeof digest === 'function') { + callback = digest; + digest = undefined; + } + + checkParameters(iterations, keylen); + password = toBuffer(password, defaultEncoding, 'Password'); + salt = toBuffer(salt, defaultEncoding, 'Salt'); + if (typeof callback !== 'function') { + throw new Error('No callback provided to pbkdf2'); + } + + digest = digest || 'sha1'; + var algo = toBrowser[digest.toLowerCase()]; + + if (!algo || typeof global.Promise !== 'function') { + getNextTick()(function () { + var out; + try { + out = sync(password, salt, iterations, keylen, digest); + } catch (e) { + callback(e); + return; + } + callback(null, out); + }); + return; + } + + resolvePromise(checkNative(algo).then(function (resp) { + if (resp) { + return browserPbkdf2(password, salt, iterations, keylen, algo); + } + + return sync(password, salt, iterations, keylen, digest); + }), callback); +}; diff --git a/node_modules/pbkdf2/lib/default-encoding.js b/node_modules/pbkdf2/lib/default-encoding.js new file mode 100644 index 0000000000000000000000000000000000000000..beb4efaedb41f26465a4df25580273d4a9bd420f --- /dev/null +++ b/node_modules/pbkdf2/lib/default-encoding.js @@ -0,0 +1,14 @@ +'use strict'; + +var defaultEncoding; +/* istanbul ignore next */ +if (global.process && global.process.browser) { + defaultEncoding = 'utf-8'; +} else if (global.process && global.process.version) { + var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10); + + defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'; +} else { + defaultEncoding = 'utf-8'; +} +module.exports = defaultEncoding; diff --git a/node_modules/pbkdf2/lib/precondition.js b/node_modules/pbkdf2/lib/precondition.js new file mode 100644 index 0000000000000000000000000000000000000000..1274dbb8fd935ba3fe6aae05cc92025e5af00c71 --- /dev/null +++ b/node_modules/pbkdf2/lib/precondition.js @@ -0,0 +1,22 @@ +'use strict'; + +var $isFinite = isFinite; +var MAX_ALLOC = Math.pow(2, 30) - 1; // default in iojs + +module.exports = function (iterations, keylen) { + if (typeof iterations !== 'number') { + throw new TypeError('Iterations not a number'); + } + + if (iterations < 0 || !$isFinite(iterations)) { + throw new TypeError('Bad iterations'); + } + + if (typeof keylen !== 'number') { + throw new TypeError('Key length not a number'); + } + + if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ + throw new TypeError('Bad key length'); + } +}; diff --git a/node_modules/pbkdf2/lib/sync-browser.js b/node_modules/pbkdf2/lib/sync-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..5dbdb6e1e372021b920959f06ed380ed1ebcca3d --- /dev/null +++ b/node_modules/pbkdf2/lib/sync-browser.js @@ -0,0 +1,131 @@ +'use strict'; + +var md5 = require('create-hash/md5'); +var RIPEMD160 = require('ripemd160'); +var sha = require('sha.js'); +var Buffer = require('safe-buffer').Buffer; + +var checkParameters = require('./precondition'); +var defaultEncoding = require('./default-encoding'); +var toBuffer = require('./to-buffer'); + +var ZEROS = Buffer.alloc(128); +var sizes = { + __proto__: null, + md5: 16, + sha1: 20, + sha224: 28, + sha256: 32, + sha384: 48, + sha512: 64, + 'sha512-256': 32, + ripemd160: 20, + rmd160: 20 +}; + +var mapping = { + __proto__: null, + 'sha-1': 'sha1', + 'sha-224': 'sha224', + 'sha-256': 'sha256', + 'sha-384': 'sha384', + 'sha-512': 'sha512', + 'ripemd-160': 'ripemd160' +}; + +function rmd160Func(data) { + return new RIPEMD160().update(data).digest(); +} + +function getDigest(alg) { + function shaFunc(data) { + return sha(alg).update(data).digest(); + } + + if (alg === 'rmd160' || alg === 'ripemd160') { + return rmd160Func; + } + if (alg === 'md5') { + return md5; + } + return shaFunc; +} + +function Hmac(alg, key, saltLen) { + var hash = getDigest(alg); + var blocksize = alg === 'sha512' || alg === 'sha384' ? 128 : 64; + + if (key.length > blocksize) { + key = hash(key); + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize); + } + + var ipad = Buffer.allocUnsafe(blocksize + sizes[alg]); + var opad = Buffer.allocUnsafe(blocksize + sizes[alg]); + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36; + opad[i] = key[i] ^ 0x5C; + } + + var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4); + ipad.copy(ipad1, 0, 0, blocksize); + this.ipad1 = ipad1; + this.ipad2 = ipad; + this.opad = opad; + this.alg = alg; + this.blocksize = blocksize; + this.hash = hash; + this.size = sizes[alg]; +} + +Hmac.prototype.run = function (data, ipad) { + data.copy(ipad, this.blocksize); + var h = this.hash(ipad); + h.copy(this.opad, this.blocksize); + return this.hash(this.opad); +}; + +function pbkdf2(password, salt, iterations, keylen, digest) { + checkParameters(iterations, keylen); + password = toBuffer(password, defaultEncoding, 'Password'); + salt = toBuffer(salt, defaultEncoding, 'Salt'); + + var lowerDigest = (digest || 'sha1').toLowerCase(); + var mappedDigest = mapping[lowerDigest] || lowerDigest; + var size = sizes[mappedDigest]; + if (typeof size !== 'number' || !size) { + throw new TypeError('Digest algorithm not supported: ' + digest); + } + + var hmac = new Hmac(mappedDigest, password, salt.length); + + var DK = Buffer.allocUnsafe(keylen); + var block1 = Buffer.allocUnsafe(salt.length + 4); + salt.copy(block1, 0, 0, salt.length); + + var destPos = 0; + var hLen = size; + var l = Math.ceil(keylen / hLen); + + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length); + + var T = hmac.run(block1, hmac.ipad1); + var U = T; + + for (var j = 1; j < iterations; j++) { + U = hmac.run(U, hmac.ipad2); + for (var k = 0; k < hLen; k++) { + T[k] ^= U[k]; + } + } + + T.copy(DK, destPos); + destPos += hLen; + } + + return DK; +} + +module.exports = pbkdf2; diff --git a/node_modules/pbkdf2/lib/sync.js b/node_modules/pbkdf2/lib/sync.js new file mode 100644 index 0000000000000000000000000000000000000000..a0c322a2f0c9c16e88bc24cb0debc15db19d0a47 --- /dev/null +++ b/node_modules/pbkdf2/lib/sync.js @@ -0,0 +1,73 @@ +'use strict'; + +var sizes = { + __proto__: null, + md5: 16, + sha1: 20, + sha224: 28, + sha256: 32, + sha384: 48, + sha512: 64, + 'sha512-256': 32, + rmd160: 20, + ripemd160: 20 +}; + +var mapping = { + __proto__: null, + 'sha-1': 'sha1', + 'sha-224': 'sha224', + 'sha-256': 'sha256', + 'sha-384': 'sha384', + 'sha-512': 'sha512', + 'ripemd-160': 'ripemd160' +}; + +var createHmac = require('create-hmac'); +var Buffer = require('safe-buffer').Buffer; + +var checkParameters = require('./precondition'); +var defaultEncoding = require('./default-encoding'); +var toBuffer = require('./to-buffer'); + +function pbkdf2(password, salt, iterations, keylen, digest) { + checkParameters(iterations, keylen); + password = toBuffer(password, defaultEncoding, 'Password'); + salt = toBuffer(salt, defaultEncoding, 'Salt'); + + var lowerDigest = (digest || 'sha1').toLowerCase(); + var mappedDigest = mapping[lowerDigest] || lowerDigest; + var size = sizes[mappedDigest]; + if (typeof size !== 'number' || !size) { + throw new TypeError('Digest algorithm not supported: ' + digest); + } + + var DK = Buffer.allocUnsafe(keylen); + var block1 = Buffer.allocUnsafe(salt.length + 4); + salt.copy(block1, 0, 0, salt.length); + + var destPos = 0; + var hLen = size; + var l = Math.ceil(keylen / hLen); + + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length); + + var T = createHmac(mappedDigest, password).update(block1).digest(); + var U = T; + + for (var j = 1; j < iterations; j++) { + U = createHmac(mappedDigest, password).update(U).digest(); + for (var k = 0; k < hLen; k++) { + T[k] ^= U[k]; + } + } + + T.copy(DK, destPos); + destPos += hLen; + } + + return DK; +} + +module.exports = pbkdf2; diff --git a/node_modules/pbkdf2/lib/to-buffer.js b/node_modules/pbkdf2/lib/to-buffer.js new file mode 100644 index 0000000000000000000000000000000000000000..5f83afe11b77ca68b3606aefea96c501ca1ce470 --- /dev/null +++ b/node_modules/pbkdf2/lib/to-buffer.js @@ -0,0 +1,20 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer; +var toBuffer = require('to-buffer'); + +var useUint8Array = typeof Uint8Array !== 'undefined'; +var useArrayBuffer = useUint8Array && typeof ArrayBuffer !== 'undefined'; +var isView = useArrayBuffer && ArrayBuffer.isView; + +module.exports = function (thing, encoding, name) { + if ( + typeof thing === 'string' + || Buffer.isBuffer(thing) + || (useUint8Array && thing instanceof Uint8Array) + || (isView && isView(thing)) + ) { + return toBuffer(thing, encoding); + } + throw new TypeError(name + ' must be a string, a Buffer, a Uint8Array, or a DataView'); +}; diff --git a/node_modules/pbkdf2/package.json b/node_modules/pbkdf2/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a24e1a06ef7b68899f9d1366b42b592873638d57 --- /dev/null +++ b/node_modules/pbkdf2/package.json @@ -0,0 +1,77 @@ +{ + "name": "pbkdf2", + "version": "3.1.5", + "description": "This library provides the functionality of PBKDF2 with the ability to use any supported hashing algorithm returned from crypto.getHashes()", + "keywords": [ + "pbkdf2", + "kdf", + "salt", + "hash" + ], + "homepage": "https://github.com/browserify/pbkdf2", + "bugs": { + "url": "https://github.com/browserify/pbkdf2/issues" + }, + "license": "MIT", + "author": "Daniel Cousens", + "browser": { + "./index.js": "./browser.js", + "./lib/sync.js": "./lib/sync-browser.js" + }, + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/browserify/pbkdf2.git" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape test/index.js", + "test": "npm run tests-only && npm run bundle-test", + "posttest": "npx npm@\">= 10.2\" audit --production", + "bundle-test": "browserify test/index.js > test/bundle.js", + "bench": "node bench/", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.2.0", + "auto-changelog": "^2.5.0", + "benchmark": "^2.1.4", + "browserify": "^17.0.1", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object.assign": "^4.1.7", + "semver": "^6.3.1", + "tape": "^5.9.0" + }, + "dependencies": { + "create-hash": "^1.2.0", + "create-hmac": "^1.1.7", + "ripemd160": "^2.0.3", + "safe-buffer": "^5.2.1", + "sha.js": "^2.4.12", + "to-buffer": "^1.2.1" + }, + "engines": { + "node": ">= 0.10" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "bench", + "test" + ] + } +} diff --git a/node_modules/performance-now/.npmignore b/node_modules/performance-now/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..496ee2ca6a2f08396a4076fe43dedf3dc0da8b6d --- /dev/null +++ b/node_modules/performance-now/.npmignore @@ -0,0 +1 @@ +.DS_Store \ No newline at end of file diff --git a/node_modules/performance-now/.tm_properties b/node_modules/performance-now/.tm_properties new file mode 100644 index 0000000000000000000000000000000000000000..4b8eb3f610c314ba7f7c605047b70692d648ffce --- /dev/null +++ b/node_modules/performance-now/.tm_properties @@ -0,0 +1,7 @@ +excludeDirectories = "{.git,node_modules}" +excludeInFolderSearch = "{excludeDirectories,lib}" + +includeFiles = "{.gitignore,.npmignore,.travis.yml}" + +[ attr.untitled ] +fileType = 'source.coffee' \ No newline at end of file diff --git a/node_modules/performance-now/.travis.yml b/node_modules/performance-now/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..1543c1990eb9ed35b8f9c8cb3fc3d5026616179e --- /dev/null +++ b/node_modules/performance-now/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "node" + - "6" + - "4" + - "0.12" diff --git a/node_modules/performance-now/README.md b/node_modules/performance-now/README.md new file mode 100644 index 0000000000000000000000000000000000000000..28080f856aa21296b6ac8749704fec106bf247f8 --- /dev/null +++ b/node_modules/performance-now/README.md @@ -0,0 +1,30 @@ +# performance-now [![Build Status](https://travis-ci.org/braveg1rl/performance-now.png?branch=master)](https://travis-ci.org/braveg1rl/performance-now) [![Dependency Status](https://david-dm.org/braveg1rl/performance-now.png)](https://david-dm.org/braveg1rl/performance-now) + +Implements a function similar to `performance.now` (based on `process.hrtime`). + +Modern browsers have a `window.performance` object with - among others - a `now` method which gives time in milliseconds, but with sub-millisecond precision. This module offers the same function based on the Node.js native `process.hrtime` function. + +Using `process.hrtime` means that the reported time will be monotonically increasing, and not subject to clock-drift. + +According to the [High Resolution Time specification](http://www.w3.org/TR/hr-time/), the number of milliseconds reported by `performance.now` should be relative to the value of `performance.timing.navigationStart`. + +In the current version of the module (2.0) the reported time is relative to the time the current Node process has started (inferred from `process.uptime()`). + +Version 1.0 reported a different time. The reported time was relative to the time the module was loaded (i.e. the time it was first `require`d). If you need this functionality, version 1.0 is still available on NPM. + +## Example usage + +```javascript +var now = require("performance-now") +var start = now() +var end = now() +console.log(start.toFixed(3)) // the number of milliseconds the current node process is running +console.log((start-end).toFixed(3)) // ~ 0.002 on my system +``` + +Running the now function two times right after each other yields a time difference of a few microseconds. Given this overhead, I think it's best to assume that the precision of intervals computed with this method is not higher than 10 microseconds, if you don't know the exact overhead on your own system. + +## License + +performance-now is released under the [MIT License](http://opensource.org/licenses/MIT). +Copyright (c) 2017 Braveg1rl diff --git a/node_modules/performance-now/lib/performance-now.js b/node_modules/performance-now/lib/performance-now.js new file mode 100644 index 0000000000000000000000000000000000000000..37f569da1e066b6547d72c778564d6f9073faeb5 --- /dev/null +++ b/node_modules/performance-now/lib/performance-now.js @@ -0,0 +1,36 @@ +// Generated by CoffeeScript 1.12.2 +(function() { + var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime; + + if ((typeof performance !== "undefined" && performance !== null) && performance.now) { + module.exports = function() { + return performance.now(); + }; + } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) { + module.exports = function() { + return (getNanoSeconds() - nodeLoadTime) / 1e6; + }; + hrtime = process.hrtime; + getNanoSeconds = function() { + var hr; + hr = hrtime(); + return hr[0] * 1e9 + hr[1]; + }; + moduleLoadTime = getNanoSeconds(); + upTime = process.uptime() * 1e9; + nodeLoadTime = moduleLoadTime - upTime; + } else if (Date.now) { + module.exports = function() { + return Date.now() - loadTime; + }; + loadTime = Date.now(); + } else { + module.exports = function() { + return new Date().getTime() - loadTime; + }; + loadTime = new Date().getTime(); + } + +}).call(this); + +//# sourceMappingURL=performance-now.js.map diff --git a/node_modules/performance-now/lib/performance-now.js.map b/node_modules/performance-now/lib/performance-now.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bef83626d876dd4f344dd4467a678dbfaa4d0a14 --- /dev/null +++ b/node_modules/performance-now/lib/performance-now.js.map @@ -0,0 +1,10 @@ +{ + "version": 3, + "file": "performance-now.js", + "sourceRoot": "..", + "sources": [ + "src/performance-now.coffee" + ], + "names": [], + "mappings": ";AAAA;AAAA,MAAA;;EAAA,IAAG,4DAAA,IAAiB,WAAW,CAAC,GAAhC;IACE,MAAM,CAAC,OAAP,GAAiB,SAAA;aAAG,WAAW,CAAC,GAAZ,CAAA;IAAH,EADnB;GAAA,MAEK,IAAG,oDAAA,IAAa,OAAO,CAAC,MAAxB;IACH,MAAM,CAAC,OAAP,GAAiB,SAAA;aAAG,CAAC,cAAA,CAAA,CAAA,GAAmB,YAApB,CAAA,GAAoC;IAAvC;IACjB,MAAA,GAAS,OAAO,CAAC;IACjB,cAAA,GAAiB,SAAA;AACf,UAAA;MAAA,EAAA,GAAK,MAAA,CAAA;aACL,EAAG,CAAA,CAAA,CAAH,GAAQ,GAAR,GAAc,EAAG,CAAA,CAAA;IAFF;IAGjB,cAAA,GAAiB,cAAA,CAAA;IACjB,MAAA,GAAS,OAAO,CAAC,MAAR,CAAA,CAAA,GAAmB;IAC5B,YAAA,GAAe,cAAA,GAAiB,OAR7B;GAAA,MASA,IAAG,IAAI,CAAC,GAAR;IACH,MAAM,CAAC,OAAP,GAAiB,SAAA;aAAG,IAAI,CAAC,GAAL,CAAA,CAAA,GAAa;IAAhB;IACjB,QAAA,GAAW,IAAI,CAAC,GAAL,CAAA,EAFR;GAAA,MAAA;IAIH,MAAM,CAAC,OAAP,GAAiB,SAAA;aAAO,IAAA,IAAA,CAAA,CAAM,CAAC,OAAP,CAAA,CAAJ,GAAuB;IAA1B;IACjB,QAAA,GAAe,IAAA,IAAA,CAAA,CAAM,CAAC,OAAP,CAAA,EALZ;;AAXL" +} \ No newline at end of file diff --git a/node_modules/performance-now/license.txt b/node_modules/performance-now/license.txt new file mode 100644 index 0000000000000000000000000000000000000000..0bf51b460fc2e7f380ff5826c968e26ed749ffd2 --- /dev/null +++ b/node_modules/performance-now/license.txt @@ -0,0 +1,7 @@ +Copyright (c) 2013 Braveg1rl + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/performance-now/package.json b/node_modules/performance-now/package.json new file mode 100644 index 0000000000000000000000000000000000000000..962bfc85ff8fe11cedee32dfbbc684a2d10f68c9 --- /dev/null +++ b/node_modules/performance-now/package.json @@ -0,0 +1,35 @@ +{ + "name": "performance-now", + "description": "Implements performance.now (based on process.hrtime).", + "keywords": [], + "version": "2.1.0", + "author": "Braveg1rl ", + "license": "MIT", + "homepage": "https://github.com/braveg1rl/performance-now", + "bugs": "https://github.com/braveg1rl/performance-now/issues", + "repository": { + "type": "git", + "url": "git://github.com/braveg1rl/performance-now.git" + }, + "private": false, + "dependencies": {}, + "devDependencies": { + "bluebird": "^3.4.7", + "call-delayed": "^1.0.0", + "chai": "^3.5.0", + "chai-increasing": "^1.2.0", + "coffee-script": "~1.12.2", + "mocha": "~3.2.0", + "pre-commit": "^1.2.2" + }, + "optionalDependencies": {}, + "main": "lib/performance-now.js", + "scripts": { + "build": "mkdir -p lib && rm -rf lib/* && node_modules/.bin/coffee --compile -m --output lib/ src/", + "prepublish": "npm test", + "pretest": "npm run build", + "test": "node_modules/.bin/mocha", + "watch": "node_modules/.bin/coffee --watch --compile --output lib/ src/" + }, + "typings": "src/index.d.ts" +} diff --git a/node_modules/performance-now/src/index.d.ts b/node_modules/performance-now/src/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..68dca8eddc83ca54a43a8c9779005825381977f7 --- /dev/null +++ b/node_modules/performance-now/src/index.d.ts @@ -0,0 +1,8 @@ +// This file describes the package to typescript. + +/** + * Returns the number of milliseconds since the page was loaded (if browser) + * or the node process was started. + */ +declare function now(): number; +export = now; diff --git a/node_modules/performance-now/src/performance-now.coffee b/node_modules/performance-now/src/performance-now.coffee new file mode 100644 index 0000000000000000000000000000000000000000..a8e075a40feda90dba21f70a8bfed1984d361773 --- /dev/null +++ b/node_modules/performance-now/src/performance-now.coffee @@ -0,0 +1,17 @@ +if performance? and performance.now + module.exports = -> performance.now() +else if process? and process.hrtime + module.exports = -> (getNanoSeconds() - nodeLoadTime) / 1e6 + hrtime = process.hrtime + getNanoSeconds = -> + hr = hrtime() + hr[0] * 1e9 + hr[1] + moduleLoadTime = getNanoSeconds() + upTime = process.uptime() * 1e9 + nodeLoadTime = moduleLoadTime - upTime +else if Date.now + module.exports = -> Date.now() - loadTime + loadTime = Date.now() +else + module.exports = -> new Date().getTime() - loadTime + loadTime = new Date().getTime() diff --git a/node_modules/performance-now/test/mocha.opts b/node_modules/performance-now/test/mocha.opts new file mode 100644 index 0000000000000000000000000000000000000000..55d8492707f336c48ef2b40e62a6953a1e141df2 --- /dev/null +++ b/node_modules/performance-now/test/mocha.opts @@ -0,0 +1,3 @@ +--require coffee-script/register +--compilers coffee:coffee-script/register +--reporter spec \ No newline at end of file diff --git a/node_modules/performance-now/test/performance-now.coffee b/node_modules/performance-now/test/performance-now.coffee new file mode 100644 index 0000000000000000000000000000000000000000..c99e95cd2cb860d32f6d8ec7f96e2b476bef68fd --- /dev/null +++ b/node_modules/performance-now/test/performance-now.coffee @@ -0,0 +1,43 @@ +chai = require "chai" +chai.use(require "chai-increasing") +{assert,expect} = chai +Bluebird = require "bluebird" + +now = require "../" + +getUptime = -> process.uptime() * 1e3 + +describe "now", -> + it "reported time differs at most 1ms from a freshly reported uptime", -> + assert.isAtMost Math.abs(now()-getUptime()), 1 + + it "two subsequent calls return an increasing number", -> + assert.isBelow now(), now() + + it "has less than 10 microseconds overhead", -> + assert.isBelow Math.abs(now() - now()), 0.010 + + it "can be called 1 million times in under 1 second (averaging under 1 microsecond per call)", -> + @timeout 1000 + now() for [0...1e6] + undefined + + it "for 10,000 numbers, number n is never bigger than number n-1", -> + stamps = (now() for [1...10000]) + expect(stamps).to.be.increasing + + it "shows that at least 0.2 ms has passed after a timeout of 1 ms", -> + earlier = now() + Bluebird.resolve().delay(1).then -> assert.isAbove (now()-earlier), 0.2 + + it "shows that at most 3 ms has passed after a timeout of 1 ms", -> + earlier = now() + Bluebird.resolve().delay(1).then -> assert.isBelow (now()-earlier), 3 + + it "shows that at least 190ms ms has passed after a timeout of 200ms", -> + earlier = now() + Bluebird.resolve().delay(200).then -> assert.isAbove (now()-earlier), 190 + + it "shows that at most 220 ms has passed after a timeout of 200ms", -> + earlier = now() + Bluebird.resolve().delay(200).then -> assert.isBelow (now()-earlier), 220 diff --git a/node_modules/performance-now/test/scripts.coffee b/node_modules/performance-now/test/scripts.coffee new file mode 100644 index 0000000000000000000000000000000000000000..16312f185c844560eb8ec02ebdfef95b3a81b9f9 --- /dev/null +++ b/node_modules/performance-now/test/scripts.coffee @@ -0,0 +1,27 @@ +Bluebird = require "bluebird" +exec = require("child_process").execSync +{assert} = require "chai" + +describe "scripts/initital-value.coffee (module.uptime(), expressed in milliseconds)", -> + result = exec("./test/scripts/initial-value.coffee").toString().trim() + it "printed #{result}", -> + it "printed a value above 100", -> assert.isAbove result, 100 + it "printed a value below 350", -> assert.isBelow result, 350 + +describe "scripts/delayed-require.coffee (sum of uptime and 250 ms delay`)", -> + result = exec("./test/scripts/delayed-require.coffee").toString().trim() + it "printed #{result}", -> + it "printed a value above 350", -> assert.isAbove result, 350 + it "printed a value below 600", -> assert.isBelow result, 600 + +describe "scripts/delayed-call.coffee (sum of uptime and 250 ms delay`)", -> + result = exec("./test/scripts/delayed-call.coffee").toString().trim() + it "printed #{result}", -> + it "printed a value above 350", -> assert.isAbove result, 350 + it "printed a value below 600", -> assert.isBelow result, 600 + +describe "scripts/difference.coffee", -> + result = exec("./test/scripts/difference.coffee").toString().trim() + it "printed #{result}", -> + it "printed a value above 0.005", -> assert.isAbove result, 0.005 + it "printed a value below 0.07", -> assert.isBelow result, 0.07 diff --git a/node_modules/performance-now/test/scripts/delayed-call.coffee b/node_modules/performance-now/test/scripts/delayed-call.coffee new file mode 100644 index 0000000000000000000000000000000000000000..0c3bab5949b74bdd7a70adc803d3d718a8281080 --- /dev/null +++ b/node_modules/performance-now/test/scripts/delayed-call.coffee @@ -0,0 +1,11 @@ +#!/usr/bin/env ./node_modules/.bin/coffee + +### +Expected output is a number above 350 and below 600. +The time reported is relative to the time the node.js process was started +this is approximately at `(Date.now() process.uptime() * 1000)` +### + +delay = require "call-delayed" +now = require "../../lib/performance-now" +delay 250, -> console.log now().toFixed 3 diff --git a/node_modules/performance-now/test/scripts/delayed-require.coffee b/node_modules/performance-now/test/scripts/delayed-require.coffee new file mode 100644 index 0000000000000000000000000000000000000000..3ddee952f2c30c87c1d6360d8d168ab8c7b6d183 --- /dev/null +++ b/node_modules/performance-now/test/scripts/delayed-require.coffee @@ -0,0 +1,12 @@ +#!/usr/bin/env ./node_modules/.bin/coffee + +### +Expected output is a number above 350 and below 600. +The time reported is relative to the time the node.js process was started +this is approximately at `(Date.now() process.uptime() * 1000)` +### + +delay = require "call-delayed" +delay 250, -> + now = require "../../lib/performance-now" + console.log now().toFixed 3 diff --git a/node_modules/performance-now/test/scripts/difference.coffee b/node_modules/performance-now/test/scripts/difference.coffee new file mode 100644 index 0000000000000000000000000000000000000000..0b5edf6c6b2a026da944c19db7524f4688b28c7a --- /dev/null +++ b/node_modules/performance-now/test/scripts/difference.coffee @@ -0,0 +1,6 @@ +#!/usr/bin/env ./node_modules/.bin/coffee + +# Expected output is above 0.005 and below 0.07. + +now = require('../../lib/performance-now') +console.log -(now() - now()).toFixed 3 diff --git a/node_modules/performance-now/test/scripts/initial-value.coffee b/node_modules/performance-now/test/scripts/initial-value.coffee new file mode 100644 index 0000000000000000000000000000000000000000..19ef4e0f3e732fb9ff8c1b46a4e1616d3fb34497 --- /dev/null +++ b/node_modules/performance-now/test/scripts/initial-value.coffee @@ -0,0 +1,10 @@ +#!/usr/bin/env ./node_modules/.bin/coffee + +### +Expected output is a number above 100 and below 350. +The time reported is relative to the time the node.js process was started +this is approximately at `(Date.now() process.uptime() * 1000)` +### + +now = require '../../lib/performance-now' +console.log now().toFixed 3 diff --git a/node_modules/pick-by-alias/.eslintrc.json b/node_modules/pick-by-alias/.eslintrc.json new file mode 100644 index 0000000000000000000000000000000000000000..c50c250446ee6d06a87a590ecbf3905696b0871d --- /dev/null +++ b/node_modules/pick-by-alias/.eslintrc.json @@ -0,0 +1,43 @@ +{ + "env": { + "browser": true, + "node": true, + "commonjs": true, + "es6": true + }, + "extends": "eslint:recommended", + "rules": { + "strict": 2, + "indent": 0, + "linebreak-style": 0, + "quotes": 0, + "semi": 0, + "no-cond-assign": 1, + "no-constant-condition": 1, + "no-duplicate-case": 1, + "no-empty": 1, + "no-ex-assign": 1, + "no-extra-boolean-cast": 1, + "no-extra-semi": 1, + "no-fallthrough": 1, + "no-func-assign": 1, + "no-global-assign": 1, + "no-implicit-globals": 2, + "no-inner-declarations": ["error", "functions"], + "no-irregular-whitespace": 2, + "no-loop-func": 1, + "no-multi-str": 1, + "no-mixed-spaces-and-tabs": 1, + "no-proto": 1, + "no-sequences": 1, + "no-throw-literal": 1, + "no-unmodified-loop-condition": 1, + "no-useless-call": 1, + "no-void": 1, + "no-with": 2, + "wrap-iife": 1, + "no-redeclare": 1, + "no-unused-vars": ["error", { "vars": "all", "args": "none" }], + "no-sparse-arrays": 1 + } +} diff --git a/node_modules/pick-by-alias/.npmignore b/node_modules/pick-by-alias/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..08b25532d6c20a465f83b50183a64307f0266fa5 --- /dev/null +++ b/node_modules/pick-by-alias/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/pick-by-alias/index.js b/node_modules/pick-by-alias/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5da4b13d1602d0840f475ac15d507329eff03cf7 --- /dev/null +++ b/node_modules/pick-by-alias/index.js @@ -0,0 +1,77 @@ +'use strict' + + +module.exports = function pick (src, props, keepRest) { + var result = {}, prop, i + + if (typeof props === 'string') props = toList(props) + if (Array.isArray(props)) { + var res = {} + for (i = 0; i < props.length; i++) { + res[props[i]] = true + } + props = res + } + + // convert strings to lists + for (prop in props) { + props[prop] = toList(props[prop]) + } + + // keep-rest strategy requires unmatched props to be preserved + var occupied = {} + + for (prop in props) { + var aliases = props[prop] + + if (Array.isArray(aliases)) { + for (i = 0; i < aliases.length; i++) { + var alias = aliases[i] + + if (keepRest) { + occupied[alias] = true + } + + if (alias in src) { + result[prop] = src[alias] + + if (keepRest) { + for (var j = i; j < aliases.length; j++) { + occupied[aliases[j]] = true + } + } + + break + } + } + } + else if (prop in src) { + if (props[prop]) { + result[prop] = src[prop] + } + + if (keepRest) { + occupied[prop] = true + } + } + } + + if (keepRest) { + for (prop in src) { + if (occupied[prop]) continue + result[prop] = src[prop] + } + } + + return result +} + +var CACHE = {} + +function toList(arg) { + if (CACHE[arg]) return CACHE[arg] + if (typeof arg === 'string') { + arg = CACHE[arg] = arg.split(/\s*,\s*|\s+/) + } + return arg +} diff --git a/node_modules/pick-by-alias/package.json b/node_modules/pick-by-alias/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5f00af87af8962271dffef4f03ec98e0d3720b28 --- /dev/null +++ b/node_modules/pick-by-alias/package.json @@ -0,0 +1,26 @@ +{ + "name": "pick-by-alias", + "version": "1.2.0", + "description": "Pick properties by aliases", + "main": "index.js", + "scripts": { + "test": "node test" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/dfcreative/pick-by-alias.git" + }, + "keywords": [ + "pick", + "object" + ], + "author": "Dima Yv ", + "license": "MIT", + "bugs": { + "url": "https://github.com/dfcreative/pick-by-alias/issues" + }, + "homepage": "https://github.com/dfcreative/pick-by-alias#readme", + "devDependencies": { + "tape": "^4.8.0" + } +} diff --git a/node_modules/pick-by-alias/readme.md b/node_modules/pick-by-alias/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..e8c7170868d830a8facc4bd8e099d196c70107d6 --- /dev/null +++ b/node_modules/pick-by-alias/readme.md @@ -0,0 +1,46 @@ +# pick-by-alias [![unstable](https://img.shields.io/badge/stability-unstable-green.svg)](http://github.com/badges/stability-badges) + +Pick object properties by synonyms. Useful to avoid remembering exact option names from user perspective. + +[![npm install pick-by-alias](https://nodei.co/npm/pick-by-alias.png?mini=true)](https://npmjs.org/package/pick-by-alias/) + +```js +let pick = require('pick-by-alias') + +let result = pick({ + positions: [...], + color: 'rgba(0, 100, 200, .75)', + viewBox: null, + extra: 123 +}, { + positions: 'positions points data coordinates', + color: 'colors color stroke', + viewport: 'viewport viewBox' +}) +``` + +### `pick(object, properties, keepRest=false)` + +Return an object with properties picked by the list or dict with aliases. Aliases are matched in priority order, ie. first matching name is picked. Each alias can be an array or a comma/space-separated string. + +```js +// pick by dict +let {a, b} = pick(src, {a: ['a', 'b', 'c'], b: 'd e f'}) + +// pick by list +let {c, d, e} = pick(src, ['c', 'd', 'e']) + +// pick by string +let {f, g} = pick(src, 'f g') +``` + +`keepRest` defines if not listed object properties should be transfered to resulting object or discarded. + +## Related + +* [defined](https://www.npmjs.com/package/defined) − get first non-undefined out of a list of values +* [update-diff](https://github.com/dfcreative/update-diff) − update object state by mapping diff. + +## License + +(c) 2017 Dima Yv. MIT License diff --git a/node_modules/pick-by-alias/test.js b/node_modules/pick-by-alias/test.js new file mode 100644 index 0000000000000000000000000000000000000000..e0aeaaa3d2e2150f370848a0897090ad3635a85f --- /dev/null +++ b/node_modules/pick-by-alias/test.js @@ -0,0 +1,79 @@ +'use strict' + +const t = require('tape') +const pick = require('./') + +t('obj', t => { + let res = pick({ + a: 0, + b: null, + c: undefined, + d: 1, + e: [0, 1] + }, {a: ['x', 'y', 'a'], b: true, c: 'd', d: ['e'], e: 'b a', f: 'd,b'}) + + t.deepEqual(res, { + a: 0, + b: null, + c: 1, + d: [0, 1], + e: null, + f: 1 + }) + + t.end() +}) + +t('array', t => { + t.deepEqual(pick({ + a: 0, + b: null, + c: undefined, + d: 1, + e: [0, 1] + }, ['a', 'b', 'c', 'd']), {a: 0, b: null, c: undefined, d: 1}) + + t.end() +}) + + +t('string', t => { + t.deepEqual(pick({ + a: 0, + b: null, + c: undefined, + d: 1, + e: [0, 1] + }, 'a b c d'), {a: 0, b: null, c: undefined, d: 1}) + + t.end() +}) + +t('avoid picking absent props', t => { + t.deepEqual(pick({a: 1, b: 2}, 'a b c'), {a: 1, b: 2}) + + t.end() +}) + +t('keep rest strategy', t => { + t.deepEqual(pick({a: 1, B: 2, Be: 2.5, c: 3}, { + a: true, + b: 'B Be' + }, true), + { + a: 1, + b: 2, + c: 3 + }) + + t.deepEqual(pick({a: 1, B: 2, Be: 2.5, c: 3}, { + a: true, + b: 'B Be' + }), + { + a: 1, + b: 2 + }) + + t.end() +}) diff --git a/node_modules/picocolors/LICENSE b/node_modules/picocolors/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..46c9b95d4b83c8eba2d9ed406f49930a9fdaf3e3 --- /dev/null +++ b/node_modules/picocolors/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/picocolors/README.md b/node_modules/picocolors/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8e47aa8eea126388d0773e7f86f91471eb5e2150 --- /dev/null +++ b/node_modules/picocolors/README.md @@ -0,0 +1,21 @@ +# picocolors + +The tiniest and the fastest library for terminal output formatting with ANSI colors. + +```javascript +import pc from "picocolors" + +console.log( + pc.green(`How are ${pc.italic(`you`)} doing?`) +) +``` + +- **No dependencies.** +- **14 times** smaller and **2 times** faster than chalk. +- Used by popular tools like PostCSS, SVGO, Stylelint, and Browserslist. +- Node.js v6+ & browsers support. Support for both CJS and ESM projects. +- TypeScript type declarations included. +- [`NO_COLOR`](https://no-color.org/) friendly. + +## Docs +Read **[full docs](https://github.com/alexeyraspopov/picocolors#readme)** on GitHub. diff --git a/node_modules/picocolors/package.json b/node_modules/picocolors/package.json new file mode 100644 index 0000000000000000000000000000000000000000..372d4b642cf553e8234986a22441cce3aea3d11f --- /dev/null +++ b/node_modules/picocolors/package.json @@ -0,0 +1,25 @@ +{ + "name": "picocolors", + "version": "1.1.1", + "main": "./picocolors.js", + "types": "./picocolors.d.ts", + "browser": { + "./picocolors.js": "./picocolors.browser.js" + }, + "sideEffects": false, + "description": "The tiniest and the fastest library for terminal output formatting with ANSI colors", + "files": [ + "picocolors.*", + "types.d.ts" + ], + "keywords": [ + "terminal", + "colors", + "formatting", + "cli", + "console" + ], + "author": "Alexey Raspopov", + "repository": "alexeyraspopov/picocolors", + "license": "ISC" +} diff --git a/node_modules/picocolors/picocolors.browser.js b/node_modules/picocolors/picocolors.browser.js new file mode 100644 index 0000000000000000000000000000000000000000..9dcf637cda1ae2b7ed3281c42463da234ae91398 --- /dev/null +++ b/node_modules/picocolors/picocolors.browser.js @@ -0,0 +1,4 @@ +var x=String; +var create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}}; +module.exports=create(); +module.exports.createColors = create; diff --git a/node_modules/picocolors/picocolors.d.ts b/node_modules/picocolors/picocolors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..94e146a82221e527be835656549ddfb1b41fd0c9 --- /dev/null +++ b/node_modules/picocolors/picocolors.d.ts @@ -0,0 +1,5 @@ +import { Colors } from "./types" + +declare const picocolors: Colors & { createColors: (enabled?: boolean) => Colors } + +export = picocolors diff --git a/node_modules/picocolors/picocolors.js b/node_modules/picocolors/picocolors.js new file mode 100644 index 0000000000000000000000000000000000000000..e32df8548820fdf608b39331be07a8519a1b6c46 --- /dev/null +++ b/node_modules/picocolors/picocolors.js @@ -0,0 +1,75 @@ +let p = process || {}, argv = p.argv || [], env = p.env || {} +let isColorSupported = + !(!!env.NO_COLOR || argv.includes("--no-color")) && + (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI) + +let formatter = (open, close, replace = open) => + input => { + let string = "" + input, index = string.indexOf(close, open.length) + return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close + } + +let replaceClose = (string, close, replace, index) => { + let result = "", cursor = 0 + do { + result += string.substring(cursor, index) + replace + cursor = index + close.length + index = string.indexOf(close, cursor) + } while (~index) + return result + string.substring(cursor) +} + +let createColors = (enabled = isColorSupported) => { + let f = enabled ? formatter : () => String + return { + isColorSupported: enabled, + reset: f("\x1b[0m", "\x1b[0m"), + bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), + dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), + italic: f("\x1b[3m", "\x1b[23m"), + underline: f("\x1b[4m", "\x1b[24m"), + inverse: f("\x1b[7m", "\x1b[27m"), + hidden: f("\x1b[8m", "\x1b[28m"), + strikethrough: f("\x1b[9m", "\x1b[29m"), + + black: f("\x1b[30m", "\x1b[39m"), + red: f("\x1b[31m", "\x1b[39m"), + green: f("\x1b[32m", "\x1b[39m"), + yellow: f("\x1b[33m", "\x1b[39m"), + blue: f("\x1b[34m", "\x1b[39m"), + magenta: f("\x1b[35m", "\x1b[39m"), + cyan: f("\x1b[36m", "\x1b[39m"), + white: f("\x1b[37m", "\x1b[39m"), + gray: f("\x1b[90m", "\x1b[39m"), + + bgBlack: f("\x1b[40m", "\x1b[49m"), + bgRed: f("\x1b[41m", "\x1b[49m"), + bgGreen: f("\x1b[42m", "\x1b[49m"), + bgYellow: f("\x1b[43m", "\x1b[49m"), + bgBlue: f("\x1b[44m", "\x1b[49m"), + bgMagenta: f("\x1b[45m", "\x1b[49m"), + bgCyan: f("\x1b[46m", "\x1b[49m"), + bgWhite: f("\x1b[47m", "\x1b[49m"), + + blackBright: f("\x1b[90m", "\x1b[39m"), + redBright: f("\x1b[91m", "\x1b[39m"), + greenBright: f("\x1b[92m", "\x1b[39m"), + yellowBright: f("\x1b[93m", "\x1b[39m"), + blueBright: f("\x1b[94m", "\x1b[39m"), + magentaBright: f("\x1b[95m", "\x1b[39m"), + cyanBright: f("\x1b[96m", "\x1b[39m"), + whiteBright: f("\x1b[97m", "\x1b[39m"), + + bgBlackBright: f("\x1b[100m", "\x1b[49m"), + bgRedBright: f("\x1b[101m", "\x1b[49m"), + bgGreenBright: f("\x1b[102m", "\x1b[49m"), + bgYellowBright: f("\x1b[103m", "\x1b[49m"), + bgBlueBright: f("\x1b[104m", "\x1b[49m"), + bgMagentaBright: f("\x1b[105m", "\x1b[49m"), + bgCyanBright: f("\x1b[106m", "\x1b[49m"), + bgWhiteBright: f("\x1b[107m", "\x1b[49m"), + } +} + +module.exports = createColors() +module.exports.createColors = createColors diff --git a/node_modules/picocolors/types.d.ts b/node_modules/picocolors/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd1aec46792f4bdb4fd06aeabf1fd93c8b3f11ea --- /dev/null +++ b/node_modules/picocolors/types.d.ts @@ -0,0 +1,51 @@ +export type Formatter = (input: string | number | null | undefined) => string + +export interface Colors { + isColorSupported: boolean + + reset: Formatter + bold: Formatter + dim: Formatter + italic: Formatter + underline: Formatter + inverse: Formatter + hidden: Formatter + strikethrough: Formatter + + black: Formatter + red: Formatter + green: Formatter + yellow: Formatter + blue: Formatter + magenta: Formatter + cyan: Formatter + white: Formatter + gray: Formatter + + bgBlack: Formatter + bgRed: Formatter + bgGreen: Formatter + bgYellow: Formatter + bgBlue: Formatter + bgMagenta: Formatter + bgCyan: Formatter + bgWhite: Formatter + + blackBright: Formatter + redBright: Formatter + greenBright: Formatter + yellowBright: Formatter + blueBright: Formatter + magentaBright: Formatter + cyanBright: Formatter + whiteBright: Formatter + + bgBlackBright: Formatter + bgRedBright: Formatter + bgGreenBright: Formatter + bgYellowBright: Formatter + bgBlueBright: Formatter + bgMagentaBright: Formatter + bgCyanBright: Formatter + bgWhiteBright: Formatter +} diff --git a/node_modules/picomatch/LICENSE b/node_modules/picomatch/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3608dca25e30b572b6ad6935c8c7918bf70e3d2f --- /dev/null +++ b/node_modules/picomatch/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/picomatch/README.md b/node_modules/picomatch/README.md new file mode 100644 index 0000000000000000000000000000000000000000..07644967ac3677dd4f4b19cece1d654aebf8c6aa --- /dev/null +++ b/node_modules/picomatch/README.md @@ -0,0 +1,738 @@ +

Picomatch

+ +

+ +version + + +test status + + +coverage status + + +downloads + +

+ +
+
+ +

+Blazing fast and accurate glob matcher written in JavaScript.
+No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions. +

+ +
+
+ +## Why picomatch? + +* **Lightweight** - No dependencies +* **Minimal** - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function. +* **Fast** - Loads in about 2ms (that's several times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps) +* **Performant** - Use the returned matcher function to speed up repeat matching (like when watching files) +* **Accurate matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories, [advanced globbing](#advanced-globbing) with extglobs, braces, and POSIX brackets, and support for escaping special characters with `\` or quotes. +* **Well tested** - Thousands of unit tests + +See the [library comparison](#library-comparisons) to other libraries. + +
+
+ +## Table of Contents + +
Click to expand + +- [Install](#install) +- [Usage](#usage) +- [API](#api) + * [picomatch](#picomatch) + * [.test](#test) + * [.matchBase](#matchbase) + * [.isMatch](#ismatch) + * [.parse](#parse) + * [.scan](#scan) + * [.compileRe](#compilere) + * [.makeRe](#makere) + * [.toRegex](#toregex) +- [Options](#options) + * [Picomatch options](#picomatch-options) + * [Scan Options](#scan-options) + * [Options Examples](#options-examples) +- [Globbing features](#globbing-features) + * [Basic globbing](#basic-globbing) + * [Advanced globbing](#advanced-globbing) + * [Braces](#braces) + * [Matching special characters as literals](#matching-special-characters-as-literals) +- [Library Comparisons](#library-comparisons) +- [Benchmarks](#benchmarks) +- [Philosophies](#philosophies) +- [About](#about) + * [Author](#author) + * [License](#license) + +_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_ + +
+ +
+
+ +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +npm install --save picomatch +``` + +
+ +## Usage + +The main export is a function that takes a glob pattern and an options object and returns a function for matching strings. + +```js +const pm = require('picomatch'); +const isMatch = pm('*.js'); + +console.log(isMatch('abcd')); //=> false +console.log(isMatch('a.js')); //=> true +console.log(isMatch('a.md')); //=> false +console.log(isMatch('a/b.js')); //=> false +``` + +
+ +## API + +### [picomatch](lib/picomatch.js#L31) + +Creates a matcher function from one or more glob patterns. The returned function takes a string to match as its first argument, and returns true if the string is a match. The returned matcher function also takes a boolean as the second argument that, when true, returns an object with additional information. + +**Params** + +* `globs` **{String|Array}**: One or more glob patterns. +* `options` **{Object=}** +* `returns` **{Function=}**: Returns a matcher function. + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch(glob[, options]); + +const isMatch = picomatch('*.!(*a)'); +console.log(isMatch('a.a')); //=> false +console.log(isMatch('a.b')); //=> true +``` + +**Example without node.js** + +For environments without `node.js`, `picomatch/posix` provides you a dependency-free matcher, without automatic OS detection. + +```js +const picomatch = require('picomatch/posix'); +// the same API, defaulting to posix paths +const isMatch = picomatch('a/*'); +console.log(isMatch('a\\b')); //=> false +console.log(isMatch('a/b')); //=> true + +// you can still configure the matcher function to accept windows paths +const isMatch = picomatch('a/*', { options: windows }); +console.log(isMatch('a\\b')); //=> true +console.log(isMatch('a/b')); //=> true +``` + +### [.test](lib/picomatch.js#L116) + +Test `input` with the given `regex`. This is used by the main `picomatch()` function to test the input string. + +**Params** + +* `input` **{String}**: String to test. +* `regex` **{RegExp}** +* `returns` **{Object}**: Returns an object with matching info. + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.test(input, regex[, options]); + +console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); +// { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } +``` + +### [.matchBase](lib/picomatch.js#L160) + +Match the basename of a filepath. + +**Params** + +* `input` **{String}**: String to test. +* `glob` **{RegExp|String}**: Glob pattern or regex created by [.makeRe](#makeRe). +* `returns` **{Boolean}** + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.matchBase(input, glob[, options]); +console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true +``` + +### [.isMatch](lib/picomatch.js#L182) + +Returns true if **any** of the given glob `patterns` match the specified `string`. + +**Params** + +* **{String|Array}**: str The string to test. +* **{String|Array}**: patterns One or more glob patterns to use for matching. +* **{Object}**: See available [options](#options). +* `returns` **{Boolean}**: Returns true if any patterns match `str` + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.isMatch(string, patterns[, options]); + +console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true +console.log(picomatch.isMatch('a.a', 'b.*')); //=> false +``` + +### [.parse](lib/picomatch.js#L198) + +Parse a glob pattern to create the source string for a regular expression. + +**Params** + +* `pattern` **{String}** +* `options` **{Object}** +* `returns` **{Object}**: Returns an object with useful properties and output to be used as a regex source string. + +**Example** + +```js +const picomatch = require('picomatch'); +const result = picomatch.parse(pattern[, options]); +``` + +### [.scan](lib/picomatch.js#L230) + +Scan a glob pattern to separate the pattern into segments. + +**Params** + +* `input` **{String}**: Glob pattern to scan. +* `options` **{Object}** +* `returns` **{Object}**: Returns an object with + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.scan(input[, options]); + +const result = picomatch.scan('!./foo/*.js'); +console.log(result); +{ prefix: '!./', + input: '!./foo/*.js', + start: 3, + base: 'foo', + glob: '*.js', + isBrace: false, + isBracket: false, + isGlob: true, + isExtglob: false, + isGlobstar: false, + negated: true } +``` + +### [.compileRe](lib/picomatch.js#L244) + +Compile a regular expression from the `state` object returned by the +[parse()](#parse) method. + +**Params** + +* `state` **{Object}** +* `options` **{Object}** +* `returnOutput` **{Boolean}**: Intended for implementors, this argument allows you to return the raw output from the parser. +* `returnState` **{Boolean}**: Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. +* `returns` **{RegExp}** + +### [.makeRe](lib/picomatch.js#L285) + +Create a regular expression from a parsed glob pattern. + +**Params** + +* `state` **{String}**: The object returned from the `.parse` method. +* `options` **{Object}** +* `returnOutput` **{Boolean}**: Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. +* `returnState` **{Boolean}**: Implementors may use this argument to return the state from the parsed glob with the returned regular expression. +* `returns` **{RegExp}**: Returns a regex created from the given pattern. + +**Example** + +```js +const picomatch = require('picomatch'); +const state = picomatch.parse('*.js'); +// picomatch.compileRe(state[, options]); + +console.log(picomatch.compileRe(state)); +//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ +``` + +### [.toRegex](lib/picomatch.js#L320) + +Create a regular expression from the given regex source string. + +**Params** + +* `source` **{String}**: Regular expression source string. +* `options` **{Object}** +* `returns` **{RegExp}** + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.toRegex(source[, options]); + +const { output } = picomatch.parse('*.js'); +console.log(picomatch.toRegex(output)); +//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ +``` + +
+ +## Options + +### Picomatch options + +The following options may be used with the main `picomatch()` function or any of the methods on the picomatch API. + +| **Option** | **Type** | **Default value** | **Description** | +| --- | --- | --- | --- | +| `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. | +| `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). | +| `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. | +| `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). | +| `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` | +| `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. | +| `dot` | `boolean` | `false` | Enable dotfile matching. By default, dotfiles are ignored unless a `.` is explicitly defined in the pattern, or `options.dot` is true | +| `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. | +| `failglob` | `boolean` | `false` | Throws an error if no matches are found. Based on the bash option of the same name. | +| `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. | +| `flags` | `string` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. | +| [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. | +| `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. | +| `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. | +| `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. | +| `matchBase` | `boolean` | `false` | Alias for `basename` | +| `maxLength` | `number` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. | +| `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. | +| `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. | +| `nocase` | `boolean` | `false` | Make matching case-insensitive. Equivalent to the regex `i` flag. Note that this option is overridden by the `flags` option. | +| `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. | +| `noext` | `boolean` | `false` | Alias for `noextglob` | +| `noextglob` | `boolean` | `false` | Disable support for matching with extglobs (like `+(a\|b)`) | +| `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) | +| `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` | +| `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. | +| [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. | +| [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. | +| [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. | +| `posix` | `boolean` | `false` | Support POSIX character classes ("posix brackets"). | +| `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself | +| `prepend` | `boolean` | `undefined` | String to prepend to the generated regex used for matching. | +| `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). | +| `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. | +| `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. | +| `unescape` | `boolean` | `undefined` | Remove backslashes preceding escaped characters in the glob pattern. By default, backslashes are retained. | +| `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatibility. | +| `windows` | `boolean` | `false` | Also accept backslashes as the path separator. | + +### Scan Options + +In addition to the main [picomatch options](#picomatch-options), the following options may also be used with the [.scan](#scan) method. + +| **Option** | **Type** | **Default value** | **Description** | +| --- | --- | --- | --- | +| `tokens` | `boolean` | `false` | When `true`, the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern | +| `parts` | `boolean` | `false` | When `true`, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when `options.tokens` is true | + +**Example** + +```js +const picomatch = require('picomatch'); +const result = picomatch.scan('!./foo/*.js', { tokens: true }); +console.log(result); +// { +// prefix: '!./', +// input: '!./foo/*.js', +// start: 3, +// base: 'foo', +// glob: '*.js', +// isBrace: false, +// isBracket: false, +// isGlob: true, +// isExtglob: false, +// isGlobstar: false, +// negated: true, +// maxDepth: 2, +// tokens: [ +// { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true }, +// { value: 'foo', depth: 1, isGlob: false }, +// { value: '*.js', depth: 1, isGlob: true } +// ], +// slashes: [ 2, 6 ], +// parts: [ 'foo', '*.js' ] +// } +``` + +
+ +### Options Examples + +#### options.expandRange + +**Type**: `function` + +**Default**: `undefined` + +Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need. + +**Example** + +The following example shows how to create a glob that matches a folder + +```js +const fill = require('fill-range'); +const regex = pm.makeRe('foo/{01..25}/bar', { + expandRange(a, b) { + return `(${fill(a, b, { toRegex: true })})`; + } +}); + +console.log(regex); +//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/ + +console.log(regex.test('foo/00/bar')) // false +console.log(regex.test('foo/01/bar')) // true +console.log(regex.test('foo/10/bar')) // true +console.log(regex.test('foo/22/bar')) // true +console.log(regex.test('foo/25/bar')) // true +console.log(regex.test('foo/26/bar')) // false +``` + +#### options.format + +**Type**: `function` + +**Default**: `undefined` + +Custom function for formatting strings before they're matched. + +**Example** + +```js +// strip leading './' from strings +const format = str => str.replace(/^\.\//, ''); +const isMatch = picomatch('foo/*.js', { format }); +console.log(isMatch('./foo/bar.js')); //=> true +``` + +#### options.onMatch + +```js +const onMatch = ({ glob, regex, input, output }) => { + console.log({ glob, regex, input, output }); +}; + +const isMatch = picomatch('*', { onMatch }); +isMatch('foo'); +isMatch('bar'); +isMatch('baz'); +``` + +#### options.onIgnore + +```js +const onIgnore = ({ glob, regex, input, output }) => { + console.log({ glob, regex, input, output }); +}; + +const isMatch = picomatch('*', { onIgnore, ignore: 'f*' }); +isMatch('foo'); +isMatch('bar'); +isMatch('baz'); +``` + +#### options.onResult + +```js +const onResult = ({ glob, regex, input, output }) => { + console.log({ glob, regex, input, output }); +}; + +const isMatch = picomatch('*', { onResult, ignore: 'f*' }); +isMatch('foo'); +isMatch('bar'); +isMatch('baz'); +``` + +
+
+ +## Globbing features + +* [Basic globbing](#basic-globbing) (Wildcard matching) +* [Advanced globbing](#advanced-globbing) (extglobs, posix brackets, brace matching) + +### Basic globbing + +| **Character** | **Description** | +| --- | --- | +| `*` | Matches any character zero or more times, excluding path separators. Does _not match_ path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the `dot` option to `true`. | +| `**` | Matches any character zero or more times, including path separators. Note that `**` will only match path separators (`/`, and `\\` with the `windows` option) when they are the only characters in a path segment. Thus, `foo**/bar` is equivalent to `foo*/bar`, and `foo/a**b/bar` is equivalent to `foo/a*b/bar`, and _more than two_ consecutive stars in a glob path segment are regarded as _a single star_. Thus, `foo/***/bar` is equivalent to `foo/*/bar`. | +| `?` | Matches any character excluding path separators one time. Does _not match_ path separators or leading dots. | +| `[abc]` | Matches any characters inside the brackets. For example, `[abc]` would match the characters `a`, `b` or `c`, and nothing else. | + +#### Matching behavior vs. Bash + +Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions: + +* Bash will match `foo/bar/baz` with `*`. Picomatch only matches nested directories with `**`. +* Bash greedily matches with negated extglobs. For example, Bash 4.3 says that `!(foo)*` should match `foo` and `foobar`, since the trailing `*` bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would return `false` for both `foo` and `foobar`. + +
+ +### Advanced globbing + +* [extglobs](#extglobs) +* [POSIX brackets](#posix-brackets) +* [Braces](#brace-expansion) + +#### Extglobs + +| **Pattern** | **Description** | +| --- | --- | +| `@(pattern)` | Match _only one_ consecutive occurrence of `pattern` | +| `*(pattern)` | Match _zero or more_ consecutive occurrences of `pattern` | +| `+(pattern)` | Match _one or more_ consecutive occurrences of `pattern` | +| `?(pattern)` | Match _zero or **one**_ consecutive occurrences of `pattern` | +| `!(pattern)` | Match _anything but_ `pattern` | + +**Examples** + +```js +const pm = require('picomatch'); + +// *(pattern) matches ZERO or more of "pattern" +console.log(pm.isMatch('a', 'a*(z)')); // true +console.log(pm.isMatch('az', 'a*(z)')); // true +console.log(pm.isMatch('azzz', 'a*(z)')); // true + +// +(pattern) matches ONE or more of "pattern" +console.log(pm.isMatch('a', 'a+(z)')); // false +console.log(pm.isMatch('az', 'a+(z)')); // true +console.log(pm.isMatch('azzz', 'a+(z)')); // true + +// supports multiple extglobs +console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false + +// supports nested extglobs +console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true +``` + +#### POSIX brackets + +POSIX classes are disabled by default. Enable this feature by setting the `posix` option to true. + +**Enable POSIX bracket support** + +```js +console.log(pm.makeRe('[[:word:]]+', { posix: true })); +//=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/ +``` + +**Supported POSIX classes** + +The following named POSIX bracket expressions are supported: + +* `[:alnum:]` - Alphanumeric characters, equ `[a-zA-Z0-9]` +* `[:alpha:]` - Alphabetical characters, equivalent to `[a-zA-Z]`. +* `[:ascii:]` - ASCII characters, equivalent to `[\\x00-\\x7F]`. +* `[:blank:]` - Space and tab characters, equivalent to `[ \\t]`. +* `[:cntrl:]` - Control characters, equivalent to `[\\x00-\\x1F\\x7F]`. +* `[:digit:]` - Numerical digits, equivalent to `[0-9]`. +* `[:graph:]` - Graph characters, equivalent to `[\\x21-\\x7E]`. +* `[:lower:]` - Lowercase letters, equivalent to `[a-z]`. +* `[:print:]` - Print characters, equivalent to `[\\x20-\\x7E ]`. +* `[:punct:]` - Punctuation and symbols, equivalent to `[\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~]`. +* `[:space:]` - Extended space characters, equivalent to `[ \\t\\r\\n\\v\\f]`. +* `[:upper:]` - Uppercase letters, equivalent to `[A-Z]`. +* `[:word:]` - Word characters (letters, numbers and underscores), equivalent to `[A-Za-z0-9_]`. +* `[:xdigit:]` - Hexadecimal digits, equivalent to `[A-Fa-f0-9]`. + +See the [Bash Reference Manual](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) for more information. + +### Braces + +Picomatch does not do brace expansion. For [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) and advanced matching with braces, use [micromatch](https://github.com/micromatch/micromatch) instead. Picomatch has very basic support for braces. + +### Matching special characters as literals + +If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes: + +**Special Characters** + +Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms. + +To match any of the following characters as literals: `$^*+?()[] + +Examples: + +```js +console.log(pm.makeRe('foo/bar \\(1\\)')); +console.log(pm.makeRe('foo/bar \\(1\\)')); +``` + +
+
+ +## Library Comparisons + +The following table shows which features are supported by [minimatch](https://github.com/isaacs/minimatch), [micromatch](https://github.com/micromatch/micromatch), [picomatch](https://github.com/micromatch/picomatch), [nanomatch](https://github.com/micromatch/nanomatch), [extglob](https://github.com/micromatch/extglob), [braces](https://github.com/micromatch/braces), and [expand-brackets](https://github.com/micromatch/expand-brackets). + +| **Feature** | `minimatch` | `micromatch` | `picomatch` | `nanomatch` | `extglob` | `braces` | `expand-brackets` | +| --- | --- | --- | --- | --- | --- | --- | --- | +| Wildcard matching (`*?+`) | ✔ | ✔ | ✔ | ✔ | - | - | - | +| Advancing globbing | ✔ | ✔ | ✔ | - | - | - | - | +| Brace _matching_ | ✔ | ✔ | ✔ | - | - | ✔ | - | +| Brace _expansion_ | ✔ | ✔ | - | - | - | ✔ | - | +| Extglobs | partial | ✔ | ✔ | - | ✔ | - | - | +| Posix brackets | - | ✔ | ✔ | - | - | - | ✔ | +| Regular expression syntax | - | ✔ | ✔ | ✔ | ✔ | - | ✔ | +| File system operations | - | - | - | - | - | - | - | + +
+
+ +## Benchmarks + +Performance comparison of picomatch and minimatch. + +_(Pay special attention to the last three benchmarks. Minimatch freezes on long ranges.)_ + +``` +# .makeRe star (*) + picomatch x 4,449,159 ops/sec ±0.24% (97 runs sampled) + minimatch x 632,772 ops/sec ±0.14% (98 runs sampled) + +# .makeRe star; dot=true (*) + picomatch x 3,500,079 ops/sec ±0.26% (99 runs sampled) + minimatch x 564,916 ops/sec ±0.23% (96 runs sampled) + +# .makeRe globstar (**) + picomatch x 3,261,000 ops/sec ±0.27% (98 runs sampled) + minimatch x 1,664,766 ops/sec ±0.20% (100 runs sampled) + +# .makeRe globstars (**/**/**) + picomatch x 3,284,469 ops/sec ±0.18% (97 runs sampled) + minimatch x 1,435,880 ops/sec ±0.34% (95 runs sampled) + +# .makeRe with leading star (*.txt) + picomatch x 3,100,197 ops/sec ±0.35% (99 runs sampled) + minimatch x 428,347 ops/sec ±0.42% (94 runs sampled) + +# .makeRe - basic braces ({a,b,c}*.txt) + picomatch x 443,578 ops/sec ±1.33% (89 runs sampled) + minimatch x 107,143 ops/sec ±0.35% (94 runs sampled) + +# .makeRe - short ranges ({a..z}*.txt) + picomatch x 415,484 ops/sec ±0.76% (96 runs sampled) + minimatch x 14,299 ops/sec ±0.26% (96 runs sampled) + +# .makeRe - medium ranges ({1..100000}*.txt) + picomatch x 395,020 ops/sec ±0.87% (89 runs sampled) + minimatch x 2 ops/sec ±4.59% (10 runs sampled) + +# .makeRe - long ranges ({1..10000000}*.txt) + picomatch x 400,036 ops/sec ±0.83% (90 runs sampled) + minimatch (FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory) +``` + +
+
+ +## Philosophies + +The goal of this library is to be blazing fast, without compromising on accuracy. + +**Accuracy** + +The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: `!(**/{a,b,*/c})`. + +Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements. + +**Performance** + +Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer. + +
+
+ +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2017-present, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). diff --git a/node_modules/picomatch/index.js b/node_modules/picomatch/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a753b1d9e843c93b62700aa155db920a1a940baa --- /dev/null +++ b/node_modules/picomatch/index.js @@ -0,0 +1,17 @@ +'use strict'; + +const pico = require('./lib/picomatch'); +const utils = require('./lib/utils'); + +function picomatch(glob, options, returnState = false) { + // default to os.platform() + if (options && (options.windows === null || options.windows === undefined)) { + // don't mutate the original options object + options = { ...options, windows: utils.isWindows() }; + } + + return pico(glob, options, returnState); +} + +Object.assign(picomatch, pico); +module.exports = picomatch; diff --git a/node_modules/picomatch/lib/constants.js b/node_modules/picomatch/lib/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..3f7ef7e53adaf9d3021fba01aaafe600b5ff772f --- /dev/null +++ b/node_modules/picomatch/lib/constants.js @@ -0,0 +1,180 @@ +'use strict'; + +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; + +/** + * Posix glob regex + */ + +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR = `${QMARK}*?`; +const SEP = '/'; + +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR, + SEP +}; + +/** + * Windows glob regex + */ + +const WINDOWS_CHARS = { + ...POSIX_CHARS, + + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)`, + SEP: '\\' +}; + +/** + * POSIX Bracket Regex + */ + +const POSIX_REGEX_SOURCE = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; + +module.exports = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE, + + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + __proto__: null, + '***': '*', + '**/**': '**', + '**/**/**': '**' + }, + + // Digits + CHAR_0: 48, /* 0 */ + CHAR_9: 57, /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 65, /* A */ + CHAR_LOWERCASE_A: 97, /* a */ + CHAR_UPPERCASE_Z: 90, /* Z */ + CHAR_LOWERCASE_Z: 122, /* z */ + + CHAR_LEFT_PARENTHESES: 40, /* ( */ + CHAR_RIGHT_PARENTHESES: 41, /* ) */ + + CHAR_ASTERISK: 42, /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, /* & */ + CHAR_AT: 64, /* @ */ + CHAR_BACKWARD_SLASH: 92, /* \ */ + CHAR_CARRIAGE_RETURN: 13, /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ + CHAR_COLON: 58, /* : */ + CHAR_COMMA: 44, /* , */ + CHAR_DOT: 46, /* . */ + CHAR_DOUBLE_QUOTE: 34, /* " */ + CHAR_EQUAL: 61, /* = */ + CHAR_EXCLAMATION_MARK: 33, /* ! */ + CHAR_FORM_FEED: 12, /* \f */ + CHAR_FORWARD_SLASH: 47, /* / */ + CHAR_GRAVE_ACCENT: 96, /* ` */ + CHAR_HASH: 35, /* # */ + CHAR_HYPHEN_MINUS: 45, /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ + CHAR_LEFT_CURLY_BRACE: 123, /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ + CHAR_LINE_FEED: 10, /* \n */ + CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ + CHAR_PERCENT: 37, /* % */ + CHAR_PLUS: 43, /* + */ + CHAR_QUESTION_MARK: 63, /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ + CHAR_SEMICOLON: 59, /* ; */ + CHAR_SINGLE_QUOTE: 39, /* ' */ + CHAR_SPACE: 32, /* */ + CHAR_TAB: 9, /* \t */ + CHAR_UNDERSCORE: 95, /* _ */ + CHAR_VERTICAL_LINE: 124, /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ + + /** + * Create EXTGLOB_CHARS + */ + + extglobChars(chars) { + return { + '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, + '?': { type: 'qmark', open: '(?:', close: ')?' }, + '+': { type: 'plus', open: '(?:', close: ')+' }, + '*': { type: 'star', open: '(?:', close: ')*' }, + '@': { type: 'at', open: '(?:', close: ')' } + }; + }, + + /** + * Create GLOB_CHARS + */ + + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } +}; diff --git a/node_modules/picomatch/lib/parse.js b/node_modules/picomatch/lib/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..8fd8ff499d182f05ffb9aaa342f5ed7541f3d89e --- /dev/null +++ b/node_modules/picomatch/lib/parse.js @@ -0,0 +1,1085 @@ +'use strict'; + +const constants = require('./constants'); +const utils = require('./utils'); + +/** + * Constants + */ + +const { + MAX_LENGTH, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants; + +/** + * Helpers + */ + +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } + + args.sort(); + const value = `[${args.join('-')}]`; + + try { + /* eslint-disable-next-line no-new */ + new RegExp(value); + } catch (ex) { + return args.map(v => utils.escapeRegex(v)).join('..'); + } + + return value; +}; + +/** + * Create the message for a syntax error + */ + +const syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; + +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + +const parse = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + input = REPLACEMENTS[input] || input; + + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + const bos = { type: 'bos', value: '', output: opts.prepend || '' }; + const tokens = [bos]; + + const capture = opts.capture ? '' : '?:'; + + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants.globChars(opts.windows); + const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); + + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; + + const globstar = opts => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + // minimatch options support + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } + + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + + input = utils.removePrefix(input, state); + len = input.length; + + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + + /** + * Tokenizing helpers + */ + + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index] || ''; + const remaining = () => input.slice(state.index + 1); + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; + + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; + } + + if (count % 2 === 0) { + return false; + } + + state.negated = true; + state.start++; + return true; + }; + + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } + } + + if (extglobs.length && tok.type !== 'paren') { + extglobs[extglobs.length - 1].inner += tok.value; + } + + if (tok.value || tok.output) append(tok); + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.output = (prev.output || prev.value) + tok.value; + prev.value += tok.value; + return; + } + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? '(' : '') + token.open; + + increment('parens'); + push({ type, value, output: state.output ? '' : ONE_CHAR }); + push({ type: 'paren', extglob: true, value: advance(), output }); + extglobs.push(token); + }; + + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + let rest; + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + + if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { + // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. + // In this case, we need to parse the string and use it in the output of the original pattern. + // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. + // + // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. + const expression = parse(rest, { ...options, fastpaths: false }).output; + + output = token.close = `)${expression})${extglobStar})`; + } + + if (token.prev.type === 'bos') { + state.negatedExtglob = true; + } + } + + push({ type: 'paren', extglob: true, value, output }); + decrement('parens'); + }; + + /** + * Fast paths + */ + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); + } + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); + } + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); + } + return star; + } + return esc ? m : `\\${m}`; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); + }); + } + } + + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + + state.output = utils.wrapOutput(output, state, options); + return state; + } + + /** + * Tokenize input until we reach end-of-string + */ + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; + } + + /** + * Escaped characters + */ + + if (value === '\\') { + const next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ type: 'text', value }); + continue; + } + + // collapse slashes to reduce potential for exploits + const match = /^\\+/.exec(remaining()); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += '\\'; + } + } + + if (opts.unescape === true) { + value = advance(); + } else { + value += advance(); + } + + if (state.brackets === 0) { + push({ type: 'text', value }); + continue; + } + } + + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ + + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE[rest]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } + } + } + + if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { + value = `\\${value}`; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ value }); + continue; + } + + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + if (state.quotes === 1 && value !== '"') { + value = utils.escapeRegex(value); + prev.value += value; + append({ value }); + continue; + } + + /** + * Double quotes + */ + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({ type: 'text', value }); + } + continue; + } + + /** + * Parentheses + */ + + if (value === '(') { + increment('parens'); + push({ type: 'paren', value }); + continue; + } + + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } + + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + + push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); + decrement('parens'); + continue; + } + + /** + * Square brackets + */ + + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); + } + + value = `\\${value}`; + } else { + increment('brackets'); + } + + push({ type: 'bracket', value }); + continue; + } + + if (value === ']') { + if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); + } + + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + decrement('brackets'); + + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } + + prev.value += value; + append({ value }); + + // when literal brackets are explicitly disabled + // assume we should match with a regex character class + if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { + continue; + } + + const escaped = utils.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); + + // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } + + // when the user specifies nothing, try to match both + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + + /** + * Braces + */ + + if (value === '{' && opts.nobrace !== true) { + increment('braces'); + + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + + braces.push(open); + push(open); + continue; + } + + if (value === '}') { + const brace = braces[braces.length - 1]; + + if (opts.nobrace === true || !brace) { + push({ type: 'text', value, output: value }); + continue; + } + + let output = ')'; + + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; + + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === 'brace') { + break; + } + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } + + output = expandRange(range, opts); + state.backtrack = true; + } + + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = '\\}'; + state.output = out; + for (const t of toks) { + state.output += (t.output || t.value); + } + } + + push({ type: 'brace', value, output }); + decrement('braces'); + braces.pop(); + continue; + } + + /** + * Pipes + */ + + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push({ type: 'text', value }); + continue; + } + + /** + * Commas + */ + + if (value === ',') { + let output = value; + + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; + } + + push({ type: 'comma', value, output }); + continue; + } + + /** + * Slashes + */ + + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + continue; + } + + push({ type: 'slash', value, output: SLASH_LITERAL }); + continue; + } + + /** + * Dots + */ + + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + + if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ type: 'text', value, output: DOT_LITERAL }); + continue; + } + + push({ type: 'dot', value, output: DOT_LITERAL }); + continue; + } + + /** + * Question marks + */ + + if (value === '?') { + const isGroup = prev && prev.value === '('; + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } + + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; + + if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { + output = `\\${value}`; + } + + push({ type: 'text', value, output }); + continue; + } + + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ type: 'qmark', value, output: QMARK_NO_DOT }); + continue; + } + + push({ type: 'qmark', value, output: QMARK }); + continue; + } + + /** + * Exclamation + */ + + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } + + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + + /** + * Plus + */ + + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } + + if ((prev && prev.value === '(') || opts.regex === false) { + push({ type: 'plus', value, output: PLUS_LITERAL }); + continue; + } + + if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { + push({ type: 'plus', value }); + continue; + } + + push({ type: 'plus', value: PLUS_LITERAL }); + continue; + } + + /** + * Plain text + */ + + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ type: 'at', extglob: true, value, output: '' }); + continue; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Plain text + */ + + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } + + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Stars + */ + + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; + } + + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } + + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); + + if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { + push({ type: 'star', value, output: '' }); + continue; + } + + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ type: 'star', value, output: '' }); + continue; + } + + // strip consecutive `/**/` + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + if (after && after !== '/') { + break; + } + rest = rest.slice(3); + consume('/**', 3); + } + + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; + + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + + state.output += prior.output + prev.output; + state.globstar = true; + + consume(value + advance()); + + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + // remove single star from output + state.output = state.output.slice(0, -prev.output.length); + + // reset previous token to globstar + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; + + // reset output with globstar + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + + const token = { type: 'star', value, output: star }; + + if (opts.bash === true) { + token.output = '.*?'; + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + push(token); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } + + if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { + if (prev.type === 'dot') { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + + } else { + state.output += nodot; + prev.output += nodot; + } + + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + + push(token); + } + + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils.escapeLast(state.output, '{'); + decrement('braces'); + } + + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + } + + // rebuild the output if we had to backtrack at any point + if (state.backtrack === true) { + state.output = ''; + + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + + if (token.suffix) { + state.output += token.suffix; + } + } + } + + return state; +}; + +/** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ + +parse.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + input = REPLACEMENTS[input] || input; + + // create constants based on platform, for windows or posix + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants.globChars(opts.windows); + + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { negated: false, prefix: '' }; + let star = opts.bash === true ? '.*?' : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + const globstar = opts => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; + + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + + case '**': + return nodot + globstar(opts); + + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; + + const source = create(match[1]); + if (!source) return; + + return source + DOT_LITERAL + match[2]; + } + } + }; + + const output = utils.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; +}; + +module.exports = parse; diff --git a/node_modules/picomatch/lib/picomatch.js b/node_modules/picomatch/lib/picomatch.js new file mode 100644 index 0000000000000000000000000000000000000000..d0ebd9f163cf240a00998dec9ed69523d1405b4d --- /dev/null +++ b/node_modules/picomatch/lib/picomatch.js @@ -0,0 +1,341 @@ +'use strict'; + +const scan = require('./scan'); +const parse = require('./parse'); +const utils = require('./utils'); +const constants = require('./constants'); +const isObject = val => val && typeof val === 'object' && !Array.isArray(val); + +/** + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public + */ + +const picomatch = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch(input, options, returnState)); + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + return false; + }; + return arrayMatcher; + } + + const isState = isObject(glob) && glob.tokens && glob.input; + + if (glob === '' || (typeof glob !== 'string' && !isState)) { + throw new TypeError('Expected pattern to be a non-empty string'); + } + + const opts = options || {}; + const posix = opts.windows; + const regex = isState + ? picomatch.compileRe(glob, options) + : picomatch.makeRe(glob, options, false, true); + + const state = regex.state; + delete regex.state; + + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; + isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); + } + + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); + const result = { glob, state, regex, posix, input, output, match, isMatch }; + + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } + + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + return returnObject ? result : true; + }; + + if (returnState) { + matcher.state = state; + } + + return matcher; +}; + +/** + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public + */ + +picomatch.test = (input, regex, options, { glob, posix } = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected input to be a string'); + } + + if (input === '') { + return { isMatch: false, output: '' }; + } + + const opts = options || {}; + const format = opts.format || (posix ? utils.toPosixSlashes : null); + let match = input === glob; + let output = (match && format) ? format(input) : input; + + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } + } + + return { isMatch: Boolean(match), match, output }; +}; + +/** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ + +picomatch.matchBase = (input, glob, options) => { + const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); + return regex.test(utils.basename(input)); +}; + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ + +picomatch.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); + return parse(pattern, { ...options, fastpaths: false }); +}; + +/** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +picomatch.scan = (input, options) => scan(input, options); + +/** + * Compile a regular expression from the `state` object returned by the + * [parse()](#parse) method. + * + * @param {Object} `state` + * @param {Object} `options` + * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. + * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. + * @return {RegExp} + * @api public + */ + +picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return state.output; + } + + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; + + let source = `${prepend}(?:${state.output})${append}`; + if (state && state.negated === true) { + source = `^(?!${source}).*$`; + } + + const regex = picomatch.toRegex(source, options); + if (returnState === true) { + regex.state = state; + } + + return regex; +}; + +/** + * Create a regular expression from a parsed glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); + * + * console.log(picomatch.compileRe(state)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `state` The object returned from the `.parse` method. + * @param {Object} `options` + * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. + * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } + + let parsed = { negated: false, fastpaths: true }; + + if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + parsed.output = parse.fastpaths(input, options); + } + + if (!parsed.output) { + parsed = parse(input, options); + } + + return picomatch.compileRe(parsed, options, returnOutput, returnState); +}; + +/** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +picomatch.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } +}; + +/** + * Picomatch constants. + * @return {Object} + */ + +picomatch.constants = constants; + +/** + * Expose "picomatch" + */ + +module.exports = picomatch; diff --git a/node_modules/picomatch/lib/scan.js b/node_modules/picomatch/lib/scan.js new file mode 100644 index 0000000000000000000000000000000000000000..e59cd7a1357b184b0c70409b161fcf0ce5433af1 --- /dev/null +++ b/node_modules/picomatch/lib/scan.js @@ -0,0 +1,391 @@ +'use strict'; + +const utils = require('./utils'); +const { + CHAR_ASTERISK, /* * */ + CHAR_AT, /* @ */ + CHAR_BACKWARD_SLASH, /* \ */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_EXCLAMATION_MARK, /* ! */ + CHAR_FORWARD_SLASH, /* / */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_PLUS, /* + */ + CHAR_QUESTION_MARK, /* ? */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_RIGHT_SQUARE_BRACKET /* ] */ +} = require('./constants'); + +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; + +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } +}; + +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not + * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ + +const scan = (input, options) => { + const opts = options || {}; + + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let negatedExtglob = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { value: '', depth: 0, isGlob: false }; + + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + + while (index < length) { + code = advance(); + let next; + + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + + if (code === CHAR_LEFT_CURLY_BRACE) { + braceEscaped = true; + } + continue; + } + + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; + + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } + + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (braceEscaped !== true && code === CHAR_COMMA) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; + + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { value: '', depth: 0, isGlob: false }; + + if (finished === true) continue; + if (prev === CHAR_DOT && index === (start + 1)) { + start += 2; + continue; + } + + lastIndex = index + 1; + continue; + } + + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS + || code === CHAR_AT + || code === CHAR_ASTERISK + || code === CHAR_QUESTION_MARK + || code === CHAR_EXCLAMATION_MARK; + + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + if (code === CHAR_EXCLAMATION_MARK && index === start) { + negatedExtglob = true; + } + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; + } + } + + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_LEFT_SQUARE_BRACKET) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + break; + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + finished = true; + break; + } + } + continue; + } + break; + } + + if (isGlob === true) { + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + } + + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + + let base = str; + let prefix = ''; + let glob = ''; + + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } + + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } + + if (opts.unescape === true) { + if (glob) glob = utils.removeBackslashes(glob); + + if (base && backslashes === true) { + base = utils.removeBackslashes(base); + } + } + + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated, + negatedExtglob + }; + + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); + } + state.tokens = tokens; + } + + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + if (idx !== 0 || value !== '') { + parts.push(value); + } + prevIndex = i; + } + + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + + state.slashes = slashes; + state.parts = parts; + } + + return state; +}; + +module.exports = scan; diff --git a/node_modules/picomatch/lib/utils.js b/node_modules/picomatch/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..9c97cae222ca82d7fc6fa29f2770212e0270bc03 --- /dev/null +++ b/node_modules/picomatch/lib/utils.js @@ -0,0 +1,72 @@ +/*global navigator*/ +'use strict'; + +const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL +} = require('./constants'); + +exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); +exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); +exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); +exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); +exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); + +exports.isWindows = () => { + if (typeof navigator !== 'undefined' && navigator.platform) { + const platform = navigator.platform.toLowerCase(); + return platform === 'win32' || platform === 'windows'; + } + + if (typeof process !== 'undefined' && process.platform) { + return process.platform === 'win32'; + } + + return false; +}; + +exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); +}; + +exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; +}; + +exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + return output; +}; + +exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; + + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + return output; +}; + +exports.basename = (path, { windows } = {}) => { + const segs = path.split(windows ? /[\\/]/ : '/'); + const last = segs[segs.length - 1]; + + if (last === '') { + return segs[segs.length - 2]; + } + + return last; +}; diff --git a/node_modules/picomatch/package.json b/node_modules/picomatch/package.json new file mode 100644 index 0000000000000000000000000000000000000000..372e27e05f412fd2d5ef4c28e4d79df1701bcf4a --- /dev/null +++ b/node_modules/picomatch/package.json @@ -0,0 +1,83 @@ +{ + "name": "picomatch", + "description": "Blazing fast and accurate glob matcher written in JavaScript, with no dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.", + "version": "4.0.3", + "homepage": "https://github.com/micromatch/picomatch", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "funding": "https://github.com/sponsors/jonschlinkert", + "repository": "micromatch/picomatch", + "bugs": { + "url": "https://github.com/micromatch/picomatch/issues" + }, + "license": "MIT", + "files": [ + "index.js", + "posix.js", + "lib" + ], + "sideEffects": false, + "main": "index.js", + "engines": { + "node": ">=12" + }, + "scripts": { + "lint": "eslint --cache --cache-location node_modules/.cache/.eslintcache --report-unused-disable-directives --ignore-path .gitignore .", + "mocha": "mocha --reporter dot", + "test": "npm run lint && npm run mocha", + "test:ci": "npm run test:cover", + "test:cover": "nyc npm run mocha" + }, + "devDependencies": { + "eslint": "^8.57.0", + "fill-range": "^7.0.1", + "gulp-format-md": "^2.0.0", + "mocha": "^10.4.0", + "nyc": "^15.1.0", + "time-require": "github:jonschlinkert/time-require" + }, + "keywords": [ + "glob", + "match", + "picomatch" + ], + "nyc": { + "reporter": [ + "html", + "lcov", + "text-summary" + ] + }, + "verb": { + "toc": { + "render": true, + "method": "preWrite", + "maxdepth": 3 + }, + "layout": "empty", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + }, + "related": { + "list": [ + "braces", + "micromatch" + ] + }, + "reflinks": [ + "braces", + "expand-brackets", + "extglob", + "fill-range", + "micromatch", + "minimatch", + "nanomatch", + "picomatch" + ] + } +} diff --git a/node_modules/picomatch/posix.js b/node_modules/picomatch/posix.js new file mode 100644 index 0000000000000000000000000000000000000000..d2f2bc59d0ac7c40b35c574c45bcedbf26263d75 --- /dev/null +++ b/node_modules/picomatch/posix.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/picomatch'); diff --git a/node_modules/pkg-dir/index.d.ts b/node_modules/pkg-dir/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3696e88c87b167977b72aadaf9096105a9175402 --- /dev/null +++ b/node_modules/pkg-dir/index.d.ts @@ -0,0 +1,41 @@ +declare const pkgDir: { + /** + Synchronously find the root directory of a Node.js project or npm package. + + @param cwd - Directory to start from. Default: `process.cwd()`. + @returns The project root path or `undefined` if it couldn't be found. + */ + sync: (cwd?: string) => string | undefined; + + /** + Find the root directory of a Node.js project or npm package. + + @param cwd - Directory to start from. Default: `process.cwd()`. + @returns The project root path or `undefined` if it couldn't be found. + + @example + ``` + // / + // └── Users + // └── sindresorhus + // └── foo + // ├── package.json + // └── bar + // ├── baz + // └── example.js + + // example.js + import pkgDir = require('pkg-dir'); + + (async () => { + const rootDir = await pkgDir(__dirname); + + console.log(rootDir); + //=> '/Users/sindresorhus/foo' + })(); + ``` + */ + (cwd?: string): Promise; +}; + +export = pkgDir; diff --git a/node_modules/pkg-dir/index.js b/node_modules/pkg-dir/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0f6b1d140601b7d46b3d99c4e881146aef95809f --- /dev/null +++ b/node_modules/pkg-dir/index.js @@ -0,0 +1,15 @@ +'use strict'; +const path = require('path'); +const findUp = require('find-up'); + +const pkgDir = async cwd => { + const filePath = await findUp('package.json', {cwd}); + return filePath && path.dirname(filePath); +}; + +module.exports = pkgDir; + +module.exports.sync = cwd => { + const filePath = findUp.sync('package.json', {cwd}); + return filePath && path.dirname(filePath); +}; diff --git a/node_modules/pkg-dir/license b/node_modules/pkg-dir/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/pkg-dir/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/pkg-dir/package.json b/node_modules/pkg-dir/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6da77163cd555b12d6f9be5440cc7dc13df39269 --- /dev/null +++ b/node_modules/pkg-dir/package.json @@ -0,0 +1,56 @@ +{ + "name": "pkg-dir", + "version": "5.0.0", + "description": "Find the root directory of a Node.js project or npm package", + "license": "MIT", + "repository": "sindresorhus/pkg-dir", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "package", + "json", + "root", + "npm", + "entry", + "find", + "up", + "find-up", + "findup", + "look-up", + "look", + "file", + "search", + "match", + "resolve", + "parent", + "parents", + "folder", + "directory", + "dir", + "walk", + "walking", + "path" + ], + "dependencies": { + "find-up": "^5.0.0" + }, + "devDependencies": { + "ava": "^2.4.0", + "tempy": "^1.0.0", + "tsd": "^0.13.1", + "xo": "^0.33.1" + } +} diff --git a/node_modules/pkg-dir/readme.md b/node_modules/pkg-dir/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..a81d7afb171dcbb37dfeb571d314bb54814b0f6d --- /dev/null +++ b/node_modules/pkg-dir/readme.md @@ -0,0 +1,69 @@ +# pkg-dir [![Build Status](https://travis-ci.com/sindresorhus/pkg-dir.svg?branch=master)](https://travis-ci.com/github/sindresorhus/pkg-dir) + +> Find the root directory of a Node.js project or npm package + +## Install + +``` +$ npm install pkg-dir +``` + +## Usage + +``` +/ +└── Users + └── sindresorhus + └── foo + ├── package.json + └── bar + ├── baz + └── example.js +``` + +```js +// example.js +const pkgDir = require('pkg-dir'); + +(async () => { + const rootDir = await pkgDir(__dirname); + + console.log(rootDir); + //=> '/Users/sindresorhus/foo' +})(); +``` + +## API + +### pkgDir(cwd?) + +Returns a `Promise` for either the project root path or `undefined` if it couldn't be found. + +### pkgDir.sync(cwd?) + +Returns the project root path or `undefined` if it couldn't be found. + +#### cwd + +Type: `string`\ +Default: `process.cwd()` + +Directory to start from. + +## Related + +- [pkg-dir-cli](https://github.com/sindresorhus/pkg-dir-cli) - CLI for this module +- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file +- [find-up](https://github.com/sindresorhus/find-up) - Find a file by walking up parent directories + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/playwright/LICENSE b/node_modules/playwright/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..df112373eb2e23e459bf93ec412be1764dc5a38b --- /dev/null +++ b/node_modules/playwright/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Portions Copyright (c) Microsoft Corporation. + Portions Copyright 2017 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/playwright/NOTICE b/node_modules/playwright/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..814ec1696f7ad36c1b524fb6adeef14b4b367fec --- /dev/null +++ b/node_modules/playwright/NOTICE @@ -0,0 +1,5 @@ +Playwright +Copyright (c) Microsoft Corporation + +This software contains code derived from the Puppeteer project (https://github.com/puppeteer/puppeteer), +available under the Apache 2.0 license (https://github.com/puppeteer/puppeteer/blob/master/LICENSE). diff --git a/node_modules/playwright/README.md b/node_modules/playwright/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8b6bd945d0767e2895821cbbe40240f9fc1e857a --- /dev/null +++ b/node_modules/playwright/README.md @@ -0,0 +1,168 @@ +# 🎭 Playwright + +[![npm version](https://img.shields.io/npm/v/playwright.svg)](https://www.npmjs.com/package/playwright) [![Chromium version](https://img.shields.io/badge/chromium-145.0.7632.6-blue.svg?logo=google-chrome)](https://www.chromium.org/Home) [![Firefox version](https://img.shields.io/badge/firefox-146.0.1-blue.svg?logo=firefoxbrowser)](https://www.mozilla.org/en-US/firefox/new/) [![WebKit version](https://img.shields.io/badge/webkit-26.0-blue.svg?logo=safari)](https://webkit.org/) [![Join Discord](https://img.shields.io/badge/join-discord-informational)](https://aka.ms/playwright/discord) + +## [Documentation](https://playwright.dev) | [API reference](https://playwright.dev/docs/api/class-playwright) + +Playwright is a framework for Web Testing and Automation. It allows testing [Chromium](https://www.chromium.org/Home), [Firefox](https://www.mozilla.org/en-US/firefox/new/) and [WebKit](https://webkit.org/) with a single API. Playwright is built to enable cross-browser web automation that is **ever-green**, **capable**, **reliable**, and **fast**. + +| | Linux | macOS | Windows | +| :--- | :---: | :---: | :---: | +| Chromium 145.0.7632.6 | :white_check_mark: | :white_check_mark: | :white_check_mark: | +| WebKit 26.0 | :white_check_mark: | :white_check_mark: | :white_check_mark: | +| Firefox 146.0.1 | :white_check_mark: | :white_check_mark: | :white_check_mark: | + +Headless execution is supported for all browsers on all platforms. Check out [system requirements](https://playwright.dev/docs/intro#system-requirements) for details. + +Looking for Playwright for [Python](https://playwright.dev/python/docs/intro), [.NET](https://playwright.dev/dotnet/docs/intro), or [Java](https://playwright.dev/java/docs/intro)? + +## Installation + +Playwright has its own test runner for end-to-end tests, we call it Playwright Test. + +### Using init command + +The easiest way to get started with Playwright Test is to run the init command. + +```Shell +# Run from your project's root directory +npm init playwright@latest +# Or create a new project +npm init playwright@latest new-project +``` + +This will create a configuration file, optionally add examples, a GitHub Action workflow and a first test example.spec.ts. You can now jump directly to writing assertions section. + +### Manually + +Add dependency and install browsers. + +```Shell +npm i -D @playwright/test +# install supported browsers +npx playwright install +``` + +You can optionally install only selected browsers, see [install browsers](https://playwright.dev/docs/cli#install-browsers) for more details. Or you can install no browsers at all and use existing [browser channels](https://playwright.dev/docs/browsers). + +* [Getting started](https://playwright.dev/docs/intro) +* [API reference](https://playwright.dev/docs/api/class-playwright) + +## Capabilities + +### Resilient • No flaky tests + +**Auto-wait**. Playwright waits for elements to be actionable prior to performing actions. It also has a rich set of introspection events. The combination of the two eliminates the need for artificial timeouts - a primary cause of flaky tests. + +**Web-first assertions**. Playwright assertions are created specifically for the dynamic web. Checks are automatically retried until the necessary conditions are met. + +**Tracing**. Configure test retry strategy, capture execution trace, videos and screenshots to eliminate flakes. + +### No trade-offs • No limits + +Browsers run web content belonging to different origins in different processes. Playwright is aligned with the architecture of the modern browsers and runs tests out-of-process. This makes Playwright free of the typical in-process test runner limitations. + +**Multiple everything**. Test scenarios that span multiple tabs, multiple origins and multiple users. Create scenarios with different contexts for different users and run them against your server, all in one test. + +**Trusted events**. Hover elements, interact with dynamic controls and produce trusted events. Playwright uses real browser input pipeline indistinguishable from the real user. + +Test frames, pierce Shadow DOM. Playwright selectors pierce shadow DOM and allow entering frames seamlessly. + +### Full isolation • Fast execution + +**Browser contexts**. Playwright creates a browser context for each test. Browser context is equivalent to a brand new browser profile. This delivers full test isolation with zero overhead. Creating a new browser context only takes a handful of milliseconds. + +**Log in once**. Save the authentication state of the context and reuse it in all the tests. This bypasses repetitive log-in operations in each test, yet delivers full isolation of independent tests. + +### Powerful Tooling + +**[Codegen](https://playwright.dev/docs/codegen)**. Generate tests by recording your actions. Save them into any language. + +**[Playwright inspector](https://playwright.dev/docs/inspector)**. Inspect page, generate selectors, step through the test execution, see click points and explore execution logs. + +**[Trace Viewer](https://playwright.dev/docs/trace-viewer)**. Capture all the information to investigate the test failure. Playwright trace contains test execution screencast, live DOM snapshots, action explorer, test source and many more. + +Looking for Playwright for [TypeScript](https://playwright.dev/docs/intro), [JavaScript](https://playwright.dev/docs/intro), [Python](https://playwright.dev/python/docs/intro), [.NET](https://playwright.dev/dotnet/docs/intro), or [Java](https://playwright.dev/java/docs/intro)? + +## Examples + +To learn how to run these Playwright Test examples, check out our [getting started docs](https://playwright.dev/docs/intro). + +#### Page screenshot + +This code snippet navigates to Playwright homepage and saves a screenshot. + +```TypeScript +import { test } from '@playwright/test'; + +test('Page Screenshot', async ({ page }) => { + await page.goto('https://playwright.dev/'); + await page.screenshot({ path: `example.png` }); +}); +``` + +#### Mobile and geolocation + +This snippet emulates Mobile Safari on a device at given geolocation, navigates to maps.google.com, performs the action and takes a screenshot. + +```TypeScript +import { test, devices } from '@playwright/test'; + +test.use({ + ...devices['iPhone 13 Pro'], + locale: 'en-US', + geolocation: { longitude: 12.492507, latitude: 41.889938 }, + permissions: ['geolocation'], +}) + +test('Mobile and geolocation', async ({ page }) => { + await page.goto('https://maps.google.com'); + await page.getByText('Your location').click(); + await page.waitForRequest(/.*preview\/pwa/); + await page.screenshot({ path: 'colosseum-iphone.png' }); +}); +``` + +#### Evaluate in browser context + +This code snippet navigates to example.com, and executes a script in the page context. + +```TypeScript +import { test } from '@playwright/test'; + +test('Evaluate in browser context', async ({ page }) => { + await page.goto('https://www.example.com/'); + const dimensions = await page.evaluate(() => { + return { + width: document.documentElement.clientWidth, + height: document.documentElement.clientHeight, + deviceScaleFactor: window.devicePixelRatio + } + }); + console.log(dimensions); +}); +``` + +#### Intercept network requests + +This code snippet sets up request routing for a page to log all network requests. + +```TypeScript +import { test } from '@playwright/test'; + +test('Intercept network requests', async ({ page }) => { + // Log and continue all network requests + await page.route('**', route => { + console.log(route.request().url()); + route.continue(); + }); + await page.goto('http://todomvc.com'); +}); +``` + +## Resources + +* [Documentation](https://playwright.dev) +* [API reference](https://playwright.dev/docs/api/class-playwright/) +* [Contribution guide](CONTRIBUTING.md) +* [Changelog](https://github.com/microsoft/playwright/releases) diff --git a/node_modules/playwright/ThirdPartyNotices.txt b/node_modules/playwright/ThirdPartyNotices.txt new file mode 100644 index 0000000000000000000000000000000000000000..85268f9ba819b96f25963961ce07445364a88e72 --- /dev/null +++ b/node_modules/playwright/ThirdPartyNotices.txt @@ -0,0 +1,5042 @@ +microsoft/playwright + +THIRD-PARTY SOFTWARE NOTICES AND INFORMATION + +This project incorporates components from the projects listed below. The original copyright notices and the licenses under which Microsoft received such components are set forth below. Microsoft reserves all rights not expressly granted herein, whether by implication, estoppel or otherwise. + +- @ampproject/remapping@2.2.1 (https://github.com/ampproject/remapping) +- @babel/code-frame@7.27.1 (https://github.com/babel/babel) +- @babel/compat-data@7.28.0 (https://github.com/babel/babel) +- @babel/core@7.28.0 (https://github.com/babel/babel) +- @babel/generator@7.28.0 (https://github.com/babel/babel) +- @babel/helper-annotate-as-pure@7.27.3 (https://github.com/babel/babel) +- @babel/helper-compilation-targets@7.27.2 (https://github.com/babel/babel) +- @babel/helper-create-class-features-plugin@7.27.1 (https://github.com/babel/babel) +- @babel/helper-globals@7.28.0 (https://github.com/babel/babel) +- @babel/helper-member-expression-to-functions@7.27.1 (https://github.com/babel/babel) +- @babel/helper-module-imports@7.27.1 (https://github.com/babel/babel) +- @babel/helper-module-transforms@7.27.3 (https://github.com/babel/babel) +- @babel/helper-optimise-call-expression@7.27.1 (https://github.com/babel/babel) +- @babel/helper-plugin-utils@7.27.1 (https://github.com/babel/babel) +- @babel/helper-replace-supers@7.27.1 (https://github.com/babel/babel) +- @babel/helper-skip-transparent-expression-wrappers@7.27.1 (https://github.com/babel/babel) +- @babel/helper-string-parser@7.27.1 (https://github.com/babel/babel) +- @babel/helper-validator-identifier@7.27.1 (https://github.com/babel/babel) +- @babel/helper-validator-identifier@7.28.5 (https://github.com/babel/babel) +- @babel/helper-validator-option@7.27.1 (https://github.com/babel/babel) +- @babel/helpers@7.28.2 (https://github.com/babel/babel) +- @babel/parser@7.28.0 (https://github.com/babel/babel) +- @babel/plugin-proposal-decorators@7.28.0 (https://github.com/babel/babel) +- @babel/plugin-syntax-async-generators@7.8.4 (https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-async-generators) +- @babel/plugin-syntax-decorators@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-syntax-import-attributes@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-syntax-json-strings@7.8.3 (https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-json-strings) +- @babel/plugin-syntax-jsx@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-syntax-object-rest-spread@7.8.3 (https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-object-rest-spread) +- @babel/plugin-syntax-optional-catch-binding@7.8.3 (https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-optional-catch-binding) +- @babel/plugin-syntax-typescript@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-transform-class-properties@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-transform-class-static-block@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-transform-destructuring@7.28.0 (https://github.com/babel/babel) +- @babel/plugin-transform-explicit-resource-management@7.28.0 (https://github.com/babel/babel) +- @babel/plugin-transform-export-namespace-from@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-transform-logical-assignment-operators@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-transform-modules-commonjs@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-transform-nullish-coalescing-operator@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-transform-numeric-separator@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-transform-optional-chaining@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-transform-private-methods@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-transform-private-property-in-object@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-transform-react-jsx@7.27.1 (https://github.com/babel/babel) +- @babel/plugin-transform-typescript@7.28.0 (https://github.com/babel/babel) +- @babel/preset-typescript@7.27.1 (https://github.com/babel/babel) +- @babel/template@7.27.2 (https://github.com/babel/babel) +- @babel/traverse@7.28.0 (https://github.com/babel/babel) +- @babel/types@7.28.2 (https://github.com/babel/babel) +- @jest/diff-sequences@30.0.1 (https://github.com/jestjs/jest) +- @jest/expect-utils@30.2.0 (https://github.com/jestjs/jest) +- @jest/get-type@30.1.0 (https://github.com/jestjs/jest) +- @jest/pattern@30.0.1 (https://github.com/jestjs/jest) +- @jest/schemas@30.0.5 (https://github.com/jestjs/jest) +- @jest/types@30.2.0 (https://github.com/jestjs/jest) +- @jridgewell/gen-mapping@0.3.12 (https://github.com/jridgewell/sourcemaps) +- @jridgewell/resolve-uri@3.1.1 (https://github.com/jridgewell/resolve-uri) +- @jridgewell/sourcemap-codec@1.5.4 (https://github.com/jridgewell/sourcemaps) +- @jridgewell/trace-mapping@0.3.29 (https://github.com/jridgewell/sourcemaps) +- @sinclair/typebox@0.34.41 (https://github.com/sinclairzx81/typebox) +- @types/debug@4.1.12 (https://github.com/DefinitelyTyped/DefinitelyTyped) +- @types/istanbul-lib-coverage@2.0.6 (https://github.com/DefinitelyTyped/DefinitelyTyped) +- @types/istanbul-lib-report@3.0.3 (https://github.com/DefinitelyTyped/DefinitelyTyped) +- @types/istanbul-reports@3.0.4 (https://github.com/DefinitelyTyped/DefinitelyTyped) +- @types/mdast@4.0.4 (https://github.com/DefinitelyTyped/DefinitelyTyped) +- @types/ms@2.1.0 (https://github.com/DefinitelyTyped/DefinitelyTyped) +- @types/node@24.9.2 (https://github.com/DefinitelyTyped/DefinitelyTyped) +- @types/stack-utils@2.0.3 (https://github.com/DefinitelyTyped/DefinitelyTyped) +- @types/unist@3.0.3 (https://github.com/DefinitelyTyped/DefinitelyTyped) +- @types/yargs-parser@21.0.3 (https://github.com/DefinitelyTyped/DefinitelyTyped) +- @types/yargs@17.0.34 (https://github.com/DefinitelyTyped/DefinitelyTyped) +- ansi-colors@4.1.3 (https://github.com/doowb/ansi-colors) +- ansi-styles@4.3.0 (https://github.com/chalk/ansi-styles) +- ansi-styles@5.2.0 (https://github.com/chalk/ansi-styles) +- anymatch@3.1.3 (https://github.com/micromatch/anymatch) +- bail@2.0.2 (https://github.com/wooorm/bail) +- binary-extensions@2.2.0 (https://github.com/sindresorhus/binary-extensions) +- braces@3.0.3 (https://github.com/micromatch/braces) +- browserslist@4.25.1 (https://github.com/browserslist/browserslist) +- buffer-from@1.1.2 (https://github.com/LinusU/buffer-from) +- caniuse-lite@1.0.30001731 (https://github.com/browserslist/caniuse-lite) +- chalk@4.1.2 (https://github.com/chalk/chalk) +- character-entities@2.0.2 (https://github.com/wooorm/character-entities) +- chokidar@3.6.0 (https://github.com/paulmillr/chokidar) +- ci-info@4.3.1 (https://github.com/watson/ci-info) +- codemirror@5.65.18 (https://github.com/codemirror/CodeMirror) +- color-convert@2.0.1 (https://github.com/Qix-/color-convert) +- color-name@1.1.4 (https://github.com/colorjs/color-name) +- convert-source-map@2.0.0 (https://github.com/thlorenz/convert-source-map) +- debug@4.4.0 (https://github.com/debug-js/debug) +- debug@4.4.3 (https://github.com/debug-js/debug) +- decode-named-character-reference@1.2.0 (https://github.com/wooorm/decode-named-character-reference) +- dequal@2.0.3 (https://github.com/lukeed/dequal) +- devlop@1.1.0 (https://github.com/wooorm/devlop) +- electron-to-chromium@1.5.192 (https://github.com/kilian/electron-to-chromium) +- enquirer@2.3.6 (https://github.com/enquirer/enquirer) +- escalade@3.2.0 (https://github.com/lukeed/escalade) +- escape-string-regexp@2.0.0 (https://github.com/sindresorhus/escape-string-regexp) +- expect@30.2.0 (https://github.com/jestjs/jest) +- extend@3.0.2 (https://github.com/justmoon/node-extend) +- fill-range@7.1.1 (https://github.com/jonschlinkert/fill-range) +- gensync@1.0.0-beta.2 (https://github.com/loganfsmyth/gensync) +- get-east-asian-width@1.3.0 (https://github.com/sindresorhus/get-east-asian-width) +- glob-parent@5.1.2 (https://github.com/gulpjs/glob-parent) +- graceful-fs@4.2.11 (https://github.com/isaacs/node-graceful-fs) +- has-flag@4.0.0 (https://github.com/sindresorhus/has-flag) +- is-binary-path@2.1.0 (https://github.com/sindresorhus/is-binary-path) +- is-extglob@2.1.1 (https://github.com/jonschlinkert/is-extglob) +- is-glob@4.0.3 (https://github.com/micromatch/is-glob) +- is-number@7.0.0 (https://github.com/jonschlinkert/is-number) +- is-plain-obj@4.1.0 (https://github.com/sindresorhus/is-plain-obj) +- jest-diff@30.2.0 (https://github.com/jestjs/jest) +- jest-matcher-utils@30.2.0 (https://github.com/jestjs/jest) +- jest-message-util@30.2.0 (https://github.com/jestjs/jest) +- jest-mock@30.2.0 (https://github.com/jestjs/jest) +- jest-regex-util@30.0.1 (https://github.com/jestjs/jest) +- jest-util@30.2.0 (https://github.com/jestjs/jest) +- js-tokens@4.0.0 (https://github.com/lydell/js-tokens) +- jsesc@3.1.0 (https://github.com/mathiasbynens/jsesc) +- json5@2.2.3 (https://github.com/json5/json5) +- lru-cache@5.1.1 (https://github.com/isaacs/node-lru-cache) +- mdast-util-from-markdown@2.0.2 (https://github.com/syntax-tree/mdast-util-from-markdown) +- mdast-util-to-string@4.0.0 (https://github.com/syntax-tree/mdast-util-to-string) +- micromark-core-commonmark@2.0.3 (https://github.com/micromark/micromark/tree/main/packages/micromark-core-commonmark) +- micromark-factory-destination@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-factory-destination) +- micromark-factory-label@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-factory-label) +- micromark-factory-space@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-factory-space) +- micromark-factory-title@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-factory-title) +- micromark-factory-whitespace@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-factory-whitespace) +- micromark-util-character@2.1.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-util-character) +- micromark-util-chunked@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-util-chunked) +- micromark-util-classify-character@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-util-classify-character) +- micromark-util-combine-extensions@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-util-combine-extensions) +- micromark-util-decode-numeric-character-reference@2.0.2 (https://github.com/micromark/micromark/tree/main/packages/micromark-util-decode-numeric-character-reference) +- micromark-util-decode-string@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-util-decode-string) +- micromark-util-encode@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-util-encode) +- micromark-util-html-tag-name@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-util-html-tag-name) +- micromark-util-normalize-identifier@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-util-normalize-identifier) +- micromark-util-resolve-all@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-util-resolve-all) +- micromark-util-sanitize-uri@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-util-sanitize-uri) +- micromark-util-subtokenize@2.1.0 (https://github.com/micromark/micromark/tree/main/packages/micromark-util-subtokenize) +- micromark-util-symbol@2.0.1 (https://github.com/micromark/micromark/tree/main/packages/micromark-util-symbol) +- micromark-util-types@2.0.2 (https://github.com/micromark/micromark/tree/main/packages/micromark-util-types) +- micromark@4.0.2 (https://github.com/micromark/micromark/tree/main/packages/micromark) +- micromatch@4.0.8 (https://github.com/micromatch/micromatch) +- ms@2.1.3 (https://github.com/vercel/ms) +- node-releases@2.0.19 (https://github.com/chicoxyzzy/node-releases) +- normalize-path@3.0.0 (https://github.com/jonschlinkert/normalize-path) +- picocolors@1.1.1 (https://github.com/alexeyraspopov/picocolors) +- picomatch@2.3.1 (https://github.com/micromatch/picomatch) +- picomatch@4.0.3 (https://github.com/micromatch/picomatch) +- pretty-format@30.2.0 (https://github.com/jestjs/jest) +- react-is@18.3.1 (https://github.com/facebook/react) +- readdirp@3.6.0 (https://github.com/paulmillr/readdirp) +- remark-parse@11.0.0 (https://github.com/remarkjs/remark/tree/main/packages/remark-parse) +- semver@6.3.1 (https://github.com/npm/node-semver) +- slash@3.0.0 (https://github.com/sindresorhus/slash) +- source-map-support@0.5.21 (https://github.com/evanw/node-source-map-support) +- source-map@0.6.1 (https://github.com/mozilla/source-map) +- stack-utils@2.0.6 (https://github.com/tapjs/stack-utils) +- stoppable@1.1.0 (https://github.com/hunterloftis/stoppable) +- supports-color@7.2.0 (https://github.com/chalk/supports-color) +- to-regex-range@5.0.1 (https://github.com/micromatch/to-regex-range) +- trough@2.2.0 (https://github.com/wooorm/trough) +- undici-types@7.16.0 (https://github.com/nodejs/undici) +- unified@11.0.5 (https://github.com/unifiedjs/unified) +- unist-util-stringify-position@4.0.0 (https://github.com/syntax-tree/unist-util-stringify-position) +- update-browserslist-db@1.1.3 (https://github.com/browserslist/update-db) +- vfile-message@4.0.3 (https://github.com/vfile/vfile-message) +- vfile@6.0.3 (https://github.com/vfile/vfile) +- yallist@3.1.1 (https://github.com/isaacs/yallist) + +%% @ampproject/remapping@2.2.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +========================================= +END OF @ampproject/remapping@2.2.1 AND INFORMATION + +%% @babel/code-frame@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/code-frame@7.27.1 AND INFORMATION + +%% @babel/compat-data@7.28.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/compat-data@7.28.0 AND INFORMATION + +%% @babel/core@7.28.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/core@7.28.0 AND INFORMATION + +%% @babel/generator@7.28.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/generator@7.28.0 AND INFORMATION + +%% @babel/helper-annotate-as-pure@7.27.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-annotate-as-pure@7.27.3 AND INFORMATION + +%% @babel/helper-compilation-targets@7.27.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-compilation-targets@7.27.2 AND INFORMATION + +%% @babel/helper-create-class-features-plugin@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-create-class-features-plugin@7.27.1 AND INFORMATION + +%% @babel/helper-globals@7.28.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-globals@7.28.0 AND INFORMATION + +%% @babel/helper-member-expression-to-functions@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-member-expression-to-functions@7.27.1 AND INFORMATION + +%% @babel/helper-module-imports@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-module-imports@7.27.1 AND INFORMATION + +%% @babel/helper-module-transforms@7.27.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-module-transforms@7.27.3 AND INFORMATION + +%% @babel/helper-optimise-call-expression@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-optimise-call-expression@7.27.1 AND INFORMATION + +%% @babel/helper-plugin-utils@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-plugin-utils@7.27.1 AND INFORMATION + +%% @babel/helper-replace-supers@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-replace-supers@7.27.1 AND INFORMATION + +%% @babel/helper-skip-transparent-expression-wrappers@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-skip-transparent-expression-wrappers@7.27.1 AND INFORMATION + +%% @babel/helper-string-parser@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-string-parser@7.27.1 AND INFORMATION + +%% @babel/helper-validator-identifier@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-validator-identifier@7.27.1 AND INFORMATION + +%% @babel/helper-validator-identifier@7.28.5 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-validator-identifier@7.28.5 AND INFORMATION + +%% @babel/helper-validator-option@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helper-validator-option@7.27.1 AND INFORMATION + +%% @babel/helpers@7.28.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors +Copyright (c) 2014-present, Facebook, Inc. (ONLY ./src/helpers/regenerator* files) + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/helpers@7.28.2 AND INFORMATION + +%% @babel/parser@7.28.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +Copyright (C) 2012-2014 by various contributors (see AUTHORS) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF @babel/parser@7.28.0 AND INFORMATION + +%% @babel/plugin-proposal-decorators@7.28.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-proposal-decorators@7.28.0 AND INFORMATION + +%% @babel/plugin-syntax-async-generators@7.8.4 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-syntax-async-generators@7.8.4 AND INFORMATION + +%% @babel/plugin-syntax-decorators@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-syntax-decorators@7.27.1 AND INFORMATION + +%% @babel/plugin-syntax-import-attributes@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-syntax-import-attributes@7.27.1 AND INFORMATION + +%% @babel/plugin-syntax-json-strings@7.8.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-syntax-json-strings@7.8.3 AND INFORMATION + +%% @babel/plugin-syntax-jsx@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-syntax-jsx@7.27.1 AND INFORMATION + +%% @babel/plugin-syntax-object-rest-spread@7.8.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-syntax-object-rest-spread@7.8.3 AND INFORMATION + +%% @babel/plugin-syntax-optional-catch-binding@7.8.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-syntax-optional-catch-binding@7.8.3 AND INFORMATION + +%% @babel/plugin-syntax-typescript@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-syntax-typescript@7.27.1 AND INFORMATION + +%% @babel/plugin-transform-class-properties@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-transform-class-properties@7.27.1 AND INFORMATION + +%% @babel/plugin-transform-class-static-block@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-transform-class-static-block@7.27.1 AND INFORMATION + +%% @babel/plugin-transform-destructuring@7.28.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-transform-destructuring@7.28.0 AND INFORMATION + +%% @babel/plugin-transform-explicit-resource-management@7.28.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-transform-explicit-resource-management@7.28.0 AND INFORMATION + +%% @babel/plugin-transform-export-namespace-from@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-transform-export-namespace-from@7.27.1 AND INFORMATION + +%% @babel/plugin-transform-logical-assignment-operators@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-transform-logical-assignment-operators@7.27.1 AND INFORMATION + +%% @babel/plugin-transform-modules-commonjs@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-transform-modules-commonjs@7.27.1 AND INFORMATION + +%% @babel/plugin-transform-nullish-coalescing-operator@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-transform-nullish-coalescing-operator@7.27.1 AND INFORMATION + +%% @babel/plugin-transform-numeric-separator@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-transform-numeric-separator@7.27.1 AND INFORMATION + +%% @babel/plugin-transform-optional-chaining@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-transform-optional-chaining@7.27.1 AND INFORMATION + +%% @babel/plugin-transform-private-methods@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-transform-private-methods@7.27.1 AND INFORMATION + +%% @babel/plugin-transform-private-property-in-object@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-transform-private-property-in-object@7.27.1 AND INFORMATION + +%% @babel/plugin-transform-react-jsx@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-transform-react-jsx@7.27.1 AND INFORMATION + +%% @babel/plugin-transform-typescript@7.28.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/plugin-transform-typescript@7.28.0 AND INFORMATION + +%% @babel/preset-typescript@7.27.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/preset-typescript@7.27.1 AND INFORMATION + +%% @babel/template@7.27.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/template@7.27.2 AND INFORMATION + +%% @babel/traverse@7.28.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/traverse@7.28.0 AND INFORMATION + +%% @babel/types@7.28.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF @babel/types@7.28.2 AND INFORMATION + +%% @jest/diff-sequences@30.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright Contributors to the Jest project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF @jest/diff-sequences@30.0.1 AND INFORMATION + +%% @jest/expect-utils@30.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright Contributors to the Jest project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF @jest/expect-utils@30.2.0 AND INFORMATION + +%% @jest/get-type@30.1.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright Contributors to the Jest project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF @jest/get-type@30.1.0 AND INFORMATION + +%% @jest/pattern@30.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright Contributors to the Jest project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF @jest/pattern@30.0.1 AND INFORMATION + +%% @jest/schemas@30.0.5 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright Contributors to the Jest project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF @jest/schemas@30.0.5 AND INFORMATION + +%% @jest/types@30.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright Contributors to the Jest project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF @jest/types@30.2.0 AND INFORMATION + +%% @jridgewell/gen-mapping@0.3.12 NOTICES AND INFORMATION BEGIN HERE +========================================= +Copyright 2024 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF @jridgewell/gen-mapping@0.3.12 AND INFORMATION + +%% @jridgewell/resolve-uri@3.1.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +Copyright 2019 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF @jridgewell/resolve-uri@3.1.1 AND INFORMATION + +%% @jridgewell/sourcemap-codec@1.5.4 NOTICES AND INFORMATION BEGIN HERE +========================================= +Copyright 2024 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF @jridgewell/sourcemap-codec@1.5.4 AND INFORMATION + +%% @jridgewell/trace-mapping@0.3.29 NOTICES AND INFORMATION BEGIN HERE +========================================= +Copyright 2024 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF @jridgewell/trace-mapping@0.3.29 AND INFORMATION + +%% @sinclair/typebox@0.34.41 NOTICES AND INFORMATION BEGIN HERE +========================================= +TypeBox + +Json Schema Type Builder with Static Type Resolution for TypeScript + +The MIT License (MIT) + +Copyright (c) 2017-2025 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF @sinclair/typebox@0.34.41 AND INFORMATION + +%% @types/debug@4.1.12 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE +========================================= +END OF @types/debug@4.1.12 AND INFORMATION + +%% @types/istanbul-lib-coverage@2.0.6 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE +========================================= +END OF @types/istanbul-lib-coverage@2.0.6 AND INFORMATION + +%% @types/istanbul-lib-report@3.0.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE +========================================= +END OF @types/istanbul-lib-report@3.0.3 AND INFORMATION + +%% @types/istanbul-reports@3.0.4 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE +========================================= +END OF @types/istanbul-reports@3.0.4 AND INFORMATION + +%% @types/mdast@4.0.4 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE +========================================= +END OF @types/mdast@4.0.4 AND INFORMATION + +%% @types/ms@2.1.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE +========================================= +END OF @types/ms@2.1.0 AND INFORMATION + +%% @types/node@24.9.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE +========================================= +END OF @types/node@24.9.2 AND INFORMATION + +%% @types/stack-utils@2.0.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE +========================================= +END OF @types/stack-utils@2.0.3 AND INFORMATION + +%% @types/unist@3.0.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE +========================================= +END OF @types/unist@3.0.3 AND INFORMATION + +%% @types/yargs-parser@21.0.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE +========================================= +END OF @types/yargs-parser@21.0.3 AND INFORMATION + +%% @types/yargs@17.0.34 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE +========================================= +END OF @types/yargs@17.0.34 AND INFORMATION + +%% ansi-colors@4.1.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2015-present, Brian Woodward. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF ansi-colors@4.1.3 AND INFORMATION + +%% ansi-styles@4.3.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF ansi-styles@4.3.0 AND INFORMATION + +%% ansi-styles@5.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF ansi-styles@5.2.0 AND INFORMATION + +%% anymatch@3.1.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +The ISC License + +Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com) + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +========================================= +END OF anymatch@3.1.3 AND INFORMATION + +%% bail@2.0.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) 2015 Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF bail@2.0.2 AND INFORMATION + +%% binary-extensions@2.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2019 Sindre Sorhus (https://sindresorhus.com), Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF binary-extensions@2.2.0 AND INFORMATION + +%% braces@3.0.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF braces@3.0.3 AND INFORMATION + +%% browserslist@4.25.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright 2014 Andrey Sitnik and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF browserslist@4.25.1 AND INFORMATION + +%% buffer-from@1.1.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2016, 2018 Linus Unnebäck + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF buffer-from@1.1.2 AND INFORMATION + +%% caniuse-lite@1.0.30001731 NOTICES AND INFORMATION BEGIN HERE +========================================= +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. +========================================= +END OF caniuse-lite@1.0.30001731 AND INFORMATION + +%% chalk@4.1.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF chalk@4.1.2 AND INFORMATION + +%% character-entities@2.0.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) 2015 Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF character-entities@2.0.2 AND INFORMATION + +%% chokidar@3.6.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF chokidar@3.6.0 AND INFORMATION + +%% ci-info@4.3.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2016 Thomas Watson Steen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF ci-info@4.3.1 AND INFORMATION + +%% codemirror@5.65.18 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (C) 2017 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF codemirror@5.65.18 AND INFORMATION + +%% color-convert@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +Copyright (c) 2011-2016 Heather Arthur + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF color-convert@2.0.1 AND INFORMATION + +%% color-name@1.1.4 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) +Copyright (c) 2015 Dmitry Ivanov + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF color-name@1.1.4 AND INFORMATION + +%% convert-source-map@2.0.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +Copyright 2013 Thorsten Lorenz. +All rights reserved. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF convert-source-map@2.0.0 AND INFORMATION + +%% debug@4.4.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk +Copyright (c) 2018-2021 Josh Junon + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF debug@4.4.0 AND INFORMATION + +%% debug@4.4.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk +Copyright (c) 2018-2021 Josh Junon + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF debug@4.4.3 AND INFORMATION + +%% decode-named-character-reference@1.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF decode-named-character-reference@1.2.0 AND INFORMATION + +%% dequal@2.0.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) Luke Edwards (lukeed.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF dequal@2.0.3 AND INFORMATION + +%% devlop@1.1.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) 2023 Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF devlop@1.1.0 AND INFORMATION + +%% electron-to-chromium@1.5.192 NOTICES AND INFORMATION BEGIN HERE +========================================= +Copyright 2018 Kilian Valkhof + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +========================================= +END OF electron-to-chromium@1.5.192 AND INFORMATION + +%% enquirer@2.3.6 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2016-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF enquirer@2.3.6 AND INFORMATION + +%% escalade@3.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Luke Edwards (lukeed.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF escalade@3.2.0 AND INFORMATION + +%% escape-string-regexp@2.0.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF escape-string-regexp@2.0.0 AND INFORMATION + +%% expect@30.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright Contributors to the Jest project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF expect@30.2.0 AND INFORMATION + +%% extend@3.0.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2014 Stefan Thomas + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF extend@3.0.2 AND INFORMATION + +%% fill-range@7.1.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF fill-range@7.1.1 AND INFORMATION + +%% gensync@1.0.0-beta.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +Copyright 2018 Logan Smyth + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF gensync@1.0.0-beta.2 AND INFORMATION + +%% get-east-asian-width@1.3.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF get-east-asian-width@1.3.0 AND INFORMATION + +%% glob-parent@5.1.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +The ISC License + +Copyright (c) 2015, 2019 Elan Shanker + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +========================================= +END OF glob-parent@5.1.2 AND INFORMATION + +%% graceful-fs@4.2.11 NOTICES AND INFORMATION BEGIN HERE +========================================= +The ISC License + +Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +========================================= +END OF graceful-fs@4.2.11 AND INFORMATION + +%% has-flag@4.0.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF has-flag@4.0.0 AND INFORMATION + +%% is-binary-path@2.1.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2019 Sindre Sorhus (https://sindresorhus.com), Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF is-binary-path@2.1.0 AND INFORMATION + +%% is-extglob@2.1.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2014-2016, Jon Schlinkert + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF is-extglob@2.1.1 AND INFORMATION + +%% is-glob@4.0.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2014-2017, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF is-glob@4.0.3 AND INFORMATION + +%% is-number@7.0.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF is-number@7.0.0 AND INFORMATION + +%% is-plain-obj@4.1.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF is-plain-obj@4.1.0 AND INFORMATION + +%% jest-diff@30.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright Contributors to the Jest project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF jest-diff@30.2.0 AND INFORMATION + +%% jest-matcher-utils@30.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright Contributors to the Jest project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF jest-matcher-utils@30.2.0 AND INFORMATION + +%% jest-message-util@30.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright Contributors to the Jest project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF jest-message-util@30.2.0 AND INFORMATION + +%% jest-mock@30.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright Contributors to the Jest project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF jest-mock@30.2.0 AND INFORMATION + +%% jest-regex-util@30.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright Contributors to the Jest project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF jest-regex-util@30.0.1 AND INFORMATION + +%% jest-util@30.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright Contributors to the Jest project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF jest-util@30.2.0 AND INFORMATION + +%% js-tokens@4.0.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2014, 2015, 2016, 2017, 2018 Simon Lydell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF js-tokens@4.0.0 AND INFORMATION + +%% jsesc@3.1.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF jsesc@3.1.0 AND INFORMATION + +%% json5@2.2.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2012-2018 Aseem Kishore, and [others]. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +[others]: https://github.com/json5/json5/contributors +========================================= +END OF json5@2.2.3 AND INFORMATION + +%% lru-cache@5.1.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +========================================= +END OF lru-cache@5.1.1 AND INFORMATION + +%% mdast-util-from-markdown@2.0.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF mdast-util-from-markdown@2.0.2 AND INFORMATION + +%% mdast-util-to-string@4.0.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) 2015 Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF mdast-util-to-string@4.0.0 AND INFORMATION + +%% micromark-core-commonmark@2.0.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-core-commonmark@2.0.3 AND INFORMATION + +%% micromark-factory-destination@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-factory-destination@2.0.1 AND INFORMATION + +%% micromark-factory-label@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-factory-label@2.0.1 AND INFORMATION + +%% micromark-factory-space@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-factory-space@2.0.1 AND INFORMATION + +%% micromark-factory-title@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-factory-title@2.0.1 AND INFORMATION + +%% micromark-factory-whitespace@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-factory-whitespace@2.0.1 AND INFORMATION + +%% micromark-util-character@2.1.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-util-character@2.1.1 AND INFORMATION + +%% micromark-util-chunked@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-util-chunked@2.0.1 AND INFORMATION + +%% micromark-util-classify-character@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-util-classify-character@2.0.1 AND INFORMATION + +%% micromark-util-combine-extensions@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-util-combine-extensions@2.0.1 AND INFORMATION + +%% micromark-util-decode-numeric-character-reference@2.0.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-util-decode-numeric-character-reference@2.0.2 AND INFORMATION + +%% micromark-util-decode-string@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-util-decode-string@2.0.1 AND INFORMATION + +%% micromark-util-encode@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-util-encode@2.0.1 AND INFORMATION + +%% micromark-util-html-tag-name@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-util-html-tag-name@2.0.1 AND INFORMATION + +%% micromark-util-normalize-identifier@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-util-normalize-identifier@2.0.1 AND INFORMATION + +%% micromark-util-resolve-all@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-util-resolve-all@2.0.1 AND INFORMATION + +%% micromark-util-sanitize-uri@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-util-sanitize-uri@2.0.1 AND INFORMATION + +%% micromark-util-subtokenize@2.1.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-util-subtokenize@2.1.0 AND INFORMATION + +%% micromark-util-symbol@2.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-util-symbol@2.0.1 AND INFORMATION + +%% micromark-util-types@2.0.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark-util-types@2.0.2 AND INFORMATION + +%% micromark@4.0.2 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF micromark@4.0.2 AND INFORMATION + +%% micromatch@4.0.8 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF micromatch@4.0.8 AND INFORMATION + +%% ms@2.1.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2020 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF ms@2.1.3 AND INFORMATION + +%% node-releases@2.0.19 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License + +Copyright (c) 2017 Sergey Rubanov (https://github.com/chicoxyzzy) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF node-releases@2.0.19 AND INFORMATION + +%% normalize-path@3.0.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2014-2018, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF normalize-path@3.0.0 AND INFORMATION + +%% picocolors@1.1.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +ISC License + +Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +========================================= +END OF picocolors@1.1.1 AND INFORMATION + +%% picomatch@2.3.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2017-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF picomatch@2.3.1 AND INFORMATION + +%% picomatch@4.0.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2017-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF picomatch@4.0.3 AND INFORMATION + +%% pretty-format@30.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. +Copyright Contributors to the Jest project. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF pretty-format@30.2.0 AND INFORMATION + +%% react-is@18.3.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF react-is@18.3.1 AND INFORMATION + +%% readdirp@3.6.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF readdirp@3.6.0 AND INFORMATION + +%% remark-parse@11.0.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) 2014 Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF remark-parse@11.0.0 AND INFORMATION + +%% semver@6.3.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +========================================= +END OF semver@6.3.1 AND INFORMATION + +%% slash@3.0.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF slash@3.0.0 AND INFORMATION + +%% source-map-support@0.5.21 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2014 Evan Wallace + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF source-map-support@0.5.21 AND INFORMATION + +%% source-map@0.6.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +Copyright (c) 2009-2011, Mozilla Foundation and contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the names of the Mozilla Foundation nor the names of project + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +========================================= +END OF source-map@0.6.1 AND INFORMATION + +%% stack-utils@2.0.6 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2016-2022 Isaac Z. Schlueter , James Talmage (github.com/jamestalmage), and Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF stack-utils@2.0.6 AND INFORMATION + +%% stoppable@1.1.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2017 Hunter Loftis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF stoppable@1.1.0 AND INFORMATION + +%% supports-color@7.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF supports-color@7.2.0 AND INFORMATION + +%% to-regex-range@5.0.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright (c) 2015-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF to-regex-range@5.0.1 AND INFORMATION + +%% trough@2.2.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) 2016 Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF trough@2.2.0 AND INFORMATION + +%% undici-types@7.16.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +MIT License + +Copyright (c) Matteo Collina and Undici contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +========================================= +END OF undici-types@7.16.0 AND INFORMATION + +%% unified@11.0.5 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) 2015 Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF unified@11.0.5 AND INFORMATION + +%% unist-util-stringify-position@4.0.0 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) 2016 Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF unist-util-stringify-position@4.0.0 AND INFORMATION + +%% update-browserslist-db@1.1.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +The MIT License (MIT) + +Copyright 2022 Andrey Sitnik and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF update-browserslist-db@1.1.3 AND INFORMATION + +%% vfile-message@4.0.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +========================================= +END OF vfile-message@4.0.3 AND INFORMATION + +%% vfile@6.0.3 NOTICES AND INFORMATION BEGIN HERE +========================================= +(The MIT License) + +Copyright (c) 2015 Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +========================================= +END OF vfile@6.0.3 AND INFORMATION + +%% yallist@3.1.1 NOTICES AND INFORMATION BEGIN HERE +========================================= +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +========================================= +END OF yallist@3.1.1 AND INFORMATION + +SUMMARY BEGIN HERE +========================================= +Total Packages: 171 +========================================= +END OF SUMMARY \ No newline at end of file diff --git a/node_modules/playwright/cli.js b/node_modules/playwright/cli.js new file mode 100644 index 0000000000000000000000000000000000000000..5db59b62cdc8c26e1209bacbd0233e13bb949b96 --- /dev/null +++ b/node_modules/playwright/cli.js @@ -0,0 +1,19 @@ +#!/usr/bin/env node +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const { program } = require('./lib/program'); +program.parse(process.argv); diff --git a/node_modules/playwright/index.d.ts b/node_modules/playwright/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e2add353db0dee60089ae66961eb1378bacaee91 --- /dev/null +++ b/node_modules/playwright/index.d.ts @@ -0,0 +1,17 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from 'playwright-core'; diff --git a/node_modules/playwright/index.js b/node_modules/playwright/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e263df6ab1f0190497dc015c678874f0e6baf343 --- /dev/null +++ b/node_modules/playwright/index.js @@ -0,0 +1,17 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +module.exports = require('playwright-core'); diff --git a/node_modules/playwright/index.mjs b/node_modules/playwright/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c736e9d13ad09e54ee6f1fe000a9c8d8aa853f40 --- /dev/null +++ b/node_modules/playwright/index.mjs @@ -0,0 +1,18 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from 'playwright-core'; +import playwright from 'playwright-core'; +export default playwright; diff --git a/node_modules/playwright/jsx-runtime.js b/node_modules/playwright/jsx-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..ff3d79e34eb4c63207e0023f8eb1c8e4e6e3a5d6 --- /dev/null +++ b/node_modules/playwright/jsx-runtime.js @@ -0,0 +1,42 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function jsx(type, props, key) { + return { + __pw_type: 'jsx', + type, + props, + key, + }; +} + +function jsxs(type, props, key) { + return { + __pw_type: 'jsx', + type, + props, + key, + }; +} + +// this is used in <> notation +const Fragment = { __pw_jsx_fragment: true }; + +module.exports = { + Fragment, + jsx, + jsxs, +}; diff --git a/node_modules/playwright/jsx-runtime.mjs b/node_modules/playwright/jsx-runtime.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1dfd5835aa0ec2d3140f12cf485a68aa9ac5ca7a --- /dev/null +++ b/node_modules/playwright/jsx-runtime.mjs @@ -0,0 +1,21 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import jsxRuntime from './jsx-runtime.js'; + +export const jsx = jsxRuntime.jsx; +export const jsxs = jsxRuntime.jsxs; +export const Fragment = jsxRuntime.Fragment; diff --git a/node_modules/playwright/lib/agents/agentParser.js b/node_modules/playwright/lib/agents/agentParser.js new file mode 100644 index 0000000000000000000000000000000000000000..099a877a22e0dbe63f431a1e525331b1d7329686 --- /dev/null +++ b/node_modules/playwright/lib/agents/agentParser.js @@ -0,0 +1,89 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var agentParser_exports = {}; +__export(agentParser_exports, { + parseAgentSpec: () => parseAgentSpec +}); +module.exports = __toCommonJS(agentParser_exports); +var import_fs = __toESM(require("fs")); +var import_utilsBundle = require("playwright-core/lib/utilsBundle"); +async function parseAgentSpec(filePath) { + const source = await import_fs.default.promises.readFile(filePath, "utf-8"); + const { header, content } = extractYamlAndContent(source); + const { instructions, examples } = extractInstructionsAndExamples(content); + return { + ...header, + instructions, + examples + }; +} +function extractYamlAndContent(markdown) { + const lines = markdown.split("\n"); + if (lines[0] !== "---") + throw new Error("Markdown file must start with YAML front matter (---)"); + let yamlEndIndex = -1; + for (let i = 1; i < lines.length; i++) { + if (lines[i] === "---") { + yamlEndIndex = i; + break; + } + } + if (yamlEndIndex === -1) + throw new Error("YAML front matter must be closed with ---"); + const yamlLines = lines.slice(1, yamlEndIndex); + const yamlRaw = yamlLines.join("\n"); + const contentLines = lines.slice(yamlEndIndex + 1); + const content = contentLines.join("\n"); + let header; + try { + header = import_utilsBundle.yaml.parse(yamlRaw); + } catch (error) { + throw new Error(`Failed to parse YAML header: ${error.message}`); + } + if (!header.name) + throw new Error('YAML header must contain a "name" field'); + if (!header.description) + throw new Error('YAML header must contain a "description" field'); + return { header, content }; +} +function extractInstructionsAndExamples(content) { + const examples = []; + const instructions = content.split("")[0].trim(); + const exampleRegex = /([\s\S]*?)<\/example>/g; + let match; + while ((match = exampleRegex.exec(content)) !== null) { + const example = match[1].trim(); + examples.push(example.replace(/[\n]/g, " ").replace(/ +/g, " ")); + } + return { instructions, examples }; +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + parseAgentSpec +});